예제 #1
0
 def add(self, rights):
     if rights:
         try:
             rights = rights.split(',')
         except AttributeError:
             pass
         for right in rights:
             set.add(self, right)
예제 #2
0
파일: spark.py 프로젝트: minorg/thryft
 def add(self, set, item, i=None, predecessor=None, causal=None):
     if predecessor is None:
         if item not in set:
             set.append(item)
     else:
         key = (item, i)
         if item not in set:
             self.links[key] = []
             set.append(item)
         self.links[key].append((predecessor, causal))
예제 #3
0
 def reloadMirrors(self):
     mirrors = sysconf.get("mirrors", {})
     for channel in self._channels.values():
         if isinstance(channel, MirrorsChannel):
             cmirrors = channel.getMirrors()
             if cmirrors:
                 for origin in cmirrors:
                     set = dict.fromkeys(cmirrors[origin])
                     set.update(dict.fromkeys(mirrors.get(origin, [])))
                     mirrors[origin] = set.keys()
     msys = self._fetcher.getMirrorSystem()
     msys.setMirrors(mirrors)
     if not msys.getHistory():
         msys.setHistory(sysconf.get("mirrors-history", []))
    def __init__(self, reference_system, receptor_atoms=[], ligand_atoms=[]):
        """
        Initialize absolute alchemical intermediate factory with reference system.

        ARGUMENTS

        reference_system (System) - reference system containing receptor and ligand
        ligand_atoms (list) - list of atoms to be designated 'ligand' -- everything else in system is considered the 'environment'
        receptor_atoms (list) - list of atoms to be considered in softening specific 'receptor' degrees of freedom -- shouldn't be the whole receptor, but a subset of atoms in binding site
        
        """

        # Create pyopenmm System object.
        self.reference_system = pyopenmm.System(reference_system)

        # Store copy of atom sets.
        self.receptor_atoms = copy.deepcopy(receptor_atoms)
        self.ligand_atoms = copy.deepcopy(ligand_atoms)
        
        # Store atom sets
        self.ligand_atomset = Set(self.ligand_atoms)
        self.receptor_atomset = Set(self.receptor_atoms)

        # Make sure intersection of ligand and receptor atomsets is null.
        intersection = Set.intersection(self.ligand_atomset, self.receptor_atomset)
        if (len(intersection) > 0):
            raise ParameterException("receptor and ligand atomsets must not overlap.")
        
        return
예제 #5
0
 def __new__(cls, *args, **kwargs):
     if args:
         new_args = (args[0], )
     else:
         new_args = ()
     obj = set.__new__(cls, *new_args)
     obj.__init__(*args, **kwargs)
     return obj
예제 #6
0
	def __init__(self, *args) :
		# Handle special case when this __init__ is used as a copy constructor,
		# i.e. with Set or ifilter instance as a sole argument
		# This is needed to overcome flawed standard sets implementation in Python 2.3+
		if len(args) == 1 :
			x = args[0]
			if isinstance(x, (Set, itertools.ifilter)) :
				_Set.__init__(self, x)
				return
		# ALARM : dependence on the sets.Set implementation !!!
		xargs = []
		for x in args :
			if isinstance(x, Keyword) :
				xargs.append(x)
			else :
				xargs.append(Keyword(x))
		_Set.__init__(self, xargs)
    def update_set (self, set):
        if set == self.content_set:
            return

        model, iter = self.treeview.get_selection ().get_selected ()
        if iter:
            # save the selected content so that it will be selected again
            # later
            self.selected_content = model[iter][self.COLUMN_EDITABLE]

        self.content_set = set.copy ()
        self.__update_model ()
예제 #8
0
    def findNeighbors(self) :
        neighbors = []
        nEdges = 0
        for i in range(self.numElems()) :
            allNeighbors = Set()
            for v in self.elemVerts_[i] :
                allNeighbors = Set.union(allNeighbors, self.vertToElemMap_[v])
            # get rid of self-references
            allNeighbors.discard(i)
            fullNeighbors = []
            for j in allNeighbors :

                numCommonNodes = Set.intersection(self.elemVerts_[i],
                                                  self.elemVerts_[j])
                if len(numCommonNodes) == self.dim_ :
                    fullNeighbors.append(j)
                         
            nEdges = nEdges + len(fullNeighbors)
            neighbors.append(fullNeighbors)

        nEdges = nEdges/2

        return (neighbors, nEdges)
