Ejemplo n.º 1
0
 def mass_excess(self, ions):
     """
     TODO:
       generally supplement by data from
          http://www.nndc.bnl.gov/masses/mass.mas12
     """
     if not is_iterable(ions):
         shape = ()
         ions = ions,
     else:
         shape = np.shape(ions)
     if not hasattr(self, '_mass_excess_data'):
         self._mass_excess_data = dict()
     me = []
     spec_ions_me = {
         isotope.ion('nt1') : 8.07131714,
         isotope.ion('h1' ) : 7.28897059,
         isotope.ion('he4') : 2.42491561,
         isotope.ion('be8') : 4.941671,
         }
     for i in ions:
         x = self._mass_excess_data.get(i, None)
         if x is None:
             try:
                 x = self.__getitem__(i).mass_excess()
             except KeyError:
                 x = spec_ions_me[isotope.ion(i)]
             self._mass_excess_data[i] = x
         me.append(x)
     if shape == ():
         return me[0]
     return np.array(me)
Ejemplo n.º 2
0
    def build_tree(self, data, tagname, attrs=None, depth=0):
        r"""Build xml tree.

        :param data: data for build xml.
        :param tagname: element tag name.
        :param attrs: element attributes. Default:``None``.
        :type attrs: dict or None
        :param depth: element depth of the hierarchy. Default:``0``.
        :type depth: int
        """
        if data is None:
            data = ''
        indent = ('\n%s' % (self.__options['indent'] * depth)) if self.__options['indent'] else ''
        if isinstance(data, utils.DictTypes):
            if self.__options['hasattr'] and self.check_structure(data.keys()):
                attrs, values = self.pickdata(data)
                self.build_tree(values, tagname, attrs, depth)
            else:
                self.__tree.append('%s%s' % (indent, self.tag_start(tagname, attrs)))
                iter = data.iteritems()
                if self.__options['ksort']:
                    iter = sorted(iter, key=lambda x:x[0], reverse=self.__options['reverse'])
                for k, v in iter:
                    attrs = {}
                    if self.__options['hasattr'] and isinstance(v, utils.DictTypes) and self.check_structure(v.keys()):
                        attrs, v = self.pickdata(v)
                    self.build_tree(v, k, attrs, depth+1)
                self.__tree.append('%s%s' % (indent, self.tag_end(tagname)))
        elif utils.is_iterable(data):
            for v in data:
                self.build_tree(v, tagname, attrs, depth)
        else:
            self.__tree.append(indent)
            data = self.safedata(data, self.__options['cdata'])
            self.__tree.append(self.build_tag(tagname, data, attrs))
Ejemplo n.º 3
0
 def font(self, value):
     if is_iterable(value):
         filename = value[0]
         font_size = value[1]
     else:
         filename = value
         font_size = DEFAULT_FONT_SIZE
     font_path = os.path.abspath(filename)
     self._image_font = ImageFont.truetype(font_path, font_size)
Ejemplo n.º 4
0
    def __setitem__(self, name, value):
        if is_iterable(name):
            base_set = self._set.intersection(
                self.transform_args_to_mishmash_set_values(*name))
        else:
            base_set = self._set.intersection(
                self.transform_args_to_mishmash_set_values(name))

        self._set = base_set
        self.__mutate(base_set, value)
Ejemplo n.º 5
0
    def __init__(self, enc_out_features):
        super(MNISTDenseClassifier2, self).__init__()

        if is_iterable(enc_out_features):
            enc_out_features = product(enc_out_features)

        self.classifier = nn.Sequential(
            nn.Linear(enc_out_features, 1000),
            nn.ReLU(),
            nn.Linear(1000, 10),
            nn.LogSoftmax(dim=1),
        )
Ejemplo n.º 6
0
 def font(self, value):
     if is_iterable(value):
         filename = value[0]
         size = value[1]
     else:
         filename = value
         size = None
     if type(filename) is not str:
         raise TypeError("Filename must be a string.")
     if type(size) not in (int, NoneType):
         raise TypeError("Size must be an integer.")
     self._init_font(filename, size)
