コード例 #1
0
ファイル: LCA.py プロジェクト: max6cn/PADS
    def __init__(self,parent,pairs):
        """Set up to find LCAs of pairs in tree defined by parent.
        LCA of any given pair x,y can then be found by self[x][y].
        However unlike the online LCA structure we can not find LCAs
        of pairs that are not supplied to us at startup time.
        """

        # set up dictionary where answers get stored
        defaultdict.__init__(self,dict)
        for u,v in pairs:
            self[u][v] = self[v][u] = None

        # set up data structure for finding node ancestor on search path
        # self.descendants forms a collection of disjoint sets,
        #    one set for the descendants of each search path node.
        # self.ancestors maps disjoint set ids to the ancestors themselves.
        self.descendants = UnionFind()
        self.ancestors = {}

        # invert the parent relationship so we can traverse the tree
        self.children = defaultdict(list)
        for x,px in parent.items():
            self.children[px].append(x)
        root = [x for x in self.children if x not in parent]
        if len(root) != 1:
            raise ValueError("LCA input is not a tree")

        # initiate depth first traversal
        self.visited = set()
        self.traverse(root[0])
コード例 #2
0
ファイル: __init__.py プロジェクト: UKPLab/emnlp2015-ih-ig
 def __init__(self, item_coder_data=None, properties=None,
              boundary_types=None, boundary_format=BoundaryFormat.mass):
     '''
     Initialize a dataset.
     '''
     defaultdict.__init__(self, dict)
     self.properties = dict()
     self.boundary_format = boundary_format
     # Masses
     if item_coder_data is not None and item_coder_data is not dict:
         defaultdict.update(self, item_coder_data)
     # Properties
     if properties is not None:
         self.properties.update(properties)
     # Boundary types
     if boundary_types is not None:
         self.boundary_types = set(boundary_types)
     else:
         self.boundary_types = set([1])
     # Coders
     self.coders = set()
     # Populate coders
     for coder_masses in defaultdict.values(self):
         for coder in coder_masses.keys():
             self.coders.add(coder)
コード例 #3
0
 def __init__(self):
     defaultdict.__init__(self, dict)
     if os.path.exists(TRACE):
         with file(TRACE, "rb") as f:
             self = pickle.load(f)
             print("read in:")
             pprint(self)
コード例 #4
0
ファイル: utils.py プロジェクト: SHLo/algorithms
 def __init__(self):
     defaultdict.__init__(self, Vertex)
     self.timer = 0
     self.is_reversed = False
     self.stack = []
     self.scc_buffer = []
     self.scc_groups = []
コード例 #5
0
ファイル: msreader.py プロジェクト: saknopp/projectxl
 def __init__(self, mpp):
     defaultdict.__init__(self)
     self.task_dict = {}
     self.Task_list = []
     self.name = mpp.Name
     self.tasks = mpp.Tasks
     self.task_list = [task for task in self.tasks]
     self.task_state_dict = {}
     
     def lookup_dict(self, wbs_list):
         if wbs_list == []:
             return_dict= self
         for level in enumerate(wbs_list):
             if level[0] == 0:
                 return_dict = self[level[1]]
             elif level[0] > 0 :            
                 return_dict = return_dict[level[1]]
         return return_dict         
             
     for task in self.task_list:
         if task != None:
             wbs_list = list(map((lambda x: int(x)), task.WBS.split('.')))        
             update_dict = lookup_dict(self, wbs_list[:-1])
             new_Task = Task(task)
             update_dict[wbs_list[-1]] = new_Task
             self.task_dict[task.WBS]= new_Task
             self.task_state_dict[task.WBS] = new_Task.task_state
             self.Task_list.append(new_Task)
コード例 #6
0
    def __init__(self, _type=int):

        def nested_ddict():
            return defaultdict(nested_ddict)

        self._type = _type
        defaultdict.__init__(self, nested_ddict)