예제 #9
0
def pattern_filter(pattern, xs, report_failed=None, check_errors=False,
                   range_match=False):
    ps = pattern.split(",")
    filtered_set = set([])
    for p0 in ps:
        p = p0.split("excluding")
        if (len(p) == 1):
            try:
                pstr = p[0].strip()
                p = re.compile(pstr + "$")
            except:
                sys.stderr.write("ERROR:`"+p[0].strip()+"' is not a valid regular expression ") 
                if (report_failed):
                    sys.stderr.write(report_failed)
                sys.stderr.write("\n")
                exit(1)
            found = False
            for item in xs:
                if p.match(str(item)):
                    found = True
                    filtered_set.add((item,0))
                elif range_match:
                    range_pattern = re.compile("(.*)__RANGE$")
                    m = range_pattern.match(str(item))
                    if m:
                        item_root = m.groups(0)[0]
                        item_pattern = re.compile(item_root + "_(.*)")
                        m = item_pattern.match(pstr)
                        if m:                            
                            n = int(m.groups(0)[0])
                            filtered_set.add((item, n))

            if check_errors and report_failed and not found:                    
                sys.stderr.write("Cannot match `" + p0 + "'" + report_failed +"\n")
                if check_errors:
                    exit(1)
                
        else:
            in_pattern = re.compile(p[0].strip())
            exc_pattern = re.compile(p[1].strip())
            in_set = set([])
            exc_set = set([])
            for item in xs:
                if in_pattern.match(str(item)):
                    in_set.add(item)
                if exc_pattern.match(str(item)):
                    exc_set.add(item)
            in_set = in_set - exc_set
            filtered_set = set.union(filtered_set, in_set)
    return list(filtered_set)
예제 #10
0
    def _is_restraint(self, valence_atoms):
        """
        Determine whether specified valence term connects the ligand with its environment.

        Parameters
        ----------
        valence_atoms : list of int
            Atom indices involved in valence term (bond, angle or torsion).
            
        Returns
        -------
        is_restraint : bool
            True if the set of atoms includes at least one ligand atom and at least one non-ligand atom; False otherwise

        Examples
        --------
        
        Various tests for a simple system.
        
        >>> # Create a reference system.
        >>> from repex import testsystems
        >>> alanine_dipeptide = testsystems.AlanineDipeptideImplicit()
        >>> [reference_system, positions] = [alanine_dipeptide.system, alanine_dipeptide.positions]
        >>> # Create a factory.
        >>> factory = AbsoluteAlchemicalFactory(reference_system, ligand_atoms=[0, 1, 2])
        >>> factory._is_restraint([0,1,2])
        False
        >>> factory._is_restraint([1,2,3])
        True
        >>> factory._is_restraint([3,4])
        False
        >>> factory._is_restraint([2,3,4,5])
        True

        """

        valence_atomset = Set(valence_atoms)
        intersection = Set.intersection(valence_atomset, self.ligand_atomset)
        if (len(intersection) >= 1) and (len(intersection) < len(valence_atomset)):
            return True

        return False        
예제 #11
0
    def _is_restraint(self, valence_atoms):
        """
        Determine whether specified valence term connects the ligand with its environment.

        ARGUMENTS
        
        valence_atoms (list of int) - atom indices involved in valence term (bond, angle or torsion)

        RETURNS

        True if the set of atoms includes at least one ligand atom and at least one non-ligand atom; False otherwise

        EXAMPLES
        
        Various tests.
        
        >>> # Create a reference system.
        >>> import testsystems
        >>> [reference_system, coordinates] = testsystems.AlanineDipeptideImplicit()
        >>> # Create a factory.
        >>> factory = AbsoluteAlchemicalFactory(reference_system, alchemical_atoms=[0, 1, 2])
        >>> factory._is_restraint([0,1,2])
        False
        >>> factory._is_restraint([1,2,3])
        True
        >>> factory._is_restraint([3,4])
        False
        >>> factory._is_restraint([2,3,4,5])
        True

        """

        valence_atomset = Set(valence_atoms)
        intersection = Set.intersection(valence_atomset, self.alchemical_atomset)
        if (len(intersection) >= 1) and (len(intersection) < len(valence_atomset)):
            return True

        return False        
예제 #12
0
 def remove(self, *args):
     print "removing %s" % args
     return Set.remove(self, *args)
예제 #13
0
 def __init__(self, *args):
     print "starting with %s" % (args,)
     Set.__init__(self, *args)
예제 #14
0
 def test_difference_superset(self):
     self.set -= Set((2, 4, 6, 8))
     self.assertEqual(self.set, Set([]))
