Changeset 25062
- Timestamp:
- 06/18/20 00:59:31 (5 years ago)
- Location:
- issm/trunk-jpl/src/m
- Files:
-
- 2 edited
Legend:
- Unmodified
- Added
- Removed
-
issm/trunk-jpl/src/m/contrib/defleurian/netCDF/export_netCDF.py
r24808 r25062 6 6 7 7 8 def export_netCDF(md, filename): 8 def export_netCDF(md, filename): # {{{ 9 res_time = time.time() 10 debug = False 9 11 if path.exists(filename): 10 12 print('File {} allready exist'.format(filename)) … … 15 17 print(('New file name is {}'.format(newname))) 16 18 filename = newname 19 #create file and define it 17 20 NCData = Dataset(filename, 'w', format='NETCDF4') 18 21 NCData.description = 'Results for run' + md.miscellaneous.name 19 22 NCData.history = 'Created ' + time.ctime(time.time()) 20 23 # define netCDF dimensions 24 #grab time from Transient if it exists 21 25 try: 22 StepNum = np.shape(dict.values(md.results.__dict__))[1]23 except IndexError:26 StepNum = len(md.results.TransientSolution) 27 except AttributeError: #no transient so just one timestep 24 28 StepNum = 1 25 Dimension1 = NCData.createDimension('DimNum1', StepNum) # time is first26 DimDict = {len( Dimension1): 'DimNum1'}29 TimeDim = NCData.createDimension('Time', StepNum) # time is first 30 DimDict = {len(TimeDim): 'Time'} 27 31 dimindex = 1 32 UnlimDim = NCData.createDimension('Unlim', None) # unlimited dimension if needed 33 DimDict[len(UnlimDim)] = {'Inf'} 34 dimindex = 2 35 #add mesh related dimension that we know are needed 28 36 dimlist = [2, md.mesh.numberofelements, md.mesh.numberofvertices, np.shape(md.mesh.elements)[1]] 37 dimnames = ['DictDummy', 'EltNum', 'VertNum', 'VertPerElt'] 29 38 print('===Creating dimensions ===') 30 39 for i, newdim in enumerate(dimlist): 31 40 if newdim not in list(DimDict.keys()): 32 41 dimindex += 1 33 NewDim = NCData.createDimension('DimNum' + str(dimindex), newdim) 34 DimDict[len(NewDim)] = 'DimNum' + str(dimindex) 42 NewDim = NCData.createDimension(dimnames[i], newdim) 43 DimDict[len(NewDim)] = dimnames[i] 44 35 45 typelist = [bool, str, str, int, float, complex, 36 46 collections.OrderedDict, 37 47 np.int64, np.ndarray, np.float64] 48 49 # get all model classes and create respective groups 38 50 groups = dict.keys(md.__dict__) 39 # get all model classes and create respective groups40 51 print('===Creating and populating groups===') 41 52 for group in groups: 42 53 NCgroup = NCData.createGroup(str(group)) 43 # In each group gather the fields of the class54 # In each group gather the fields of the class 44 55 fields = dict.keys(md.__dict__[group].__dict__) 45 # looping on fields56 # looping on fields in each group 46 57 for field in fields: 47 58 # Special treatment for list fields … … 49 60 StdList = False 50 61 if len(md.__dict__[group].__dict__[field]) == 0: 51 StdList = True 62 StdList = True #this is an empty list 52 63 else: 64 #returns False for exotic types (typicaly results) 53 65 StdList = type(md.__dict__[group].__dict__[field][0]) in typelist 54 66 NCgroup.__setattr__('classtype', md.__dict__[group].__class__.__name__) 55 67 if StdList: # this is a standard or empty list just proceed 56 68 Var = md.__dict__[group].__dict__[field] 57 DimDict = CreateVar(NCData, Var, field, NCgroup, DimDict) 69 Var = SqueezeVar(Var) 70 if debug: 71 print("=££=creating var for {}.{}".format(group, field)) 72 DimDict, ncvar = CreateVar(NCData, Var, field, NCgroup, DimDict) 73 if ncvar is not None: 74 FillVar(ncvar, Var) 58 75 else: # this is a list of fields, specific treatment needed 76 if debug: 77 print("list of fields happens for {}.{}".format(group, field)) 59 78 Listsize = len(md.__dict__[group].__dict__[field]) 60 79 Subgroup = NCgroup.createGroup(str(field)) 61 Subgroup.__setattr__('classtype', md.__dict__[group].__dict__[field].__class__.__name__) 62 for listindex in range(0, Listsize): 63 try: 64 Listgroup = Subgroup.createGroup(str(md.__dict__[group].__dict__[field].__getitem__(listindex).__dict__['name'])) 65 except KeyError: 66 for naming in ['step']: 67 Listgroup = Subgroup.createGroup(str(md.__dict__[group].__dict__[field].__getitem__(listindex).__dict__[naming])) 68 except AttributeError: 69 Listgroup = Subgroup.createGroup(str(md.__dict__[group].__dict__[field].__class__.__name__) + str(listindex)) 70 Listgroup.__setattr__('classtype', md.__dict__[group].__dict__[field].__getitem__(listindex).__class__.__name__) 71 try: 72 subfields = dict.keys(md.__dict__[group].__dict__[field].__getitem__(listindex).__dict__) 73 except AttributeError: 74 subfields = dict.keys(md.__dict__[group].__dict__[field].__getitem__(listindex)) 75 for subfield in subfields: 76 if subfield != 'outlog': 80 try: 81 #take the class of the first element to define nc class and get the list of variables 82 Subgroup.__setattr__('classtype', md.__dict__[group].__dict__[field][0].__class__.__name__) 83 subfields = dict.keys(md.__dict__[group].__dict__[field][0].__dict__) 84 except IndexError: 85 Subgroup.__setattr__('classtype', md.__dict__[group].__dict__[field].__class__.__name__) 86 except AttributeError: 87 subfields = dict.keys(md.__dict__[group].__dict__[field].__getitem__(0)) 88 89 # for subfield in subfields: 90 # if subfield not in['errlog', 'outlog']: 91 # #first create the variable 92 # try: 93 # Var = md.__dict__[group].__dict__[field].__getitem__(0).__dict__[subfield] 94 # except AttributeError: 95 # Var = md.__dict__[group].__dict__[field].__getitem__(0)[subfield] 96 # Var = SqueezeVar(Var) 97 # #If first time we create a nc variable 98 # if Listsize == len(TimeDim): 99 # ExtraDim = 'Time' 100 # else: 101 # ExtraDim = 'Unlim' 102 # if debug: 103 # print("=$$=creating var for {}.{}.{}".format(group, field, subfield)) 104 # DimDict, ncvar = CreateVar(NCData, Var, subfield, Subgroup, DimDict, ExtraDim) 105 106 # for listindex in range(0, Listsize): 107 # try: 108 # Var = md.__dict__[group].__dict__[field].__getitem__(listindex).__dict__[subfield] 109 # except AttributeError: 110 # Var = md.__dict__[group].__dict__[field].__getitem__(listindex)[subfield] 111 # Var = SqueezeVar(Var) 112 # #and fill it up 113 # FillVar(ncvar, Var, listindex) 114 115 for subfield in subfields: 116 if subfield not in['errlog', 'outlog']: 117 try: 118 Var = md.__dict__[group].__dict__[field].__getitem__(0).__dict__[subfield] 119 except AttributeError: 120 Var = md.__dict__[group].__dict__[field].__getitem__(0)[subfield] 121 StackedVar = SqueezeVar(Var) 122 123 for listindex in range(1, Listsize): 77 124 try: 78 125 Var = md.__dict__[group].__dict__[field].__getitem__(listindex).__dict__[subfield] 79 126 except AttributeError: 80 127 Var = md.__dict__[group].__dict__[field].__getitem__(listindex)[subfield] 81 DimDict = CreateVar(NCData, Var, subfield, Listgroup, DimDict, md.__dict__[group], field, listindex) 128 Var = SqueezeVar(Var) 129 StackedVar = np.vstack((StackedVar, Var)) 130 if debug: 131 print("=$$=creating var for {}.{}.{}".format(group, field, subfield)) 132 StackedVar = SqueezeVar(StackedVar) 133 DimDict, ncvar = CreateVar(NCData, StackedVar, subfield, Subgroup, DimDict) 134 #and fill it up 135 if ncvar is not None: 136 FillVar(ncvar, StackedVar) 137 82 138 # No subgroup, we directly treat the variable 83 139 elif type(md.__dict__[group].__dict__[field]) in typelist or field == 'bamg': 84 140 NCgroup.__setattr__('classtype', md.__dict__[group].__class__.__name__) 85 141 Var = md.__dict__[group].__dict__[field] 86 DimDict = CreateVar(NCData, Var, field, NCgroup, DimDict) 142 Var = SqueezeVar(Var) 143 if debug: 144 print("====creating var for {}.{}".format(group, field)) 145 DimDict, ncvar = CreateVar(NCData, Var, field, NCgroup, DimDict) 146 if ncvar is not None: 147 FillVar(ncvar, Var) 87 148 elif md.__dict__[group].__dict__[field] is None: 88 149 print('field md.{}.{} is None'.format(group, field)) … … 92 153 NCgroup.__setattr__('classtype', md.__dict__[group].__class__.__name__) 93 154 Var = md.__dict__[group].__dict__[field].data 94 DimDict = CreateVar(NCData, Var, field, NCgroup, DimDict) 155 Var = SqueezeVar(Var) 156 if debug: 157 print("=++=creating var for {}.{}".format(group, field)) 158 DimDict, ncvar = CreateVar(NCData, Var, field, NCgroup, DimDict) 159 if ncvar is not None: 160 FillVar(ncvar, Var) 95 161 else: 96 162 NCgroup.__setattr__('classtype', str(group)) … … 99 165 subfields = dict.keys(md.__dict__[group].__dict__[field].__dict__) 100 166 for subfield in subfields: 101 if str(subfield) != 'outlog':167 if str(subfield) not in ['errlog', 'outlog']: 102 168 Var = md.__dict__[group].__dict__[field].__dict__[subfield] 103 DimDict = CreateVar(NCData, Var, subfield, Subgroup, DimDict) 169 Var = SqueezeVar(Var) 170 if debug: 171 print("+==+creating var for {}.{}.{}".format(group, field, subfield)) 172 DimDict, ncvar = CreateVar(NCData, Var, subfield, Subgroup, DimDict) 173 if ncvar is not None: 174 FillVar(ncvar, Var) 104 175 NCData.close() 105 106 #============================================================================ 176 print("export time is {}".format(time.time() - res_time)) 177 178 # }}} 179 180 181 def CreateVar(NCData, var, field, Group, DimDict, *SupDim): # {{{ 182 #================================================================= 107 183 # Define the variables 108 109 110 def CreateVar(NCData, var, field, Group, DimDict, * step_args): 184 #================================================================= 111 185 # grab type 112 186 try: 113 187 val_type = str(var.dtype) 188 if val_type.startswith('<U'): 189 val_type = 'stringarray' 114 190 except AttributeError: 115 191 val_type = type(var) … … 130 206 str: str, 131 207 dict: str} 208 132 209 # Now define and fill up variable 133 210 # treating scalar string or bool as atribute 134 211 if val_type in [str, bool]: 135 212 Group.__setattr__(str(field).swapcase(), str(var)) 213 ncvar = None 214 # numpy array of strings 215 elif val_type == "stringarray": 216 #if all strings are the same set it as an attribute 217 if all(var == var[0]): 218 Group.__setattr__(str(field).swapcase(), str(var[0])) 219 ncvar = None 220 else: 221 dimensions, DimDict = GetDim(NCData, val_shape, val_type, DimDict, val_dim) 222 ncvar = Group.createVariable(str(field), str, dimensions=dimensions, zlib=True) 136 223 # treating list as string table 137 224 elif val_type == list: 138 dimensions, DimDict = GetDim(NCData, val_shape, val_type, DimDict, val_dim) 139 # try to get the type from the first element 225 # try to get the type from the first element 140 226 try: 141 227 nctype = TypeDict[type(var[0])] 142 228 except IndexError: 143 229 nctype = str # most probably an empty list take str for that 144 ncvar = Group.createVariable(str(field), nctype, dimensions, zlib=True) 145 if val_shape == 0: 146 ncvar = [] 147 else: 148 for elt in range(0, val_shape[0]): 149 ncvar[elt] = var[elt] 230 231 if val_shape in [(), (0,), 0]: 232 ncvar = Group.createVariable(str(field), nctype, zlib=True) 233 else: 234 dimensions, DimDict = GetDim(NCData, val_shape, val_type, DimDict, val_dim) 235 ncvar = Group.createVariable(str(field), nctype, dimensions=dimensions, zlib=True) 236 # treating bool tables and dict as string tables 237 elif val_type in ['bool', collections.OrderedDict, dict]: 238 if val_shape in [(), (0,), 0]: 239 ncvar = Group.createVariable(str(field), str, zlib=True) 240 else: 241 dimensions, DimDict = GetDim(NCData, val_shape, val_type, DimDict, val_dim) 242 ncvar = Group.createVariable(str(field), str, dimensions=dimensions, zlib=True) 243 # Now dealing with numeric variables 244 elif val_type in [float, 'float64', np.float64, int, 'int64']: 245 if val_shape in [(), (0,), 0] and not SupDim: 246 ncvar = Group.createVariable(str(field), TypeDict[val_type], zlib=True) 247 else: 248 dimensions, DimDict = GetDim(NCData, val_shape, val_type, DimDict, val_dim) 249 if SupDim: 250 dimensions = SupDim + dimensions 251 ncvar = Group.createVariable(str(field), TypeDict[val_type], dimensions=dimensions, zlib=True) 252 else: 253 print(('WARNING type "{}" is unknown for "{}.{}"'.format(val_type, Group.name, field))) 254 ncvar = None 255 return DimDict, ncvar 256 # }}} 257 258 259 def FillVar(ncvar, invar, *UnlimIndex): # {{{ 260 #================================================================= 261 # Define the variables 262 #================================================================= 263 # grab type 264 try: 265 val_type = str(invar.dtype) 266 except AttributeError: 267 val_type = type(invar) 268 # grab dimension 269 if val_type in [collections.OrderedDict, dict]: 270 val_shape = len(invar) 271 else: 272 val_shape = np.shape(invar) 273 # Now fill up variable 274 # treating list as string table 275 if val_type == list: 276 if val_shape == 0: 277 ncvar = [] 278 else: 279 for elt in range(0, val_shape[0]): 280 ncvar[elt] = invar[elt] 150 281 # treating bool tables as string tables 151 282 elif val_type == 'bool': 152 dimensions, DimDict = GetDim(NCData, val_shape, val_type, DimDict, val_dim)153 ncvar = Group.createVariable(str(field), str, dimensions, zlib=True)154 283 for elt in range(0, val_shape[0]): 155 ncvar[elt] = str( var[elt])284 ncvar[elt] = str(invar[elt]) 156 285 # treating dictionaries as tables of strings 157 286 elif val_type in [collections.OrderedDict, dict]: 158 dimensions, DimDict = GetDim(NCData, val_shape, val_type, DimDict, val_dim) 159 ncvar = Group.createVariable(str(field), str, dimensions, zlib=True) 160 for elt, key in enumerate(dict.keys(var)): 287 for elt, key in enumerate(dict.keys(invar)): 161 288 ncvar[elt, 0] = key 162 ncvar[elt, 1] = str( var[key]) # converting to str to avoid potential problems289 ncvar[elt, 1] = str(invar[key]) # converting to str to avoid potential problems 163 290 # Now dealing with numeric variables 164 291 elif val_type in [float, 'float64', np.float64, int, 'int64']: 165 dimensions, DimDict = GetDim(NCData, val_shape, val_type, DimDict, val_dim)166 ncvar = Group.createVariable(str(field), TypeDict[val_type], dimensions, zlib=True)167 292 try: 168 nan_val = np.isnan( var)293 nan_val = np.isnan(invar) 169 294 if nan_val.all(): 170 n cvar[:]= 'NaN'295 naned = 'NaN' 171 296 else: 172 n cvar[:] =var297 naned = invar 173 298 except TypeError: # type does not accept nan, get vallue of the variable 174 ncvar[:] = var 175 else: 176 print(('WARNING type "{}" is unknown for "{}.{}"'.format(val_type, Group.name, field))) 177 return DimDict 178 179 180 # ============================================================================ 181 # retriev the dimension tuple from a dictionnary 182 def GetDim(NCData, val_shape, val_type, DimDict, val_dim): 299 naned = invar 300 if UnlimIndex: 301 if len(val_shape) == 0: 302 ncvar[UnlimIndex] = naned 303 elif len(val_shape) == 1: 304 ncvar[UnlimIndex, :] = naned 305 elif len(val_shape) == 2: 306 ncvar[UnlimIndex, :, :] = naned 307 elif len(val_shape) == 3: 308 ncvar[UnlimIndex, :, :, :] = naned 309 else: 310 print('WARNING: dimension not supported') 311 else: 312 ncvar[:] = naned 313 else: 314 print(('WARNING type "{}" is unknown'.format(val_type))) 315 return 316 # }}} 317 318 319 def GetDim(NCData, val_shape, val_type, DimDict, val_dim): #{{{ 320 # ============================================================================ 321 # retriev the dimension tuple from a dictionnary 322 # ============================================================================ 183 323 output = [] 184 324 if val_type in [collections.OrderedDict, dict]: # dealling with a dictionnary 185 325 try: 186 326 output = [str(DimDict[val_shape])] # first try to get the coresponding dimension if ti exists 187 output = output + [DimDict[2]] # dimension5is 2 to treat with dict327 output = output + [DimDict[2]] # DictDummy is 2 to treat with dict 188 328 except KeyError: 189 329 index = len(DimDict) + 1 # if the dimension does not exist, increment naming … … 203 343 output = output + [str(DimDict[val_shape[dim]])] 204 344 return tuple(output), DimDict 345 # }}} 346 347 348 def SqueezeVar(Var): # {{{ 349 vardim = len(np.shape(Var)) 350 if vardim > 1: 351 Var = np.squeeze(Var) 352 353 return Var 354 # }}} -
issm/trunk-jpl/src/m/io/loadvars.py
r24657 r25062 34 34 filename = '' 35 35 nvdict = {} 36 debug = False #print messages if true 36 37 37 38 if len(args) >= 1 and isinstance(args[0], str): … … 60 61 raise TypeError("Unrecognized input arguments.") 61 62 62 if whichdb(filename): 63 if whichdb(filename): #We used python pickle for the save 63 64 print("Loading variables from file {}.".format(filename)) 64 65 my_shelf = shelve.open(filename, 'r') # 'r' for read - only … … 78 79 my_shelf.close() 79 80 80 else: 81 else: #We used netcdf for the save 81 82 try: 82 83 NCFile = Dataset(filename, mode='r') … … 89 90 NCFile = Dataset(filename, mode='r') 90 91 for mod in dict.keys(classtype): 91 #print(' - Now treating classtype {}'.format(mod)) 92 #==== First we create the model structure {{{ 93 if debug: 94 print(' - Now treating classtype {}'.format(mod)) 92 95 if np.size(classtree[mod]) > 1: 96 # this points to a subclass (results.TransientSolution for example) 93 97 curclass = NCFile.groups[classtree[mod][0]].groups[classtree[mod][1]] 94 if classtype[mod][0] == 'list': 98 if debug: 99 print("now checking {} for list : {}".format(mod, classtype[mod][0] == 'list' or (classtype[mod][0] == 'results' and 'Time' in NCFile.dimensions))) 100 if classtype[mod][0] == 'list' or (classtype[mod][0] == 'results' and 'Time' in NCFile.dimensions): #We have a list of variables 95 101 keylist = [key for key in curclass.groups] 96 try: 97 steplist = [int(key) for key in curclass.groups] 98 except ValueError: 99 steplist = [int(findall(r'\d + ', key)[0]) for key in keylist] 100 indexlist = [index * (len(curclass.groups) - 1) / max(1, max(steplist)) for index in steplist] 101 listtype = curclass.groups[keylist[0]].classtype 102 if listtype == 'dict': 103 nvdict['md'].__dict__[classtree[mod][0]].__dict__[classtree[mod][1]] = [OrderedDict() for i in range(max(1, len(curclass.groups)))] 102 # this is related to the old structure of NC files where every steps of results had its own group 103 if len(keylist) > 0: 104 #this is kept for compatibility 105 #and treatment of list of dicts?? 106 try: 107 #group are named after their step 108 steplist = [int(key) for key in curclass.groups] 109 except ValueError: 110 #or a number is appended at the end of the name 111 steplist = [int(findall(r'\d + ', key)[0]) for key in keylist] 112 indexlist = [int(index * (len(curclass.groups) - 1) / max(1, max(steplist))) for index in steplist] 113 listtype = curclass.groups[keylist[0]].classtype 114 #discriminate between dict and results 115 if listtype == 'dict': 116 nvdict['md'].__dict__[classtree[mod][0]].__dict__[classtree[mod][1]] = [OrderedDict() for i in range(max(1, len(curclass.groups)))] 117 else: 118 nvdict['md'].__dict__[classtree[mod][0]].__dict__[classtree[mod][1]] = [getattr(__import__(listtype), listtype)() for i in range(max(1, len(curclass.groups)))] 119 Tree = nvdict['md'].__dict__[classtree[mod][0]].__dict__[classtree[mod][1]][:] 104 120 else: 105 nvdict['md'].__dict__[classtree[mod][0]].__dict__[classtree[mod][1]] = [getattr(__import__(listtype), listtype)() for i in range(max(1, len(curclass.groups)))] 106 Tree = nvdict['md'].__dict__[classtree[mod][0]].__dict__[classtree[mod][1]][:] 121 #that is the current treatment 122 #here we have a more NC approach with time being a dimension 123 keylist = [key for key in curclass.variables] 124 dimlist = [curclass.variables[key].dimensions for key in keylist] 125 indexlist = np.arange(0, len(NCFile.dimensions['Time'])) 126 if 'Time' in np.all(dimlist): 127 #Time dimension is in all the variables so we take that as stepnumber for the results 128 listtype = curclass.classtype 129 nvdict['md'].__dict__[classtree[mod][0]].__dict__[classtree[mod][1]] = [getattr(__import__(listtype), listtype)() for i in range(max(1, len(NCFile.dimensions['Time'])))] 130 Tree = nvdict['md'].__dict__[classtree[mod][0]].__dict__[classtree[mod][1]][:] 131 else: 132 print("ERROR: Time dimension is not in all results. That has been overlooked for now but your resulat are not saved.") 133 107 134 else: 108 135 nvdict['md'].__dict__[classtree[mod][0]].__dict__[classtree[mod][1]] = getattr(classtype[mod][1], classtype[mod][0])() … … 112 139 nvdict['md'].__dict__[mod] = getattr(classtype[mod][1], classtype[mod][0])() 113 140 Tree = nvdict['md'].__dict__[classtree[mod][0]] 114 #treating groups that are lists 141 if debug: 142 print("for {} Tree is a {}".format(mod, Tree.__class__.__name__)) 143 # }}} 144 #==== Then we populate it {{{ 115 145 for i in range(0, max(1, len(curclass.groups))): 116 146 if len(curclass.groups) > 0: … … 118 148 else: 119 149 listclass = curclass 150 #==== We deal with Variables {{{ 120 151 for var in listclass.variables: 121 #print("treating var {}".format(var)) 152 if debug: 153 print("treating var {}".format(var)) 122 154 if var not in ['errlog', 'outlog']: 123 155 varval = listclass.variables[str(var)] 124 156 vardim = varval.ndim 125 if vardim == 0: 126 if type(Tree) == list: 127 t = int(indexlist[i]) 128 if listtype == 'dict': 129 Tree[t][str(var)] = varval[0].data 130 131 else: 132 Tree[t].__dict__[str(var)] = varval[0].data 133 134 else: 135 if str(varval[0]) == '': #no value 136 Tree.__dict__[str(var)] = [] 137 138 elif varval[0] == 'True': #treatin bool 139 Tree.__dict__[str(var)] = True 140 141 elif varval[0] == 'False': #treatin bool 142 Tree.__dict__[str(var)] = False 143 144 else: 145 Tree.__dict__[str(var)] = varval[0].item() 146 elif vardim == 1: 147 if varval.dtype == str: 148 if varval.shape[0] == 1: 149 Tree.__dict__[str(var)] = [str(varval[0]), ] 150 151 elif 'True' in varval[:] or 'False' in varval[:]: 152 Tree.__dict__[str(var)] = np.asarray([V == 'True' for V in varval[:]], dtype=bool) 153 154 else: 155 Tree.__dict__[str(var)] = [str(vallue) for vallue in varval[:]] 156 157 else: 157 #There is a special treatment for results to account for its specific structure 158 #that is the new export version where time is a named dimension 159 NewFormat = 'Time' in NCFile.dimensions 160 if type(Tree) == list and NewFormat: 161 for t in indexlist: 162 if vardim == 1: 163 Tree[t].__dict__[str(var)] = varval[t].data 164 elif vardim == 2: 165 Tree[t].__dict__[str(var)] = varval[t, :].data 166 elif vardim == 3: 167 Tree[t].__dict__[str(var)] = varval[t, :, :].data 168 else: 169 print('table dimension greater than 3 not implemented yet') 170 else: 171 if vardim == 0: #that is a scalar 172 if type(Tree) == list: 173 t = indexlist[i] 174 if listtype == 'dict': 175 Tree[t][str(var)] = varval[0].data 176 else: 177 Tree[t].__dict__[str(var)] = varval[0].data 178 else: 179 if str(varval[0]) == '': #no value 180 Tree.__dict__[str(var)] = [] 181 elif varval[0] == 'True': #treatin bool 182 Tree.__dict__[str(var)] = True 183 elif varval[0] == 'False': #treatin bool 184 Tree.__dict__[str(var)] = False 185 else: 186 Tree.__dict__[str(var)] = varval[0].item() 187 188 elif vardim == 1: #that is a vector 189 if varval.dtype == str: 190 if varval.shape[0] == 1: 191 Tree.__dict__[str(var)] = [str(varval[0]), ] 192 elif 'True' in varval[:] or 'False' in varval[:]: 193 Tree.__dict__[str(var)] = np.asarray([V == 'True' for V in varval[:]], dtype=bool) 194 else: 195 Tree.__dict__[str(var)] = [str(vallue) for vallue in varval[:]] 196 else: 197 if type(Tree) == list: 198 t = indexlist[i] 199 if listtype == 'dict': 200 Tree[t][str(var)] = varval[:].data 201 else: 202 Tree[t].__dict__[str(var)] = varval[:].data 203 else: 204 try: 205 #some thing specifically require a list 206 mdtype = type(Tree.__dict__[str(var)]) 207 except KeyError: 208 mdtype = float 209 if mdtype == list: 210 Tree.__dict__[str(var)] = [mdval for mdval in varval[:]] 211 else: 212 Tree.__dict__[str(var)] = varval[:].data 213 214 elif vardim == 2: 215 #dealling with dict 216 if varval.dtype == str: #that is for toolkits wich needs to be ordered 217 if any(varval[:, 0] == 'toolkit'): #toolkit definition have to be first 218 Tree.__dict__[str(var)] = OrderedDict([('toolkit', str(varval[np.where(varval[:, 0] == 'toolkit')[0][0], 1]))]) 219 strings1 = [str(arg[0]) for arg in varval if arg[0] != 'toolkits'] 220 strings2 = [str(arg[1]) for arg in varval if arg[0] != 'toolkits'] 221 Tree.__dict__[str(var)].update(list(zip(strings1, strings2))) 222 else: 223 if type(Tree) == list: 224 t = indexlist[i] 225 if listtype == 'dict': 226 Tree[t][str(var)] = varval[:, :].data 227 else: 228 Tree[t].__dict__[str(var)] = varval[:, :].data 229 else: 230 Tree.__dict__[str(var)] = varval[:, :].data 231 elif vardim == 3: 158 232 if type(Tree) == list: 159 233 t = int(indexlist[i]) 160 234 if listtype == 'dict': 161 Tree[t][str(var)] = varval[:].data 162 163 else: 164 Tree[t].__dict__[str(var)] = varval[:].data 165 else: 166 try: 167 #some thing specifically require a list 168 mdtype = type(Tree.__dict__[str(var)]) 169 except KeyError: 170 mdtype = float 171 if mdtype == list: 172 Tree.__dict__[str(var)] = [mdval for mdval in varval[:]] 173 174 else: 175 Tree.__dict__[str(var)] = varval[:].data 176 177 elif vardim == 2: 178 #dealling with dict 179 if varval.dtype == str: #that is for toolkits wich needs to be ordered 180 if any(varval[:, 0] == 'toolkit'): #toolkit definition have to be first 181 Tree.__dict__[str(var)] = OrderedDict([('toolkit', str(varval[np.where(varval[:, 0] == 'toolkit')[0][0], 1]))]) 182 strings1 = [str(arg[0]) for arg in varval if arg[0] != 'toolkits'] 183 strings2 = [str(arg[1]) for arg in varval if arg[0] != 'toolkits'] 184 Tree.__dict__[str(var)].update(list(zip(strings1, strings2))) 235 Tree[t][str(var)] = varval[:, :, :].data 236 else: 237 Tree[t].__dict__[str(var)] = varval[:, :, :] 238 else: 239 Tree.__dict__[str(var)] = varval[:, :, :].data 185 240 else: 186 if type(Tree) == list: 187 t = int(indexlist[i]) 188 if listtype == 'dict': 189 Tree[t][str(var)] = varval[:, :].data 190 else: 191 Tree[t].__dict__[str(var)] = varval[:, :].data 192 else: 193 Tree.__dict__[str(var)] = varval[:, :].data 194 elif vardim == 3: 195 if type(Tree) == list: 196 t = int(indexlist[i]) 197 if listtype == 'dict': 198 Tree[t][str(var)] = varval[:, :, :].data 199 else: 200 Tree[t].__dict__[str(var)] = varval[:, :, :] 201 else: 202 Tree.__dict__[str(var)] = varval[:, :, :].data 203 else: 204 print('table dimension greater than 3 not implemented yet') 241 print('table dimension greater than 3 not implemented yet') 242 # }}} 243 #==== And with atribute {{{ 205 244 for attr in listclass.ncattrs(): 206 245 if attr != 'classtype': #classtype is for treatment, don't get it back … … 217 256 elif listclass.getncattr(attr) == 'False': 218 257 Tree.__dict__[str(attr).swapcase()] = False 258 # }}} 259 # }}} 219 260 NCFile.close() 220 261 if len(args) >= 2 and isinstance(args[1], str): # (value)
Note:
See TracChangeset
for help on using the changeset viewer.