コード例 #7
0
    def __init__(self, *args, **kwargs):
        """Linearly interpolated dictionary class

        This class assumes a numeric key/value pair and will
        allow a linear interpolation between the
        all values, filling the dictionary with the results."""
        defaultdict.__init__(self)
        self.sortedkeys = None
コード例 #8
0
ファイル: model.py プロジェクト: haphi/pycarddav
    def __init__(self, ddict=''):

        if ddict == '':
            defaultdict.__init__(self, list)
        else:
            defaultdict.__init__(self, list, ddict)
        self.href = ''
        self.edited = 0
コード例 #9
0
ファイル: core.py プロジェクト: HaKDMoDz/Plex-Trakt-Scrobbler
 def __init__(self, default, *args, **kw):
     '''
     :argument default: function that can provide default values
     :param *args: iterable of keys/value pairs
     :param **kw: keyword arguments
     '''
     defaultdict.__init__(self, default)
     writestuf.update(self, *args, **kw)
コード例 #10
0
ファイル: amr_graph.py プロジェクト: Juicechuan/AMR_graph
    def __init__(self,*args, **kwargs):

        defaultdict.__init__(self,ListMap,*args,**kwargs)
        self.roots = []
        self.external_nodes = {}

        # attributes to be added
        self.node_to_concepts = {}
コード例 #11
0
ファイル: core.py プロジェクト: lcrees/stuf
 def __init__(self, default, *args, **kw):
     '''
     @param default: function that can provide default values
     @param *args: iterable of keys/value pairs
     @param **kw: keyword arguments
     '''
     defaultdict.__init__(self, default)
     directstuf.__init__(self, *args, **kw)
コード例 #12
0
 def __init__(self, value={}, factory=None):
     factory = factory or SetterDict
     defaultdict.__init__(self, factory)
     for k, v in value.items():
         if isinstance(v, Mapping):
             SetterDict.__setitem__(self, k, factory(v))
         else:
             SetterDict.__setitem__(self, k, v)
コード例 #13
0
    def __init__(self, delta):
        """
        delta is defined in seconds
        """
        start = lambda:datetime.utcfromtimestamp(0)

        self.__delta = timedelta(seconds=delta)
        self.__start = start()
        defaultdict.__init__(self, list)
コード例 #14
0
    def __init__(self, *args, **kwargs):
        """
        A Composition object stores a chemical composition of a
        substance. Basically it is a dict object, in which keys are the names
        of chemical elements and values contain integer numbers of
        corresponding atoms in a substance.

        The main improvement over dict is that Composition objects allow
        addition and subtraction.

        If ``formula`` is not specified, the constructor will look at the first
        positional argument and try to build the object from it. Without
        positional arguments, a Composition will be constructed directly from
        keyword arguments.

        Parameters
        ----------
        formula : str, optional
            A string with a chemical formula. All elements must be present in
            `mass_data`.
        mol_comp : dict, optional
            A dict with the elemental composition of the standard molecules (the
            default value is std_mol_comp).
        mass_data : dict, optional
            A dict with the masses of chemical elements (the default
            value is :py:data:`nist_mass`). It is used for formulae parsing only.
        """
        defaultdict.__init__(self, int)
        mol_comp = kwargs.get('mol_comp', std_mol_comp)
        mass_data = kwargs.get('mass_data', nist_mass)

        kw_sources = set(
            ('formula',))
        kw_given = kw_sources.intersection(kwargs)
        if len(kw_given) > 1:
            raise ChemicalCompositionError('Only one of {} can be specified!\n\
                Given: {}'.format(', '.join(kw_sources),
                                  ', '.join(kw_given)))

        elif kw_given:
            kwa = kw_given.pop()
            getattr(self, '_from_' + kwa)(kwargs[kwa],
                                          mass_data if kwa == 'formula' else mol_comp)
        # can't build from kwargs
        elif args:
            if isinstance(args[0], dict):
                self._from_dict(args[0])
            elif isinstance(args[0], str):
                try:
                    self._from_formula(args[0], mass_data)
                except ChemicalCompositionError:
                    raise ChemicalCompositionError(
                        'Could not create a Composition object from '
                        'string: "{}": not a valid sequence or '
                        'formula'.format(args[0]))
        else:
            self._from_dict(kwargs)
