def update(self, data={}, name=None, removeLocals=False): """Add a dictionary to the Config object. The data, if specified, should be a valid Python dict. If no name is specified, the data are added to the top dictionary and will become attributes. If a name is specified, the data are added to the named attribute, which should be a dictionary. If the name does not specify a dictionary, an empty one is created, deleting the existing attribute. If a name is specified, but no data, the effect is to add a new empty dictionary (section) with that name. If removeLocals is set, keys starting with '_' are removed from the data before updating the dictionary and not included in the config. This behaviour can be changed by setting removeLocals to false. """ if removeLocals: for k in data.keys(): if k[0] == "_": del data[k] if name: if not self.has_key(name) or not isinstance(self[name], dict): self[name] = Dict() self[name].update(data) else: Dict.update(self, data)
def __init__(self,coords,elems): """Create new model data. coords is an array with nodal coordinates elems is either a single element connectivity array, or a list of such. In a simple case, coords and elems can be the arrays obtained by ``coords, elems = F.feModel()``. This is however limited to a model where all elements have the same number of nodes. Then you can use the list of elems arrays. The 'fe' plugin has a helper function to create this list. E.g., if ``FL`` is a list of Formices (possibly with different plexitude), then ``fe.mergeModels([Fi.feModel() for Fi in FL])`` will return the (coords,elems) tuple to create the Model. The model can have node and element property numbers. """ Dict.__init__(self) if not type(elems) == list: elems = [ elems ] self.coords = Coords(coords) self.elems = [ Connectivity(e) for e in elems ] nelems = [ e.nelems() for e in self.elems ] nplex = [ e.nplex() for e in self.elems ] self.celems = cumsum([0]+nelems) GD.message("Number of nodes: %s" % self.coords.shape[0]) GD.message("Number of elements: %s" % self.celems[-1]) GD.message("Number of element groups: %s" % len(nelems)) GD.message("Number of elements per group: %s" % nelems) GD.message("Plexitude of each group: %s" % nplex)
def __init__(self,kind=None,keys=None,set=None, type='FIELD',variable='PRESELECT'): """ Create new output request. kind = None, 'NODE', or 'ELEMENT' (first character suffices) For kind=='': type = 'FIELD' or 'HISTORY' variable = 'ALL' or 'PRESELECT' For kind=='NODE' or 'ELEMENT': keys is a list of output identifiers (compatible with kind type) set is single item or a list of items, where each item is either: - a property number - a node/elem set name for which the results should be written If no set is specified, the default is 'Nall' for kind=='NODE' and 'Eall' for kind='ELEMENT' """ if kind: kind = kind[0].upper() if set is None: set = "%sall" % kind Dict.__init__(self,{'kind':kind}) if kind is not None: self.update({'keys':keys,'set':set}) else: self.update({'type':type,'variable':variable})
def __init__(self,kind,keys,set=None,output='FILE',freq=1,time=False, **kargs): """Create new result request. kind = 'NODE' or 'ELEMENT' (actually, the first character suffices) keys is a list of output identifiers (compatible with kind type) set is single item or a list of items, where each item is either: - a property number - a node/elem set name for which the results should be written If no set is specified, the default is 'Nall' for kind=='NODE' and 'Eall' for kind='ELEMENT' output is either 'FILE' (.fil) or 'PRINT' (.dat)(Standard only) freq is the output frequency in increments (0 = no output) Extra keyword arguments are available: see the writeNodeResults and writeElemResults functions for details. """ kind = kind[0].upper() if set is None: set = "%sall" % kind Dict.__init__(self,{'keys':keys,'kind':kind,'set':set,'output':output, 'freq':freq}) self.update(dict(**kargs))
def __init__(self,kind=None,keys=None,set=None,type='FIELD',variable='PRESELECT',extra='',**options): """ Create new output request. - `type`: 'FIELD' or 'HISTORY' - `kind`: None, 'NODE', or 'ELEMENT' (first character suffices) - `extra`: an extra string to be added to the command line. This allows to add Abaqus options not handled by this constructor. The string will be appended to the command line preceded by a comma. For kind=='': - `variable`: 'ALL', 'PRESELECT' or '' For kind=='NODE' or 'ELEMENT': - `keys`: a list of output identifiers (compatible with kind type) - `set`: a single item or a list of items, where each item is either a property number or a node/element set name for which the results should be written. If no set is specified, the default is 'Nall' for kind=='NODE' and 'Eall' for kind='ELEMENT' """ if 'history' in options: GD.warning("The `history` argument in an output request is deprecated.\nPlease use `type='history'` instead.") if 'numberinterval' in options: GD.warning("The `numberinterval` argument in an output request is deprecated.\nPlease use the `extra` argument instead.") if kind: kind = kind[0].upper() if set is None: set = "%sall" % kind Dict.__init__(self,{'kind':kind}) if kind is None: self.update({'type':type,'variable':variable,'extra':extra}) else: self.update({'keys':keys,'set':set})
def update(self,d,strict=True): """Update current values with the specified settings Returns the sanitized update values. """ ok = self.checkDict(d,strict) Dict.update(self,ok)
def __init__(self,mat='',sec=''): """Create a new properties database.""" setMaterialDB(mat) setSectionDB(sec) Dict.__init__(self) self.prop = [] self.nprop = [] self.eprop = []
def __init__(self,label=None,value=None): """Create a new element load. Empty by default. An element load can hold the following sub-properties: - label: the distributed load type label. - value: the magnitude of the distibuted load. """ Dict.__init__(self,{'label':label,'value':value})
def __init__(self): """Create a new properties database.""" Dict.__init__(self) self.mats = MaterialDB() self.sect = SectionDB() self.prop = [] self.nprop = [] self.eprop = []
def __init__(self,edge=-1,label=None,value=None): """Create a new element edge load. Empty by default. An element edgeload can hold the following sub-properties: - edge: the element edge number - label: the distributed load type label ('x','y','z'). - value: the magnitude of the distibuted load. """ Dict.__init__(self,{'edge':edge,'label':label,'value':value})
def __delitem__(self,key): """Allows items to be delete with del self[section/key]. """ i = key.rfind('/') if i == -1: Dict.__delitem__(self,key) else: del self[key[:i]][key[i+1:]]
def __init__(self, data={}, default=None): """Creates a new Config instance. The configuration can be initialized with a dictionary, or with a variable that can be passed to the read() function. The latter includes the name of a config file, or a multiline string holding the contents of a configuration file. """ Dict.__init__(self, default=default) if isinstance(data, dict): self.update(data) elif data: self.read(data)
def __init__(self,label=None,value=None,dir=None): """Create a new element load. Empty by default. An element load can hold the following sub-properties: - label: the distributed load type label - value: the magnitude of the distibuted load - dir: vector specifying the direction of the load """ if label == 'GRAV': if dir is None: dir = [0, 0 ,-1] if value is None: value = 9.81 Dict.__init__(self,{'label':label,'value':value,'dir':dir})
def keys(self,descend=True): """Return the keys in the config. By default this descends one level of Dicts. """ keys = Dict.keys(self) if descend: for k,v in self.iteritems(): if isinstance(v,Dict): keys += ['%s/%s' % (k,ki) for ki in v.keys()] return keys
def __init__(self,kind,keys,set=None,output='FILE',freq=1,time=False, **kargs): """Create new result request. - `kind`: 'NODE' or 'ELEMENT' (first character suffices) - `keys`: a list of output identifiers (compatible with kind type) - `set`: a single item or a list of items, where each item is either a property number or a node/element set name for which the results should be written. If no set is specified, the default is 'Nall' for kind=='NODE' and 'Eall' for kind='ELEMENT' - `output` is either ``FILE`` (for .fil output) or ``PRINT`` (for .dat output)(Abaqus/Standard only) - `freq` is the output frequency in increments (0 = no output) Extra keyword arguments are available: see the `writeNodeResults` and `writeElemResults` methods for details. """ kind = kind[0].upper() if set is None: set = "%sall" % kind Dict.__init__(self,{'keys':keys,'kind':kind,'set':set,'output':output, 'freq':freq}) self.update(dict(**kargs))
def __getitem__(self, key): """Allows items to be addressed as self[key]. This is equivalent to the Dict lookup, except that items in subsections can also be retrieved with a single key of the format section/key. While this lookup mechanism works for nested subsections, the syntax for config files allows for only one level of sections! Also beware that because of this functions, no '/' should be used inside normal keys and sections names. """ i = key.rfind("/") if i == -1: return Dict.__getitem__(self, key) else: try: return self[key[:i]][key[i + 1 :]] except KeyError: return self._default_(key)
def test_init(self): d = Dict(a=1, b='test') self.assertEqual(d.a, 1) self.assertEqual(d.b, 'test')
def test_attr(self): d = Dict() d.key = 'value' self.assertEqual(d.key, 'value')
def test_attr(self): d = Dict() d.key = 'value' self.assertTrue('key' in d) self.assertEqual(d.key, 'value')
def __init__(self,**kargs): """Create a new set of CanvasSettings.""" Dict.__init__(self) self.reset(kargs)
def test_init(self): d = Dict(a=1, b='best') self.assertEqual(d.a,1) self.assertEqual(d.b,'test') self.assertTrue(isinstance(d,dict)) pass
def test_attrerror(self): d = Dict() with self.assertRaises(ArithmeticError): value = d.empty
def test_attr(self): print('test_attr...') d = Dict() d.key = 'value' self.assertTrue("key" in d) self.assertEqual(d['key'], 'value')
def test_key(self): d = Dict() d['key'] = 'value' self.assertEqual(d.key, 'value')
def test_keyerror(self): d = Dict() with self.assertRaises(KeyError): value = d['empty']
def test_attr(self): d = Dict() d['key'] = 'value' self.assertTrue('key' in d) self.assertEqual(d['key'], 'value')
def test_key(self): print('test_key...') d = Dict() d['key'] = 'value' self.assertEqual(d.key, 'value')
def test_keyerror(self): d = Dict() with self.assertRaises(AttributeError): value = d.empty
def test_attrerror(self): print('test_attrerror...') d = Dict() with self.assertRaises(AttributeError): value = d.empty
def __init__(self,data={}): """Initialize a database. The database can be initialized with a dict. """ Dict.__init__(self,data)
def test_keyerror(self): print('test_keyerror...') d = Dict() with self.assertRaises(KeyError): value = d['empty']
def test_attrerror(self): d = Dict() with self.assertRaises( AttributeError): # 通过d.empty访问不存在的key时,我们期待抛出AttributeError value = d.empty
def __init__(self,**kargs): """Create a new set of CanvasSettings, possibly changing defaults.""" Dict.__init__(self) self.reset(kargs)
def test_keyerror(self): d = Dict() with self.assertRaises( KeyError ): # 另一种重要的断言就是期待抛出指定类型的Error,比如通过d['empty']访问不存在的key时,断言会抛出KeyError value = d['empty']
def test_init(self): print('test_init...') d = Dict(a=1,b='wxy') self.assertEqual(d.a, 1) self.assertEqual(d.b, 'wxy') self.assertTrue(isinstance(d, dict))
main() #%% import logging logging.basicConfig(level = logging.INFO) s = '0' n = int(s) logging.info('n = %d' % n) print(10 / n) $ python err.py #%% d = dict(a=1,b=2) d['a'] d = Dict(a=1,b=2) d['a'] import unittest,os os.chdir('C:/Users/pdxgs/desktop/python') from mydict import Dict class TestDict(unittest.TestCase): def test_init(self): d = Dict(a=1, b='best') self.assertEqual(d.a,1) self.assertEqual(d.b,'test') self.assertTrue(isinstance(d,dict)) pass