Changeset 27612


Ignore:
Timestamp:
02/24/23 10:55:24 (2 years ago)
Author:
jdquinn
Message:

BUG: Check size of multidimensional list differently

File:
1 edited

Legend:

Unmodified
Added
Removed
  • issm/trunk-jpl/src/m/qmu/helpers.py

    r27458 r27612  
    66
    77class struct(object):
    8     """STRUCT class definition - An empty struct that can be assigned arbitrary
     8    """struct class definition - An empty struct that can be assigned arbitrary
    99    attributes
    1010    """
     
    3636
    3737class Lstruct(list):
    38     """An empty struct that can be assigned arbitrary attributes but can also be
    39     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']
    4040
    4141    Note that 'x' returns the array and x.__dict__ will only return attributes
     
    4848
    4949    Examples:
    50 
    5150        x = Lstruct(1, 2, 3, 4) -> [1, 2, 3, 4]
    5251        x.a = 'hello'
     
    8887
    8988class 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
    9290    its fields/attributes and their corresponding values were added.
    9391
     
    9795
    9896    Example:
    99         OrderedDict:  # a bit clumsy to use and look at
     97        OrderedDict: # A bit clumsy to use and look at
    10098            x['y'] = 5
    10199
    102         OrderedStruct:  # nicer to look at, and works the same way
     100        OrderedStruct: # Nicer to look at, and works the same way
    103101            x.y = 5
    104102            OR
    105             x['y'] = 5  # supports OrderedDict-style usage
     103            x['y'] = 5 # Supports OrderedDict-style usage
    106104
    107105    Supports: len(x), str(x), for-loop iteration.
     
    115113        x = OrderedStruct('y', 5, 'z', 6)
    116114
    117     note below that the output fields as iterables are always in the same
     115    Note below that the output fields as iterables are always in the same
    118116    order as the inputs
    119117
    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 -> 5
    127     x['y'] -> 5
    128     x.z -> 6
    129     x['z'] -> 6
    130 
    131     for i in x:  # same as x.items()
    132         print i
    133      ->
    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)
    136134
    137135    Note: to access internal fields use dir(x) (input fields will be included,
     
    178176            return _v[pos]
    179177        except ValueError:
    180             # not in keys, not a valid attribute, raise error
     178            # Not in keys, not a valid attribute, raise error
    181179            raise AttributeError('Attribute "' + str(attr) + '" does not exist.')
    182180
    183181    def __getattribute__(self, attr):
    184         # re-route calls to vars(x) and x.__dict__
     182        # Re-route calls to vars(x) and x.__dict__
    185183        if attr == '__dict__':
    186184            return OrderedDict(list(self.items()))
     
    211209
    212210    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
    217214        """
    218215        newInstance = type(self)()
     
    222219
    223220    def __deepcopy__(self, memo=None):
    224         """
    225         hard copy of all attributes
     221        """hard copy of all attributes
    226222        same thing but call deepcopy recursively
    227223        technically not how it should be done,
     
    256252
    257253def 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
    261256    "empty" types)
    262257    """
    263258
    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]:
    265264        if np.size(x) == 0:
    266265            return True
    267266
    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
    269269        try:
    270270            x = np.concatenate(x)
     
    274274            if not isempty(i):
    275275                return False
    276     # the array isn't empty but is full of "empty" type objects, so return True
     276        # The array isn't empty but is full of "empty" type objects, so return True
    277277        return True
    278278
     
    282282        return True
    283283
    284     # type may not be understood by numpy, in which case it definitely is NOT NaN or infinity
     284    # Type may not be understood by NumPy, in which case it definitely is NOT NaN or infinity
    285285    try:
    286286        if np.isnan(x) or np.isinf(x):
     
    289289        pass
    290290
    291     # if all of that fails, then it is not empty
     291    # If all of the above fails, then it is not empty
    292292    return False
    293293
    294294
    295295def fieldnames(x, ignore_internals=True):
    296     """
    297     returns a list of fields of x
     296    """Returns a list of fields of x
     297
    298298    ignore_internals ignores all fieldnames starting with '_' and is True by
    299299    default
     
    308308
    309309def 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
    312312    ignore_internals ignores all fieldnames starting with '_' and is True by
    313313    default
     
    317317
    318318def 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)
    322320    """
    323321    try:
    324         a = x[:x.rindex('/')]  #path
    325         b = x[x.rindex('/') + 1:]  #full filename
    326     except ValueError:  #no path provided
     322        a = x[:x.rindex('/')] # Path
     323        b = x[x.rindex('/') + 1:] # Full filename
     324    except ValueError: # No path provided
    327325        a = ''
    328326        b = x
    329327    try:
    330         c, d = b.split('.')  #file name, extension
    331     except ValueError:  #no extension provided
     328        c, d = b.split('.') # File name, extension
     329    except ValueError: # No extension provided
    332330        return [a, b, '']
    333331    return [a, c, '.' + d]
     
    349347    result = str(args[0])
    350348    for i in range(len(args[1:])):
    351         # if last argument wasn't empty, add a '/' between it and the next argument
     349        # If last argument wasn't empty, add a '/' between it and the next argument
    352350        if len(args[i]) != 0:
    353351            result += '/' + str(args[i + 1])
     
    358356
    359357def 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
    366362    """
    367363    for line in fidi:
     
    372368
    373369def 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
    377372
    378373    filler is 0.0 by default
Note: See TracChangeset for help on using the changeset viewer.