コード例 #15
0
 def __init__(self, type=int, *args):
   """
   :param type: type
   :param args: *
   :return:
   """
   assert issubclass(type, numbers.Real)
   DistributionTable.__init__(self)
   defaultdict.__init__(self, type, *args)
コード例 #16
0
    def __init__(self, ddict=""):

        if ddict == "":
            defaultdict.__init__(self, list)
        else:
            defaultdict.__init__(self, list, ddict)
        self.href = ""
        self.account = ""
        self.etag = ""
        self.edited = 0
コード例 #17
0
 def __init__(self,groups):
     defaultdict.__init__(self,dict)
     for g in groups:
         for i in xrange(len(g)):
             for j in xrange( i+1 ,len(g)):
                 pdb_i = g[i]
                 pdb_j = g[j]
                 self[pdb_i][pdb_j] = 1
                 self[pdb_j][pdb_i] = 1
     self.pdbs = [pdb for g in groups for pdb in g]
コード例 #18
0
ファイル: amr_graph.py プロジェクト: masterkeywikz/seq2graph
    def __init__(self,*args, **kwargs):

        defaultdict.__init__(self,ListMap,*args,**kwargs)
        self.roots = []
        self.external_nodes = {}

        # attributes to be added
        self.node_to_concepts = {}
        self.align_to_sentence = None

        self.reentrance_triples = []
コード例 #19
0
ファイル: rule.py プロジェクト: rupenp/transforest
    def __init__(self, rulefilename):
        '''read in rules from a file'''
        defaultdict.__init__(self, list) # N.B. superclass
        self.ruleid = 0
        print >> logs, "reading rules from %s ..." % rulefilename

        ## YY new switch
        if isinstance(rulefilename, str):
           self.add_rulefromfile(rulefilename)
        else: # list/iterator   
           self.from_strlist(rulefilename)
コード例 #20
0
ファイル: graph.py プロジェクト: spacenut/cs585
 def __init__(self, default_factory=None):
     """
     :param default_factory: unused
     :return:
     """
     defaultdict.__init__(self, default_freq_dict)
     self._sid_gen = SkolemKeyGenerator()
     self._sk = defaultdict(self._sid_gen.next)
     self._sids = {}
     self._skolem(ROOT)
     self._pos = set()
コード例 #21
0
ファイル: dag.py プロジェクト: christianbuck/nlu
    def __init__(self, *args, **kwargs):
        defaultdict.__init__(self, ListMap, *args, **kwargs) 
        self.roots = []
        self.external_nodes = [] 
        self.replace_count = 0    # Count how many replacements have occured in this DAG
                                  # to prefix unique new node IDs for glued fragments.

        self.__cached_triples = None
        self.__cached_depth = None

        self.node_alignments = {} 
        self.edge_alignments = {}
コード例 #22
0
ファイル: log.py プロジェクト: piergiaj/generate-image
 def __init__(self, uuid=None):
     defaultdict.__init__(self, dict)
     self.status = {}
     if uuid is None:
         self.uuid = uuid4()
         self.status.update({
             'iterations_done': 0,
             'epochs_done': 0,
             '_epoch_ends':[],
             'resumed_from': None
         })
     else:
         self.uuid = uuid
コード例 #23
0
ファイル: metaDict.py プロジェクト: burgerdev/lazyflow
    def __init__(self, other=None, *args, **kwargs):
        if other is None:
            defaultdict.__init__(self, lambda: None, **kwargs)
        else:
            defaultdict.__init__(self, lambda: None, other, **kwargs)

        if not '_ready' in self:
            # flag that indicates whether all dependencies of the slot
            # are ready
            self._ready = False

        # flag that indicates whether any piece of meta information
        # changed since this flag was reset
        self._dirty = True