예제 #15
0
 def test_difference_method_call(self):
     self.set.difference_update(Set([3, 4, 5]))
     self.assertEqual(self.set, Set([2, 6]))
예제 #16
0
파일: base.py 프로젝트: OnShift/turbogears
 def __init__(self, *args):
     set.__init__(self, args)
예제 #17
0
 def test_add_present(self):
     self.set.add("c")
     self.assertEqual(self.set, Set("abc"))
예제 #18
0
 def test_sym_difference_method_call(self):
     self.set.symmetric_difference_update(Set([3, 4, 5]))
     self.assertEqual(self.set, Set([2, 3, 5, 6]))
예제 #19
0
 def test_update_unit_tuple_non_overlap(self):
     self.set.union_update(("a", "z"))
     self.assertEqual(self.set, Set(self.values + ["z"]))
예제 #20
0
 def test_update_unit_tuple_overlap(self):
     self.set.union_update(("a", ))
     self.assertEqual(self.set, Set(self.values))
예제 #21
0
 def test_update_empty_tuple(self):
     self.set.union_update(())
     self.assertEqual(self.set, Set(self.values))
예제 #22
0
 def test_discard_absent(self):
     self.set.discard("d")
     self.assertEqual(self.set, Set("abc"))
예제 #23
0
 def test_discard_present(self):
     self.set.discard("c")
     self.assertEqual(self.set, Set("ab"))
예제 #24
0
 def test_remove_present(self):
     self.set.remove("b")
     self.assertEqual(self.set, Set("ac"))
예제 #25
0
 def test_add_absent(self):
     self.set.add("d")
     self.assertEqual(self.set, Set("abcd"))
예제 #26
0
class TestSubsetEqualEmpty(TestSubsets):
    left = Set()
    right = Set()
    name = "both empty"
    cases = "==", "<=", ">="
 def db_update(self):
     self._check_new_set()
     for set in self.sets.values():
         set.db_update()
예제 #28
0
class TestSubsetEqualNonEmpty(TestSubsets):
    left = Set([1, 2])
    right = Set([1, 2])
    name = "equal pair"
    cases = "==", "<=", ">="
예제 #29
0
 def __init__(self, privacy=()):
     if privacy is None or privacy == '!':
         privacy = ()
     if isinstance(privacy, basestring):
         privacy = privacy.split(',')
     set.__init__(self, privacy)
예제 #30
0
class TestSubsetEmptyNonEmpty(TestSubsets):
    left = Set()
    right = Set([1, 2])
    name = "one empty, one non-empty"
    cases = "!=", "<", "<="
