Changeset 27612
- Timestamp:
- 02/24/23 10:55:24 (2 years ago)
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
issm/trunk-jpl/src/m/qmu/helpers.py
r27458 r27612 6 6 7 7 class struct(object): 8 """ STRUCTclass definition - An empty struct that can be assigned arbitrary8 """struct class definition - An empty struct that can be assigned arbitrary 9 9 attributes 10 10 """ … … 36 36 37 37 class Lstruct(list): 38 """An empty struct that can be assigned arbitrary attributes but can also be39 accesed as a list. Eg. x.y = 'hello', x[:] = ['w', 'o', 'r', 'l', 'd']38 """An empty struct that can be assigned arbitrary attributes but can also 39 be accessed as a list. Eg. x.y = 'hello', x[:] = ['w', 'o', 'r', 'l', 'd'] 40 40 41 41 Note that 'x' returns the array and x.__dict__ will only return attributes … … 48 48 49 49 Examples: 50 51 50 x = Lstruct(1, 2, 3, 4) -> [1, 2, 3, 4] 52 51 x.a = 'hello' … … 88 87 89 88 class OrderedStruct(object): 90 """ 91 A form of dictionary-like structure that maintains the ordering in which 89 """A form of dictionary-like structure that maintains the ordering in which 92 90 its fields/attributes and their corresponding values were added. 93 91 … … 97 95 98 96 Example: 99 OrderedDict: # abit clumsy to use and look at97 OrderedDict: # A bit clumsy to use and look at 100 98 x['y'] = 5 101 99 102 OrderedStruct: # nicer to look at, and works the same way100 OrderedStruct: # Nicer to look at, and works the same way 103 101 x.y = 5 104 102 OR 105 x['y'] = 5 # supports OrderedDict-style usage103 x['y'] = 5 # Supports OrderedDict-style usage 106 104 107 105 Supports: len(x), str(x), for-loop iteration. … … 115 113 x = OrderedStruct('y', 5, 'z', 6) 116 114 117 note below that the output fields as iterables are always in the same115 Note below that the output fields as iterables are always in the same 118 116 order as the inputs 119 117 120 x.keys() -> ['y', 'z']121 x.values() -> [5, 6]122 x.items() -> [('y', 6), ('z', 6)]123 x.__dict__ -> [('y', 6), ('z', 6)]124 vars(x) -> [('y', 6), ('z', 6)]125 126 x.y -> 5127 x['y'] -> 5128 x.z -> 6129 x['z'] -> 6130 131 for i in x: # same as x.items()132 print i133 ->134 ('x', 5)135 ('y', 6)118 x.keys() -> ['y', 'z'] 119 x.values() -> [5, 6] 120 x.items() -> [('y', 6), ('z', 6)] 121 x.__dict__ -> [('y', 6), ('z', 6)] 122 vars(x) -> [('y', 6), ('z', 6)] 123 124 x.y -> 5 125 x['y'] -> 5 126 x.z -> 6 127 x['z'] -> 6 128 129 for i in x: # same as x.items() 130 print i 131 -> 132 ('x', 5) 133 ('y', 6) 136 134 137 135 Note: to access internal fields use dir(x) (input fields will be included, … … 178 176 return _v[pos] 179 177 except ValueError: 180 # not in keys, not a valid attribute, raise error178 # Not in keys, not a valid attribute, raise error 181 179 raise AttributeError('Attribute "' + str(attr) + '" does not exist.') 182 180 183 181 def __getattribute__(self, attr): 184 # re-route calls to vars(x) and x.__dict__182 # Re-route calls to vars(x) and x.__dict__ 185 183 if attr == '__dict__': 186 184 return OrderedDict(list(self.items())) … … 211 209 212 210 def __copy__(self): 213 """ 214 shallow copy, hard copies of trivial attributes, 215 references to structures like lists/OrderedDicts 216 unless redefined as an entirely different structure 211 """shallow copy, hard copies of trivial attributes, references to 212 structures like lists/OrderedDicts unless redefined as an entirely 213 different structure 217 214 """ 218 215 newInstance = type(self)() … … 222 219 223 220 def __deepcopy__(self, memo=None): 224 """ 225 hard copy of all attributes 221 """hard copy of all attributes 226 222 same thing but call deepcopy recursively 227 223 technically not how it should be done, … … 256 252 257 253 def isempty(x): 258 """ 259 returns true if object is +/-infinity, NaN, None, '', has length 0, or is 260 an array/matrix composed only of such components (includes mixtures of 254 """Returns true if object is +/-infinity, NaN, None, '', has length 0, or 255 is an array/matrix composed only of such components (includes mixtures of 261 256 "empty" types) 262 257 """ 263 258 264 if type(x) in [list, np.ndarray, tuple]: 259 if type(x) is list: 260 if len(x) == 0: 261 return True 262 263 if type(x) in [np.ndarray, tuple]: 265 264 if np.size(x) == 0: 266 265 return True 267 266 268 # if anything in that array/matrix is not empty, the whole thing is not empty 267 if type(x) in [list, np.ndarray, tuple]: 268 # If anything in the array/matrix is not empty, the whole thing is not empty 269 269 try: 270 270 x = np.concatenate(x) … … 274 274 if not isempty(i): 275 275 return False 276 # the array isn't empty but is full of "empty" type objects, so return True276 # The array isn't empty but is full of "empty" type objects, so return True 277 277 return True 278 278 … … 282 282 return True 283 283 284 # type may not be understood by numpy, in which case it definitely is NOT NaN or infinity284 # Type may not be understood by NumPy, in which case it definitely is NOT NaN or infinity 285 285 try: 286 286 if np.isnan(x) or np.isinf(x): … … 289 289 pass 290 290 291 # if all of thatfails, then it is not empty291 # If all of the above fails, then it is not empty 292 292 return False 293 293 294 294 295 295 def fieldnames(x, ignore_internals=True): 296 """ 297 returns a list of fields of x 296 """Returns a list of fields of x 297 298 298 ignore_internals ignores all fieldnames starting with '_' and is True by 299 299 default … … 308 308 309 309 def isfield(x, y, ignore_internals=True): 310 """ 311 is y is a field of x? 310 """Returns True if y is a field of x 311 312 312 ignore_internals ignores all fieldnames starting with '_' and is True by 313 313 default … … 317 317 318 318 def fileparts(x): 319 """ 320 given: "path/path/.../file_name.ext" 321 returns: [path, file_name, ext] (list of strings) 319 """given: "path/path/.../file_name.ext", returns: [path, file_name, ext] (list of strings) 322 320 """ 323 321 try: 324 a = x[:x.rindex('/')] #path325 b = x[x.rindex('/') + 1:] #full filename326 except ValueError: #no path provided322 a = x[:x.rindex('/')] # Path 323 b = x[x.rindex('/') + 1:] # Full filename 324 except ValueError: # No path provided 327 325 a = '' 328 326 b = x 329 327 try: 330 c, d = b.split('.') #file name, extension331 except ValueError: #no extension provided328 c, d = b.split('.') # File name, extension 329 except ValueError: # No extension provided 332 330 return [a, b, ''] 333 331 return [a, c, '.' + d] … … 349 347 result = str(args[0]) 350 348 for i in range(len(args[1:])): 351 # if last argument wasn't empty, add a '/' between it and the next argument349 # If last argument wasn't empty, add a '/' between it and the next argument 352 350 if len(args[i]) != 0: 353 351 result += '/' + str(args[i + 1]) … … 358 356 359 357 def findline(fidi, s): 360 """ 361 returns full first line containing s (as a string), or None 362 363 Note: will include any newlines or tabs that occur in that line, 364 use str(findline(f, s)).strip() to remove these, str() in case result is 365 None 358 """returns full first line containing s (as a string), or None 359 360 Note: will include any newlines or tabs that occur in that line, use 361 str(findline(f, s)).strip() to remove these, str() in case result is None 366 362 """ 367 363 for line in fidi: … … 372 368 373 369 def empty_nd_list(shape, filler=0., as_numpy_ndarray=False): 374 """ 375 returns a python list of the size/shape given (shape must be int or tuple) 376 the list will be filled with the optional second argument 370 """Returns a python list of the size/shape given (shape must be int or 371 tuple) the list will be filled with the optional second argument 377 372 378 373 filler is 0.0 by default
Note:
See TracChangeset
for help on using the changeset viewer.