1919import os
2020import m8r
2121import numpy as np
22+ import subprocess
2223
2324try :
2425 import xarray as xr
@@ -40,7 +41,7 @@ def rsf_to_xarray(path, chunks = "auto"):
4041 ndim = len (shape )
4142
4243 dims = []
43- # units = []
44+ units = []
4445 coords = {}
4546 for axis in range (1 , ndim + 1 ):
4647 n = f .int (f"n{ axis } " )
@@ -49,14 +50,18 @@ def rsf_to_xarray(path, chunks = "auto"):
4950 label = f .string (f"label{ axis } " )
5051 if label == None :
5152 label = f"dim{ axis } "
52- # unit = f.string(f"unit{axis}")
53+ unit = f .string (f"unit{ axis } " )
54+ if unit == None :
55+ unit = "??"
5356
5457 coords [label ] = np .arange (n ) * d + o
5558 dims .append (label )
56- # units.append(unit)
59+ units .append (unit )
5760
5861 # data = np.asarray(f)
5962 binFile = f .string ("in" )
63+ label = f .string ("label" )
64+ unit0 = f .string ("unit" )
6065
6166 rsf_type = getattr (f , 'type' , None )
6267 if not rsf_type :
@@ -94,8 +99,15 @@ def rsf_to_xarray(path, chunks = "auto"):
9499 ds = xr .DataArray (
95100 data ,
96101 dims = dims ,
97- coords = coords
102+ coords = coords ,
98103 )
104+ if label :
105+ ds .attrs ['long_name' ] = label
106+ if unit0 :
107+ ds .attrs ['units' ] = unit0
108+
109+ for dim , unit in zip (dims , units ):
110+ ds .coords [dim ].attrs ['units' ] = unit
99111
100112 return ds
101113
@@ -126,11 +138,18 @@ def xarray_to_rsf(ds, outpath):
126138
127139 dims = ds .dims
128140 out = m8r .Output (outpath )
141+ label = ds .attrs .get ('long_name' , None )
142+ unit0 = ds .attrs .get ('units' , None )
129143
130144 # Set Type
131145 out .settype (rsf_type )
132146 out .put ("data_format" , fmt_str )
133147
148+ if label :
149+ out .put ("label" , label )
150+ if unit0 :
151+ out .put ("unit" , unit0 )
152+
134153 for i , dim in enumerate (dims , start = 1 ):
135154
136155 coord = ds .coords [dim ].values
@@ -146,7 +165,8 @@ def xarray_to_rsf(ds, outpath):
146165 out .put (f"o{ i } " , o )
147166 out .put (f"d{ i } " , d )
148167 out .put (f"label{ i } " , str (dim ))
149-
168+ out .put (f"unit{ i } " , str (ds .coords [dim ].attrs .get ('units' , '??' )))
169+
150170 out .write (data .astype (out_dtype ))
151171 out .close ()
152172
@@ -244,8 +264,10 @@ def _patched_apply(self, *srcs):
244264
245265 full_cmd = " " .join (cmd_parts )
246266
247- if os .system (full_cmd ) != 0 :
248- raise RuntimeError (f"Command failed: { full_cmd } " )
267+ result = subprocess .run (full_cmd , shell = True , stderr = subprocess .PIPE , stdout = subprocess .PIPE , universal_newlines = True )
268+
269+ if result .returncode != 0 :
270+ raise RuntimeError (f"{ full_cmd } \n { result .stderr } " )
249271
250272 if self .plot :
251273 return m8r .Vplot (out_file , temp = True )
0 commit comments