예제 #31
0
파일: Utility.py 프로젝트: ablot/acq4
def findspikes(xin, vin, thresh, t0=None, t1= None, dt=1.0, mode=None, interpolate=False, debug=False):
    """ findspikes identifies the times of action potential in the trace v, with the
    times in t. An action potential is simply timed at the first point that exceeds
    the threshold... or is the peak. 
    4/1/11 - added peak mode
    if mode is none or schmitt, we work as in the past.
    if mode is peak, we return the time of the peak of the AP instead
    7/15/11 - added interpolation flag
    if True, the returned time is interpolated, based on a spline fit
    if False, the returned time is just taken as the data time.
    2012/10/9: Removed masked arrays and forced into ndarray from start
    (metaarrays were really slow...) 
    """
    # if debug:
    # # this does not work with pyside...
    #     import matplotlib
    #     matplotlib.use('Qt4Agg')
    #     import pylab
    #     from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
    #     from matplotlib.figure import Figure
    #     
    #     #MP.rcParams['interactive'] = False
        
    st=numpy.array([])
    spk = []
    if xin is None:
        return(st, spk)
    xt = xin.view(numpy.ndarray)
    v = vin.view(numpy.ndarray)
    if t1 is not None and t0 is not None:
        it0 = int(t0/dt)
        it1 = int(t1/dt)
        if not isinstance(xin, numpy.ndarray):
            xt = xt[it0:it1]
            v = v[it0:it1]
        else:
            xt = xt[it0:it1]
            v = v[it0:it1]
    # if debug:
    #     f = pylab.figure(1)
    #     print "xt: ", xt
    #     print "v: ", v
    #     pylab.plot(numpy.array(xt), v, 'k-')
    #     pylab.draw()
    #     pylab.show()

    dv = numpy.diff(v, axis=0) # compute slope
    dv /= dt
    st=numpy.array([])
    spk = []
    spv = numpy.where(v > thresh)[0].tolist() # find points above threshold
    sps = numpy.where(dv > 0.0)[0].tolist() # find points where slope is positive
    sp = list(Set.intersection(Set(spv),Set(sps))) # intersection defines putative spikes
    sp.sort() # make sure all detected events are in order (sets is unordered)
    sp = tuple(sp) # convert to tuple
    if sp is ():
        return(st, spk) # nothing detected
    dx = 1
    mingap = int(0.0005/dt) # 0.5 msec between spikes (a little unphysiological...)
    # normal operating mode is fixed voltage threshold
    # for this we need to just get the FIRST positive crossing,
    if mode is 'schmitt':
        sthra = list(numpy.where(numpy.diff(sp) > mingap))
        sthr = [sp[x] for x in sthra[0]] # bump indices by 1
        for k in sthr:
            x = xt[k-1:k+1]
            y = v[k-1:k+1]
            if interpolate:
                dx = 0
                m = (y[1]-y[0])/dt # local slope
                b = y[0]-(x[0]*m)
                s0 = (thresh-b)/m
            else:
                s0 = x[1]
            st = numpy.append(st, x[1])

    elif mode is 'peak':
        pkwidth = 1.0e-3 # in same units as dt  - usually msec
        kpkw = int(pkwidth/dt)
        z = (numpy.array(numpy.where(numpy.diff(spv) > 1)[0])+1).tolist()
        z.insert(0, 0) # first element in spv is needed to get starting AP
        spk = []
        for k in z:
            zk = spv[k]
            spkp = numpy.argmax(v[zk:zk+kpkw])+zk # find the peak position
            x = xt[spkp-1:spkp+2]
            y = v[spkp-1:spkp+2]
            if interpolate:
                try:
                    # mimic Igor FindPeak routine with B = 1
                    m1 = (y[1]-y[0])/dt # local slope to left of peak
                    b1 = y[0]-(x[0]*m1)
                    m2 = (y[2]-y[1])/dt # local slope to right of peak
                    b2 = y[1]-(x[1]*m2)
                    mprime = (m2-m1)/dt # find where slope goes to 0 by getting the line
                    bprime = m2-((dt/2.0)*mprime)
                    st = numpy.append(st, -bprime/mprime+x[1])
                    spk.append(spkp)
                except:
                    continue
            else:
                st = numpy.append(st, x[1]) # always save the first one
                spk.append(spkp)
    return(st, spk)
예제 #32
0
class TestSubsetPartial(TestSubsets):
    left = Set([1])
    right = Set([1, 2])
    name = "one a non-empty proper subset of other"
    cases = "!=", "<", "<="
예제 #33
0
 def __init__(self, sequence=tuple()):
     DependencyCell.__init__(self)
     set.__init__(self, sequence)
예제 #34
0
class TestSubsetNonOverlap(TestSubsets):
    left = Set([1])
    right = Set([2])
    name = "neither empty, neither contains"
    cases = "!="
예제 #35
0
 def __init__(self, rights=None):
     set.__init__(self)
     self.add(rights)
예제 #36
0
 def setUp(self):
     self.set = Set((1, 2, 3))
     self.other = 19
     self.otherIsIterable = False
예제 #37
0
파일: annotkit.py 프로젝트: YuJinhui/kobas
 def __init__(self,iterable=None):
     Set.__init__(self,iterable)
예제 #38
0
 def setUp(self):
     self.set = Set((1, 2, 3))
     self.other = {1: 2, 3: 4}
     self.otherIsIterable = True
예제 #39
0
 def add(self, *args):
     print "adding %s" % args
     return Set.add(self, *args)
예제 #40
0
 def setUp(self):
     self.set = Set((1, 2, 3))
     self.other = operator.add
     self.otherIsIterable = False
예제 #41
0
 def test_difference_subset(self):
     self.set -= Set((2, 4))
     self.assertEqual(self.set, Set([6]))
예제 #42
0
 def setUp(self):
     self.set = Set((1, 2, 3))
     self.other = (2, 4, 6)
     self.otherIsIterable = True
 def db_has_changed(self):
     self._check_new_set()
     for set in self.sets.values():
         if set.db_has_changed():
             return True
     return False
예제 #44
0
 def setUp(self):
     self.set = Set((1, 2, 3))
     self.other = 'abc'
     self.otherIsIterable = True
 def db_revert(self):
     self._new_set = None
     for set in self.sets.values():
         set.db_revert()
 def add(self, thing):
     print '%s ok' % thing
     Set.add(self, thing)