Ejemplo n.º 7
0
 def build_post_body(self, args, kargs):
     self.parameters = {}
     
     if not self.post_data == {}:
         return
     
     post_body = []
     
     for idx, arg in enumerate(args):
         if arg is None:
             continue
         
         try:
             if not is_iterable(arg):
                 post_body.append((self.allowed_param[idx], convert_to_utf8_str(arg)))
             else:
                 self.parameters[self.allowed_param[idx]] = []
                 for value in arg:
                     post_body.append((self.allowed_param[idx], convert_to_utf8_str(value)))
                     self.parameters[self.allowed_param[idx]].append(convert_to_utf8_str(arg))
         except:
             raise MicardError('Too many parameters supplied!')
         
     for k, arg in kargs.items():
         if arg is None:
             continue
         
         if not is_iterable(arg):
             post_body.append((k, convert_to_utf8_str(arg)))
             self.parameters[k] = convert_to_utf8_str(arg)
         else:
             self.parameters[k]=[]
             for value in arg:
                 post_body.append((k,convert_to_utf8_str(value)))
                 self.parameters[k].append(convert_to_utf8_str(value))
     
     post_body.sort()
     self.post_data = post_body
Ejemplo n.º 8
0
def test_is_iterable():
    assert is_iterable([1, 2, 3])
    assert is_iterable((1, 2, 3))
    assert is_iterable('string')
    assert is_iterable(u'unicode')
    assert is_iterable({'key':'val'})
    def f():
        for i in xrange(3):
            yield i

    assert is_iterable(f())
    assert not is_iterable(123)
Ejemplo n.º 9
0
    def __init__(self, values):
        """
        `values` must be an iterable, usually a list of lists.
        """

        if not ut.is_iterable(values):
            raise TypeError("`values` must be iterable for a pascal.Array!")

        len_vals = len(values)

        if len_vals == 0:
            raise ValueError("`values` must not be empty for a pascal.Array!")

        len_first = len(values[0])

        if any(len(x) != len_first for x in values[1:]):
            raise ValueError("All iterables in `values` must be of the same length.")

        self._values = values
        self.rank = len_vals
Ejemplo n.º 10
0
    def build_tree(self, data, tagname, attrs=None, depth=0):
        r"""Build xml tree.

        :param data: data for build xml.
        :param tagname: element tag name.
        :param attrs: element attributes. Default:``None``.
        :type attrs: dict or None
        :param depth: element depth of the hierarchy. Default:``0``.
        :type depth: int
        """
        if data is None:
            data = ''
        indent = ('\n%s' % (self.__options['indent'] * depth)
                  ) if self.__options['indent'] else ''
        if isinstance(data, utils.DictTypes):
            if self.__options['hasattr'] and self.check_structure(data.keys()):
                attrs, values = self.pickdata(data)
                self.build_tree(values, tagname, attrs, depth)
            else:
                self.__tree.append('%s%s' %
                                   (indent, self.tag_start(tagname, attrs)))
                iter = data.iteritems()
                if self.__options['ksort']:
                    iter = sorted(iter,
                                  key=lambda x: x[0],
                                  reverse=self.__options['reverse'])
                for k, v in iter:
                    attrs = {}
                    if self.__options['hasattr'] and isinstance(
                            v, utils.DictTypes) and self.check_structure(
                                v.keys()):
                        attrs, v = self.pickdata(v)
                    self.build_tree(v, k, attrs, depth + 1)
                self.__tree.append('%s%s' % (indent, self.tag_end(tagname)))
        elif utils.is_iterable(data):
            for v in data:
                self.build_tree(v, tagname, attrs, depth)
        else:
            self.__tree.append(indent)
            data = self.safedata(data, self.__options['cdata'])
            self.__tree.append(self.build_tag(tagname, data, attrs))