コード例 #24
0
ファイル: dok_matrix.py プロジェクト: satomacoto/wordcolony
 def __init__(self, arg1=None, axis=0):
     '''
     arg1 : {(a,b):1,...} or {a:{b:1},...}
     '''
     defaultdict.__init__(self,float)
     
     if isinstance(arg1,dict):
         try:
             if len(arg1.keys()[0]) == 2:
                 self.update(arg1)
             elif isinstance(arg1.values()[0], dict):
                 self.update(dok_matrix.setvecs(arg1,axis))
         except:
             raise TypeError('invalid input format')
コード例 #25
0
    def __init__(self, *param, **named_param):
        """
        Takes one or two parameters
            1) int, [TYPE]
            1) dict
        """
        if not len(param):
            self.factory = nested_dict
            defaultdict.__init__(self, self.factory)
            return

        if len(param) == 1:
            # int = level
            if isinstance(param[0], int):
                self.factory = _nested_levels(param[0], any_type())
                defaultdict.__init__(self, self.factory)
                return
            # existing dict
            if isinstance(param[0], dict):
                self.factory = nested_dict
                defaultdict.__init__(self, self.factory)
                nested_dict_from_dict(param[0], self)
                return

        if len(param) == 2:
            if isinstance(param[0], int):
                self.factory = _nested_levels(*param)
                defaultdict.__init__(self, self.factory)
                return

        raise Exception("nested_dict should be initialised with either "
                        "1) the number of nested levels and an optional type, or "
                        "2) an existing dict to be converted into a nested dict "
                        "(factory = %s. len(param) = %d, param = %s" % (factory, len(param), param))
コード例 #26
0
ファイル: util.py プロジェクト: gitzain/project-x
    def __init__(self, strings=None):
        """Builds a Trie object, which is built around a ``defaultdict``
        
        If ``strings`` is provided, it will add the ``strings``, which
        consist of a ``list`` of ``strings``, to the Trie. 
        Otherwise, it'll construct an empty Trie.

        :param strings: List of strings to insert into the trie 
            (Default is ``None``)
        :type strings: list(str)

        """
        defaultdict.__init__(self, Trie)
        if strings:
            for string in strings:
                self.insert(string)
コード例 #27
0
ファイル: metrics.py プロジェクト: Avidereta/AgentNet
    def __init__(self):
        """
        An auxiliary class used to store and plot several [time-related] metrics on a single plot

        Example usage:
        >>> mm = Metrics()
        >>> mm["y"][0] = 1
        >>> mm["y"][1] = 2
        >>> mm["z"][0] = 2
        >>> mm["z"][1] = 1.5
        >>> mm["z"][2.5] = 1.4
        >>> plt.figure(figsize=[10, 10])
        >>> mm.plot()
        >>> plt.show()
        """
        defaultdict.__init__(self, dict)