예제 #47
0
 def uniq(alist):
     set = {}
     return [set.setdefault(e,e) for e in alist if e not in set]
예제 #48
0
 def __repr__(self):
     return '%s(%s), %s' % (self.__class__.__name__, Set.__repr__(self))
예제 #49
0
 def setUp(self):
     self.set = Set((1, 2, 3))
     self.other = [Set('ab'), ImmutableSet('cd')]
     self.otherIsIterable = True
예제 #50
0
 def setUp(self):
     self.values = ["a", "b", "c"]
     self.set = Set(self.values)
예제 #51
0
 def test_sym_difference_overlap(self):
     self.set ^= Set((3, 4, 5))
     self.assertEqual(self.set, Set([2, 3, 5, 6]))
예제 #52
0
	def __contains__(self, x) :
		if isinstance(x, Keyword) :
			return _Set.__contains__(self, x)
		else :
			return _Set.__contains__(self, Keyword(x))
예제 #53
0
 def setUp(self):
     self.set = Set(["hello"])
예제 #54
0
 def setUp(self):
     self.set = Set(["zero", 0, None])
예제 #55
0
파일: weak.py 프로젝트: FaithNahn/amsn2
 def __init__(self, iterable=None):
     Set.__init__(self)
     self._data = WeakKeyDictionary()
     if iterable is not None:
         self._update(iterable)
예제 #56
0
 def test_difference_overlap(self):
     self.set -= Set((3, 4, 5))
     self.assertEqual(self.set, Set([2, 6]))
예제 #57
0
def makeChacoGraphFile(filename) : 
    f = file(filename + '.ele')
    nodeToEleMap = {}
    elemVerts = []
    # read header 
    while 1 :
        line = f.readline()
        if line[0]=='#': continue
        header = line.split()
        nElems = int(header[0])
        d = int(header[1])-1
        break
    # read lines, building elements and the element-to-node map
    while 1:
        line = f.readline()
        if not line : break
        if line[0]=='#': continue
        toks = line.split()
        ele = int(toks[0])
        verts = Set()
        for i in range(d+1) :
            node = int(toks[i+1])
            verts.add(node)
            if nodeToEleMap.has_key(node) :
                nodeToEleMap[node].add(ele)
            else :
                nodeToEleMap[node] = Set()
                nodeToEleMap[node].add(ele)
        elemVerts.append(verts)

    # For each node, assign one of the adjoining elements as its "owner."
    # The node will later be assigned to the same processer as the owner.
    # The choice of owner is arbitrary; here, we simply choose the
    # adjoining element having the largest index.
    #
    # We write the ownership information to a file, with the format:
    # line 1: <num nodes>
    # line 2: <node 1 number> <node 1 owner>
    # etc.
    nodeOwnerFile = file(filename + '.owner', 'w')
    nodeOwnerFile.write('%d\n' % len(nodeToEleMap.keys()))
    for node in nodeToEleMap.keys() :
        owner = max(nodeToEleMap[node])
        nodeOwnerFile.write('%d %d\n' % (node, owner))


    
    
    # determine lists of neighbors for each element
    neighbors = []
    nEdges = 0
    for i in range(nElems) :
        allNeighbors = Set()
        for v in elemVerts[i] :
            allNeighbors = Set.union(allNeighbors, nodeToEleMap[v])
        # get rid of self-references
        allNeighbors.discard(i)
        fullNeighbors = []
        for j in allNeighbors :
            numCommonNodes = Set.intersection(elemVerts[i], elemVerts[j])
            if len(numCommonNodes) == d :
                fullNeighbors.append(j)
                
        nEdges = nEdges + len(fullNeighbors)
        neighbors.append(fullNeighbors)

    nEdges = nEdges/2

    graphFile = file(filename + '.graph', 'w')
    graphFile.write('%d %d\n' % (nElems, nEdges))

    for i in range(nElems) :
        line = ''
        for j in neighbors[i] :
            line = line +  '%d ' % (j+1)
        graphFile.write(line + '\n');
    graphFile.flush()

    return (elemVerts, nodeToEleMap)
예제 #58
0
 def __init__(self,iterable=None):
     '''Construct a multiset from an optional iterable.'''
     Set.__init__(self,iterable)
예제 #59
0
 def setUp(self):
     self.set = Set()
예제 #60
0
 def test_difference_non_overlap(self):
     self.set -= Set([8])
     self.assertEqual(self.set, Set([2, 4, 6]))