Ejemplo n.º 11
0
 def mass_excess(self, ions):
     """
     TODO:
       generally supplement by data from
          http://www.nndc.bnl.gov/masses/mass.mas12
     """
     if not is_iterable(ions):
         shape = ()
         ions = ions,
     else:
         shape = np.shape(ions)
     if not hasattr(self, '_mass_excess_data'):
         self._mass_excess_data = dict()
     me = []
     spec_ions_me = {
         isotope.ion('nt1') : 8.07131714,
         isotope.ion('h1' ) : 7.28897059,
         isotope.ion('he4') : 2.42491561,
         isotope.ion('be8') : 4.941671,
         }
     for i in ions:
         x = self._mass_excess_data.get(i, None)
         if x is None:
             try:
                 x = self.__getitem__(i).mass_excess()
             except KeyError:
                 try:
                     x = spec_ions_me[isotope.ion(i)]
                 except KeyError:
                     x = 0
                     #print(f' [ERROR] NOT FOUND: {i} (returning {x})')
                     print(' [ERROR] NOT FOUND: {} (returning {})'.format(i,x))
             self._mass_excess_data[i] = x
         me.append(x)
     if shape == ():
         return me[0]
     return np.array(me)
Ejemplo n.º 12
0
    def actions(self, actions):
        if not is_iterable(actions):
            raise TypeError('actions must be list-like')

        self._actions = list(actions)
Ejemplo n.º 13
0
    def _construct_children_params(self,
                                   children,
                                   child_type,
                                   child_params,
                                   params,
                                   num_children=None):
        """overridden from CompoundObject. this incorporates the specified
        ShapeObject's shape into the child parameters.
        
        Parameters
        ----------
        children : list[string | list] | None
            see CompoundObject. if unspecified, the number of children will be
            determined from the specified shape.
        child_type : string | list[string] | None
            see CompoundObject
        child_params : dict | list[dict] | None
            see CompoundObject
        params : dict
            a dict of the keyword arguments passed to the ShapeObject
            constructor. this might include a 'shape' element that overrides the
            default shape.
        num_children : Number, optional
            the number of children that should be created. if unspecified,
            determined from the specified shape.
        
        Returns
        -------
        children : list[list[string, dict]]
            the children specification list
        """
        #process the shape
        shape = params.pop('shape', None)
        if shape is None:
            shape = copy(self._default_shape)
        if shape is not None:
            shape = self._attributes['shape'].coerce_value(shape)
            assert is_iterable(shape), 'shape must be iterable'

            num_shape = len(shape)

            if num_children is None:
                num_children = num_shape
            else:
                assert num_children == num_shape, 'number of children (%d) and shape length (%d) do not match' % (
                    num_children, num_shape)

        #pop the parent position out of params (so the super method doesn't give
        #the children a position based on the parent)
        if not 'position' in params:
            position = self._attributes['position']
            params['position'] = self._get_init_value(params,
                                                      position,
                                                      evaluate=False)
        parent_pos = params.pop('position')

        #parse callable positions
        if callable(parent_pos):
            if 'shape' in inspect.getargspec(parent_pos)[0]:
                parent_pos = parent_pos(self, shape=shape)
            else:
                parent_pos = parent_pos(self)

        #get the children without positions specified
        children = super(ShapeObject, self)._construct_children_params(
            children,
            child_type,
            child_params,
            params,
            num_children=num_children)

        #put position back in params
        params['position'] = parent_pos

        #parse the absolute child positions
        if shape is not None:
            #absolute shape positions
            children_pos = parent_pos + shape

            #make sure int coordinates are respected
            if isinstance(parent_pos, np.ndarray) and parent_pos.dtype == int:
                children_pos = children_pos.astype(int)

            for idx, child in enumerate(children):
                if not 'position' in child[1]:
                    child[1]['position'] = children_pos[idx]

        return children