コード例 #28
0
    def __init__(self, nd = 16, ds = None, flat = False):
        self.nd = nd
        self.flat = flat
        self._spatial = not flat
        self.ActiveDimensions = [nd,nd,nd]
        self.shape = tuple(self.ActiveDimensions)
        self.size = np.prod(self.ActiveDimensions)
        self.LeftEdge = [0.0, 0.0, 0.0]
        self.RightEdge = [1.0, 1.0, 1.0]
        self.dds = np.ones(3, "float64")
        class fake_dataset(defaultdict):
            pass

        if ds is None:
            # required attrs
            ds = fake_dataset(lambda: 1)
            ds["Massarr"] = np.ones(6)
            ds.current_redshift = ds.omega_lambda = ds.omega_matter = \
                ds.cosmological_simulation = 0.0
            ds.gamma = 5./3.0
            ds.hubble_constant = 0.7
            ds.domain_left_edge = np.zeros(3, 'float64')
            ds.domain_right_edge = np.ones(3, 'float64')
            ds.dimensionality = 3
            ds.periodicity = (True, True, True)
        self.ds = ds

        class fake_index(object):
            class fake_io(object):
                def _read_data_set(io_self, data, field):
                    return self._read_data(field)
                _read_exception = RuntimeError
            io = fake_io()
            def get_smallest_dx(self):
                return 1.0

        self.index = fake_index()
        self.requested = []
        self.requested_parameters = []
        if not self.flat:
            defaultdict.__init__(self,
                lambda: np.ones((nd, nd, nd), dtype='float64')
                + 1e-4*np.random.random((nd, nd, nd)))
        else:
            defaultdict.__init__(self,
                lambda: np.ones((nd * nd * nd), dtype='float64')
                + 1e-4*np.random.random((nd * nd * nd)))
コード例 #29
0
ファイル: stcutils.py プロジェクト: re-born/stc
    def __init__(self, file_path):
        defaultdict.__init__(self, dict)
        self.src = file_path

        if not os.path.isfile(file_path):
            return

        f = open(file_path)
        lines = f.readlines()
        f.close()

        for line in lines:
            data = line.replace("\n", "").split("\t")
            input_id = data[0]
            output_id = data[1]
            labels = data[2:]
            self[input_id][output_id] = labels
コード例 #30
0
ファイル: msreader.py プロジェクト: saknopp/projectxl
 def __init__(self, task):
     defaultdict.__init__(self)
     self.task = task
     self.wbs_list = list(map((lambda x: int(x)), self.task.WBS.split('.')))
     self.status_override = self.task.Text5
     if self.status_override == '':
         self.status_override = 'N/A'
     self.recovery_plan = self.task.Text6
     self.action = 'N/A'
     if ':' in task.Name:
         test_action = self.task.Name.split(':')[0]
         if test_action[:2] in ['IC', 'CA', 'PA', 'RM']:
             self.action = test_action
     self.task_state = TaskState(wbs_list=self.wbs_list, action=self.action, name=self.task.Name, \
     has_subtask = self.has_subtask(), start=convert_date(self.task.Start), finish=convert_date(self.task.Finish), due_date=convert_date(self.get_due_date()), \
     percent_complete=self.task.PercentComplete, status=self.status(), status_override=self.status_override, \
     recovery_plan=self.recovery_plan)
コード例 #31
0
ファイル: __init__.py プロジェクト: gappyp/autodif
 def __init__(self, default_factory, *args, **kwargs):
     super(AttrDict, self).__init__(*args, **kwargs)
     defaultdict.__init__(self, default_factory)
     self.__exclude_keys__ |= {'default_factory', '_ipython_display_'}
コード例 #32
0
 def __init__(self, *args, **kwargs):
     defaultdict.__init__(self, *args, **kwargs)
コード例 #33
0
ファイル: game.py プロジェクト: kevinmandich/Persian
    def __init__(self, territories):

        defaultdict.__init__(self, dict)
        self.territories = territories
        self.create()
コード例 #34
0
ファイル: bolig.py プロジェクト: Proteusiq/bolig_visual
 def __init__(self, *p_arg, **n_arg):
     defaultdict.__init__(self, *p_arg, **n_arg)
     self._lock = threading.Lock()
コード例 #35
0
ファイル: events.py プロジェクト: dnouri/Kotti
 def __init__(self, *args, **kwargs):
     defaultdict.__init__(self, list)
     OrderedDict.__init__(self, *args, **kwargs)
コード例 #36
0
 def __init__(self):
     defaultdict.__init__(self, int)
コード例 #37
0
 def __init__(self, seq=None):
     defaultdict.__init__(self, default_factory)
     if seq:
         self.update(seq)
コード例 #38
0
 def __init__(self):
     defaultdict.__init__(self, Resolution)
