Ejemplo n.º 1
0
    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)
Ejemplo n.º 2
0
    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)
Ejemplo n.º 3
0
    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})
Ejemplo n.º 4
0
    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))
Ejemplo n.º 5
0
    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})
Ejemplo n.º 6
0
    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)
Ejemplo n.º 7
0
 def __init__(self,mat='',sec=''):
     """Create a new properties database."""
     setMaterialDB(mat)
     setSectionDB(sec)
     Dict.__init__(self)
     self.prop = []
     self.nprop = []
     self.eprop = []
Ejemplo n.º 8
0
 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})
Ejemplo n.º 9
0
 def __init__(self):
     """Create a new properties database."""
     Dict.__init__(self)
     self.mats = MaterialDB()
     self.sect = SectionDB()
     self.prop = []
     self.nprop = []
     self.eprop = []
Ejemplo n.º 10
0
 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})
Ejemplo n.º 11
0
    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:]]
Ejemplo n.º 12
0
    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)
Ejemplo n.º 13
0
    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})
Ejemplo n.º 14
0
    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
Ejemplo n.º 15
0
    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))
Ejemplo n.º 16
0
    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)
Ejemplo n.º 17
0
 def test_init(self):
     d = Dict(a=1, b='test')
     self.assertEqual(d.a, 1)
     self.assertEqual(d.b, 'test')
Ejemplo n.º 18
0
 def test_attr(self):
     d = Dict()
     d.key = 'value'
     self.assertEqual(d.key, 'value')
Ejemplo n.º 19
0
 def test_attr(self):
     d = Dict()
     d.key = 'value'
     self.assertTrue('key' in d)
     self.assertEqual(d.key, 'value')
Ejemplo n.º 20
0
 def __init__(self,**kargs):
     """Create a new set of CanvasSettings."""
     Dict.__init__(self)
     self.reset(kargs)
Ejemplo n.º 21
0
 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
Ejemplo n.º 22
0
 def test_attrerror(self):
     d = Dict()
     with self.assertRaises(ArithmeticError):
         value = d.empty
Ejemplo n.º 23
0
	def test_attr(self):
		print('test_attr...')
		d = Dict()
		d.key = 'value'
		self.assertTrue("key" in d)
		self.assertEqual(d['key'], 'value')
Ejemplo n.º 24
0
 def test_key(self):
     d = Dict()
     d['key'] = 'value'
     self.assertEqual(d.key, 'value')
Ejemplo n.º 25
0
 def test_keyerror(self):
     d = Dict()
     with self.assertRaises(KeyError):
         value = d['empty']
Ejemplo n.º 26
0
 def test_attr(self):
     d = Dict()
     d['key'] = 'value'
     self.assertTrue('key' in d)
     self.assertEqual(d['key'], 'value')
Ejemplo n.º 27
0
	def test_key(self):
		print('test_key...')
		d = Dict()
		d['key'] = 'value'
		self.assertEqual(d.key, 'value')
Ejemplo n.º 28
0
 def test_keyerror(self):
     d = Dict()
     with self.assertRaises(AttributeError):
         value = d.empty
Ejemplo n.º 29
0
	def test_attrerror(self):
		print('test_attrerror...')
		d = Dict()
		with self.assertRaises(AttributeError):
			value = d.empty
Ejemplo n.º 30
0
    def __init__(self,data={}):
        """Initialize a database.

        The database can be initialized with a dict.
        """
        Dict.__init__(self,data)
Ejemplo n.º 31
0
	def test_keyerror(self):
		print('test_keyerror...')
		d = Dict()
		with self.assertRaises(KeyError):
			value = d['empty']
Ejemplo n.º 32
0
 def test_attrerror(self):
     d = Dict()
     with self.assertRaises(
             AttributeError):  # 通过d.empty访问不存在的key时,我们期待抛出AttributeError
         value = d.empty
Ejemplo n.º 33
0
 def __init__(self,**kargs):
     """Create a new set of CanvasSettings, possibly changing defaults."""
     Dict.__init__(self)
     self.reset(kargs)
Ejemplo n.º 34
0
 def test_keyerror(self):
     d = Dict()
     with self.assertRaises(
             KeyError
     ):  # 另一种重要的断言就是期待抛出指定类型的Error,比如通过d['empty']访问不存在的key时,断言会抛出KeyError
         value = d['empty']
Ejemplo n.º 35
0
	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))
Ejemplo n.º 36
0
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