"""grd2xyz - Convert grid to data table"""importnumpyasnpimportpandasaspdfrompygmt.clibimportSessionfrompygmt.exceptionsimportGMTInvalidInputfrompygmt.helpersimport(GMTTempFile,build_arg_string,fmt_docstring,kwargs_to_strings,use_alias,)
[docs]@fmt_docstring@use_alias(R="region",V="verbose",)@kwargs_to_strings(R="sequence")defgrd2xyz(grid,format="a",**kwargs):r""" Create xyz tables from grid files. Read a binary 2-D grid files and write out xyz-triplets in ASCII [or binary] format to a standard output. Full option list at :gmt-docs:`grd2xyz.html` {aliases} Parameters ---------- grid : str or xarray.DataArray The file name of the input grid or the grid loaded as a DataArray. This is the only required parameter. format : str Determine the format the xyz data will be returned in: **a**: numpy array [Default option] **d**: pandas DataFrame **s**: string {R} {V} Returns ------- info : str A string with information about the grid. """withGMTTempFile()asoutfile:withSession()aslib:file_context=lib.virtualfile_from_data(check_kind="raster",data=grid)withfile_contextasinfile:arg_str=" ".join([infile,build_arg_string(kwargs),"->"+outfile.name])lib.call_module("grd2xyz",arg_str)result=outfile.read()ifformat=="s":returnresultdata_list=[]forstring_entryinresult.strip().split("\n"):float_entry=[]string_list=string_entry.strip().split()foriinstring_list:float_entry.append(float(i))data_list.append(float_entry)data_array=np.array(data_list)ifformat=="a":result=data_arrayelifformat=="d":result=pd.DataFrame(data_array)else:raiseGMTInvalidInput("""Must specify format as either a, d, or s.""")returnresult