コード例 #39
0
ファイル: mappings.py プロジェクト: Arusekk/snakeoil
 def __init__(self, default_factory):
     # we have our own init to explicitly force via prototype
     # that a default_factory is required
     defaultdict.__init__(self, default_factory)
コード例 #40
0
 def __init__(self):
     defaultdict.__init__(self, timedelta)
コード例 #41
0
ファイル: _planelog.py プロジェクト: tatawang/pseudonetcdf
 def __init__(self, default_factory, unitdict):
     defaultdict.__init__(self, default_factory)
     self._unitdict = unitdict
コード例 #42
0
ファイル: Observer.py プロジェクト: sagodiz/SonarQube-plug-in
 def __init__(self):
     defaultdict.__init__(self, object)
コード例 #43
0
 def __init__(self, pairs):
     defaultdict.__init__(self, list)
     for key, value in pairs:
         self[key].append(value)
コード例 #44
0
ファイル: path.py プロジェクト: nvrivera/genome_runner
	def __init__(self):
		defaultdict.__init__(self, PathNode)
		self.files = []
		self.organisms = []
コード例 #45
0
ファイル: txn.py プロジェクト: giuliano52/gramps
    def __init__(self, msg, grampsdb, batch=False, **kwargs):
        """
        Create a new transaction.

        The grampsdb should have transaction_begin/commit/abort methods, and
        a get_undodb method to store undo actions.

        A Transaction instance can be created directly, but it is advised to
        use a context to do this. Like this the user must not worry about
        calling the transaction_xx methods on the database.

        The grampsdb parameter is a reference to the DbWrite object to which
        this transaction will be applied.
        grampsdb.get_undodb() should return a list-like interface that
        stores the commit data. This could be a simple list, or a RECNO-style
        database object.

        The data structure used to handle the transactions (see the add method)
        is a Python dictionary where:

        key = (object type, transaction type) where:
            object type = the numeric type of an object. These are
                          defined as PERSON_KEY = 0, FAMILY_KEY = 1, etc.
                          as imported from dbconst.
            transaction type = a numeric representation of the type of
                          transaction: TXNADD = 0, TXNUPD = 1, TXNDEL = 2

        data = Python list where:
            list element = (handle, data) where:
                handle = handle (database key) of the object in the transaction
                data = pickled representation of the object
        """

        # Conditional on __debug__ because all that frame stuff may be slow
        if __debug__:
            caller_frame = inspect.stack()[1]
            # If the call comes from gramps.gen.db.generic.DbGenericTxn.__init__
            # then it is just a dummy redirect, so we need to go back another
            # frame to get any real information. The test does not accurately
            # check this, but seems to be good enough for the current diagnostic
            # purposes.
            if os.path.split(caller_frame[1])[1] == "generic.py" and \
               caller_frame[3] == "__init__":
                caller_frame = inspect.stack()[2]
            _LOG.debug(
                "%sDbTxn %s instantiated for '%s'. Called from file %s, "
                "line %s, in %s" %
                (("Batch " if batch else "", ) + (hex(id(self)), ) + (msg, ) +
                 (os.path.split(caller_frame[1])[1], ) +
                 (tuple(caller_frame[i] for i in range(2, 4)))))
        defaultdict.__init__(self, list, {})

        self.msg = msg
        self.commitdb = grampsdb.get_undodb()
        self.db = grampsdb
        self.batch = batch
        for key, value in kwargs.items():
            setattr(self, key, value)
        self.first = None
        self.last = None
        self.timestamp = 0
コード例 #46
0
ファイル: field_detector.py プロジェクト: ruithnadsteud/yt
    def __init__(self, nd=16, ds=None, flat=False, field_parameters=None):
        self.nd = nd
        self.flat = flat
        self._spatial = not flat
        self.ActiveDimensions = [nd, nd, nd]
        self.shape = tuple(self.ActiveDimensions)
        self.size = np.prod(self.ActiveDimensions)
        self.LeftEdge = [0.0, 0.0, 0.0]
        self.RightEdge = [1.0, 1.0, 1.0]
        self.dds = np.ones(3, "float64")
        if field_parameters is None:
            self.field_parameters = {}
        else:
            self.field_parameters = field_parameters

        class fake_dataset(defaultdict):
            pass

        if ds is None:
            # required attrs
            ds = fake_dataset(lambda: 1)
            ds["Massarr"] = np.ones(6)
            ds.current_redshift = 0.0
            ds.omega_lambda = 0.0
            ds.omega_matter = 0.0
            ds.cosmological_simulation = 0
            ds.gamma = 5.0 / 3.0
            ds.hubble_constant = 0.7
            ds.domain_left_edge = np.zeros(3, "float64")
            ds.domain_right_edge = np.ones(3, "float64")
            ds.dimensionality = 3
            ds.force_periodicity()
        self.ds = ds

        class fake_index:
            class fake_io:
                def _read_data_set(io_self, data, field):
                    return self._read_data(field)

                _read_exception = RuntimeError

            io = fake_io()

            def get_smallest_dx(self):
                return 1.0

        self.index = fake_index()
        self.requested = []
        self.requested_parameters = []
        if not self.flat:
            defaultdict.__init__(
                self,
                lambda: np.ones((nd, nd, nd), dtype="float64")
                + 1e-4 * np.random.random((nd, nd, nd)),
            )
        else:
            defaultdict.__init__(
                self,
                lambda: np.ones((nd * nd * nd), dtype="float64")
                + 1e-4 * np.random.random(nd * nd * nd),
            )
コード例 #47
0
    def __init__(self):
        defaultdict.__init__(self, dict)

        # default_image and vars_dir attributes should be set from outside
        self.default_image = None
        self.vars_dir = None
コード例 #48
0
 def __init__(self, data_source, default_factory=None):
     self.data_source = data_source
     return defaultdict.__init__(self, default_factory)
コード例 #49
0
ファイル: dependency.py プロジェクト: xaniasd/dagster
 def __init__(self):
     defaultdict.__init__(self, list)
コード例 #50
0
ファイル: workflow.py プロジェクト: vmarkovtsev/veles
 def __init__(self, default_factory=list, *items, **kwargs):
     OrderedDict.__init__(self, *items, **kwargs)
     defaultdict.__init__(self, default_factory)
コード例 #51
0
    def __init__(self, *args, **kwargs):
        """
        A Composition object stores a chemical composition of a
        substance. Basically it is a dict object, in which keys are the names
        of chemical elements and values contain integer numbers of
        corresponding atoms in a substance.

        The main improvement over dict is that Composition objects allow
        addition and subtraction.

        A Composition object can be initialized with one of the
        following arguments: formula, sequence, parsed_sequence or
        split_sequence.

        If none of these are specified, the constructor will look at the first
        positional argument and try to build the object from it. Without
        positional arguments, a Composition will be constructed directly from
        keyword arguments.

        If there's an ambiguity, i.e. the argument is both a valid sequence
        and a formula (such as 'HCN'), it will be treated as a sequence. You
        need to provide the 'formula' keyword to override this.

        .. warning::

            Be careful when supplying a list with a parsed sequence or a split
            sequence as a keyword argument. It must be
            obtained with enabled `show_unmodified_termini` option.
            When supplying it as a positional argument, the option doesn't
            matter, because the positional argument is always converted to
            a sequence prior to any processing.

        Parameters
        ----------
        formula : str, optional
            A string with a chemical formula. All elements must be present in
            `mass_data`.
        sequence : str, optional
            A polypeptide sequence string in modX notation.
        parsed_sequence : list of str, optional
            A polypeptide sequence parsed into a list of amino acids.
        split_sequence : list of tuples of str, optional
            A polypeptyde sequence parsed into a list of tuples
            (as returned be :py:func:`pyteomics.parser.parse` with
            ``split=True``).
        aa_comp : dict, optional
            A dict with the elemental composition of the amino acids (the
            default value is std_aa_comp).
        mass_data : dict, optional
            A dict with the masses of chemical elements (the default
            value is :py:data:`nist_mass`). It is used for formulae parsing only.
        charge : int, optional
            If not 0 then additional protons are added to the composition.
        ion_comp : dict, optional
            A dict with the relative elemental compositions of peptide ion
            fragments (default is :py:data:`std_ion_comp`).
        ion_type : str, optional
            If specified, then the polypeptide is considered to be in the form
            of the corresponding ion. Do not forget to specify the charge state!
        """
        defaultdict.__init__(self, int)

        aa_comp = kwargs.get('aa_comp', std_aa_comp)
        mass_data = kwargs.get('mass_data', nist_mass)

        kw_sources = {'formula', 'sequence', 'parsed_sequence',
                'split_sequence'}
        kw_given = kw_sources.intersection(kwargs)
        if len(kw_given) > 1:
            raise PyteomicsError('Only one of {} can be specified!\n'
                    'Given: {}'.format(', '.join(kw_sources),
                        ', '.join(kw_given)))
        elif kw_given:
            kwa = kw_given.pop()
            getattr(self, '_from_' + kwa)(kwargs[kwa],
                    mass_data if kwa == 'formula' else aa_comp)

        # can't build from kwargs
        elif args:
            if isinstance(args[0], dict):
                self._from_dict(args[0])
            elif isinstance(args[0], str):
                try:
                    self._from_sequence(args[0], aa_comp)
                except PyteomicsError:
                    try:
                        self._from_formula(args[0], mass_data)
                    except PyteomicsError:
                        raise PyteomicsError(
                                'Could not create a Composition object from '
                                'string: "{}": not a valid sequence or '
                                'formula'.format(args[0]))
            else:
                try:
                    self._from_sequence(parser.tostring(args[0], True),
                            aa_comp)
                except:
                    raise PyteomicsError('Could not create a Composition object'
                            ' from `{}`. A Composition object must be '
                            'specified by sequence, parsed or split sequence,'
                            ' formula or dict.'.format(args[0]))
        else:
            self._from_dict(kwargs)

        ion_comp = kwargs.get('ion_comp', std_ion_comp)
        if 'ion_type' in kwargs:
            self += ion_comp[kwargs['ion_type']]

        # Get charge
        charge = self['H+']
        if 'charge' in kwargs:
            if charge:
                raise PyteomicsError(
                    'Charge is specified both by the number of protons and '
                    '`charge` in kwargs')
            charge = kwargs['charge']
            self['H+'] = charge
コード例 #52
0
 def __init__(self):
     defaultdict.__init__(self, IntervalTree)
     self.declared_regions = dict()
     self.inferred_regions = dict()
     self.yield_inferred = True
コード例 #53
0
 def __init__(self):
     defaultdict.__init__(self, Value)
コード例 #54
0
 def __init__(self, *args, **kwargs):
     defaultdict.__init__(self, list, *args, **kwargs)
     self._keys = []
     self._key_value = []
コード例 #55
0
 def __init__(self, data=None):
     defaultdict.__init__(self, float)
     if data:
         self.update(self.process_data(data))
コード例 #56
0
 def __init__(self, *args):
     defaultdict.__init__(self, *args)
     self.lock = threading.Lock()
コード例 #57
0
 def __init__(self):
     defaultdict.__init__(self, lambda: ())
コード例 #58
0
 def __init__(self):
   defaultdict.__init__(self, self.__class__)
コード例 #59
0
 def __init__(self):
     defaultdict.__init__(self, None)
コード例 #60
0
 def __init__(self, typeID, *args, **kwargs):
     defaultdict.__init__(self, *args, **kwargs)
     self.typeID = typeID