def __init__(self,
                 particleEffect,
                 parent,
                 worldRelative=1,
                 renderParent=None,
                 duration=0.0,
                 softStopT=0.0,
                 cleanup=False,
                 name=None):
        """
        particleEffect is a ParticleEffect
        parent is a NodePath: this is where the effect will be
                              parented in the scenegraph
        worldRelative is a boolean: this will override 'renderParent'
                                    with render
        renderParent is a NodePath: this is where the particles will
                                    be rendered in the scenegraph
        duration is a float: for the time
        softStopT is a float: no effect if 0.0,
                              a positive value will count from the
                              start of the interval,
                              a negative value will count from the
                              end of the interval
        cleanup is a boolean: if True the effect will be destroyed
                              and removed from the scenegraph upon
                              interval completion
                              set to False if planning on reusing
                              the interval
        name is a string: use this for unique intervals so that
                          they can be easily found in the taskMgr
        """

        # Generate unique name
        id = 'Particle-%d' % ParticleInterval.particleNum
        ParticleInterval.particleNum += 1
        if name == None:
            name = id
        # Record instance variables
        self.particleEffect = particleEffect
        self.cleanup = cleanup

        if parent != None:
            self.particleEffect.reparentTo(parent)
        if worldRelative:
            renderParent = render
        if renderParent:
            for particles in self.particleEffect.getParticlesList():
                particles.setRenderParent(renderParent.node())

        self.__softStopped = False

        if softStopT == 0.0:
            self.softStopT = duration
        elif softStopT < 0.0:
            self.softStopT = duration + softStopT
        else:
            self.softStopT = softStopT

        # Initialize superclass
        Interval.__init__(self, name, duration)
Beispiel #2
0
    def __init__(self,
                 particleEffect,
                 duration=0.0,
                 parent=None,
                 renderParent=None,
                 name=None):
        """
        particleEffect is ??
        parent is ??
        worldRelative is a boolean
        loop is a boolean
        duration is a float for the time
        name is ??
        """
        # Generate unique name
        id = 'Particle-%d' % TestInterval.particleNum
        TestInterval.particleNum += 1
        if name == None:
            name = id
        # Record instance variables
        self.particleEffect = particleEffect
        self.parent = parent
        self.renderParent = renderParent

        Interval.__init__(self, name, duration)
 def privInitialize(self, t):
     self.__initialize()
     if self.collNode:
         self.collNode.clearSolids()
         csolid = CollisionParabola(self.parabola, 0, 0)
         self.collNode.addSolid(csolid)
     Interval.privInitialize(self, t)
Beispiel #4
0
 def __init__(self,
              node,
              startPos=None,
              endPos=None,
              duration=None,
              startVel=None,
              endZ=None,
              wayPoint=None,
              timeToWayPoint=None,
              gravityMult=None,
              name=None,
              collNode=None):
     self.node = node
     self.collNode = collNode
     if self.collNode:
         if isinstance(self.collNode, NodePath):
             self.collNode = self.collNode.node()
     if name == None:
         name = '%s-%s' % (self.__class__.__name__,
                           self.projectileIntervalNum)
         ProjectileInterval.projectileIntervalNum += 1
     args = (startPos, endPos, duration, startVel, endZ, wayPoint,
             timeToWayPoint, gravityMult)
     self.implicitStartPos = 0
     if startPos is None:
         if duration is None:
             self.notify.error('must provide either startPos or duration')
         self.duration = duration
         self.trajectoryArgs = args
         self.implicitStartPos = 1
     else:
         self.trajectoryArgs = args
         self.__calcTrajectory(*args)
     Interval.__init__(self, name, self.duration)
     return
Beispiel #5
0
    def trim_back_edges(self, u: str):
        """
		Remove back edges ending at parent u (phase 2)
		@param u:
		@return:
		"""
        # drop entire conflict pairs
        while len(self.s) and self.lowest(self.top_s()) == self.height[u]:
            p = self.s.pop()
            if p.l.low is not None:
                self.side[p.l.low] = -1

        # one more conflict pair to consider
        if len(self.s):
            p = self.s.pop()
            # trim left interval
            while p.l.high is not None and p.l.high[1] == u:
                p.l.high = self.ref[p.l.high]
            if p.l.high is None and p.l.low is not None:  # just emptied
                self.ref[p.l.low] = p.r.low
                self.side[p.l.low] = -1
                p.l = Interval(high=p.l.high)
            # trim right interval
            while p.r.high is not None and p.r.high[1] == u:
                p.r.high = self.ref[p.r.high]
            if p.r.high is None and p.r.low is not None:  # just emptied
                self.ref[p.r.low] = p.l.low
                self.side[p.r.low] = -1
                p.r = Interval(high=p.r.high)
            self.s.append(p)
Beispiel #6
0
 def testTransposeTo(self):
     for Ch, Int in self.TranspositionTest:
         TransposedInterval = Interval(Ch[0][0],
                                       Ch[0][1]).TransposeTo(Ch[1])
         self.assertEqual(TransposedInterval.__repr__(), Int.__repr__())
         print(Interval(Ch[0][0], Ch[0][1]), "transposed to ", Ch[1],
               " gives", TransposedInterval)
 def privStep(self, t):
     self.node.setFluidPos(self._ProjectileInterval__calcPos(t))
     Interval.privStep(self, t)
     if self.collNode and self.collNode.getNumSolids() > 0:
         csolid = self.collNode.modifySolid(0)
         csolid.setT1(csolid.getT2())
         csolid.setT2(t)
 def privInstant(self):
     self._ProjectileInterval__initialize()
     Interval.privInstant(self)
     if self.collNode:
         self.collNode.clearSolids()
         csolid = CollisionParabola(self.parabola, 0, self.duration)
         self.collNode.addSolid(csolid)
    def __init__(self,
                 particleEffect,
                 parent,
                 worldRelative=1,
                 renderParent=None,
                 duration=0.0,
                 softStopT=0.0,
                 cleanup=False,
                 name=None):
        id = 'Particle-%d' % ParticleInterval.particleNum
        ParticleInterval.particleNum += 1
        if name == None:
            name = id
        self.particleEffect = particleEffect
        self.cleanup = cleanup
        if parent != None:
            self.particleEffect.reparentTo(parent)
        if worldRelative:
            renderParent = render
        if renderParent:
            for particles in self.particleEffect.getParticlesList():
                particles.setRenderParent(renderParent.node())

        self.__softStopped = False
        if softStopT == 0.0:
            self.softStopT = duration
        else:
            if softStopT < 0.0:
                self.softStopT = duration + softStopT
            else:
                self.softStopT = softStopT
        Interval.__init__(self, name, duration)
        return
    def __init__(self,
                 particleEffect,
                 parent,
                 worldRelative = 1,
                 renderParent = None,
                 duration = 0.0,
                 softStopT = 0.0,
                 cleanup = False,
                 name = None):
        """
        particleEffect is a ParticleEffect
        parent is a NodePath: this is where the effect will be
                              parented in the scenegraph
        worldRelative is a boolean: this will override 'renderParent'
                                    with render
        renderParent is a NodePath: this is where the particles will
                                    be rendered in the scenegraph
        duration is a float: for the time
        softStopT is a float: no effect if 0.0,
                              a positive value will count from the
                              start of the interval,
                              a negative value will count from the
                              end of the interval
        cleanup is a boolean: if True the effect will be destroyed
                              and removed from the scenegraph upon
                              interval completion
                              set to False if planning on reusing
                              the interval
        name is a string: use this for unique intervals so that
                          they can be easily found in the taskMgr
        """
        
        # Generate unique name
        id = 'Particle-%d' % ParticleInterval.particleNum
        ParticleInterval.particleNum += 1
        if name == None:
            name = id
        # Record instance variables
        self.particleEffect = particleEffect 
        self.cleanup = cleanup

        if parent != None:
            self.particleEffect.reparentTo(parent)
        if worldRelative:
            renderParent = render
        if renderParent:
            for particles in self.particleEffect.getParticlesList():
                particles.setRenderParent(renderParent.node())

        self.__softStopped = False
        
        if softStopT == 0.0:
            self.softStopT = duration
        elif softStopT < 0.0:
            self.softStopT = duration+softStopT
        else:
            self.softStopT = softStopT
            
        # Initialize superclass
        Interval.__init__(self, name, duration)
Beispiel #11
0
 def __init__(self, left: Interval = None, right: Interval = None):
     if left is None:
         left = Interval()
     if right is None:
         right = Interval()
     self.l = left
     self.r = right
    def __init__(self,
                 particleEffect,
                 duration=0.0,
                 parent = None,
                 renderParent = None,
                 name=None):
        """
        particleEffect is ??
        parent is ??
        worldRelative is a boolean
        loop is a boolean
        duration is a float for the time
        name is ??
        """
        # Generate unique name
        id = 'Particle-%d' % TestInterval.particleNum
        TestInterval.particleNum += 1
        if name == None:
            name = id
        # Record instance variables
        self.particleEffect = particleEffect
        self.parent = parent
        self.renderParent = renderParent

        Interval.__init__(self, name, duration)
Beispiel #13
0
 def privInstant(self):
     self.__initialize()
     Interval.privInstant(self)
     if self.collNode:
         self.collNode.clearSolids()
         csolid = CollisionParabola(self.parabola, 0, self.duration)
         self.collNode.addSolid(csolid)
    def __init__(
        self,
        node,
        startPos=None,
        endPos=None,
        duration=None,
        startVel=None,
        endZ=None,
        wayPoint=None,
        timeToWayPoint=None,
        gravityMult=None,
        name=None,
    ):
        """
        You may specify several different sets of input parameters.
        (If startPos is not provided, it will be obtained from the node's
        position at the time that the interval is first started. Note that
        in this case you must provide a duration of some kind.)
        
        # go from startPos to endPos in duration seconds
        startPos, endPos, duration
        # given a starting velocity, go for a specific time period
        startPos, startVel, duration
        # given a starting velocity, go until you hit a given Z plane
        startPos, startVel, endZ
        # pass through wayPoint at time 'timeToWayPoint'. Go until
        # you hit a given Z plane
        startPos, wayPoint, timeToWayPoint, endZ
        
        You may alter gravity by providing a multiplier in 'gravityMult'.
        '2.' will make gravity twice as strong, '.5' half as strong.
        '-1.' will reverse gravity
        """
        self.node = node

        if name == None:
            name = "%s-%s" % (self.__class__.__name__, self.projectileIntervalNum)
            ProjectileInterval.projectileIntervalNum += 1

            """
            # attempt to add info about the caller
            file, line, func = PythonUtil.callerInfo()
            if file is not None:
                name += '-%s:%s:%s' % (file, line, func)
            """

        args = (startPos, endPos, duration, startVel, endZ, wayPoint, timeToWayPoint, gravityMult)
        self.implicitStartPos = 0
        if startPos is None:
            if duration is None:
                self.notify.error("must provide either startPos or duration")
            self.duration = duration
            # we can't calc the trajectory until we know our starting
            # position; delay until the interval is actually started
            self.trajectoryArgs = args
            self.implicitStartPos = 1
        else:
            self.__calcTrajectory(*args)

        Interval.__init__(self, name, self.duration)
 def __init__(self, node, startPos = None, endPos = None, duration = None, startVel = None, endZ = None, wayPoint = None, timeToWayPoint = None, gravityMult = None, name = None, collNode = None):
     self.node = node
     self.collNode = collNode
     if self.collNode:
         if isinstance(self.collNode, NodePath):
             self.collNode = self.collNode.node()
     if name == None:
         name = '%s-%s' % (self.__class__.__name__, self.projectileIntervalNum)
         ProjectileInterval.projectileIntervalNum += 1
     args = (startPos,
      endPos,
      duration,
      startVel,
      endZ,
      wayPoint,
      timeToWayPoint,
      gravityMult)
     self.implicitStartPos = 0
     if startPos is None:
         if duration is None:
             self.notify.error('must provide either startPos or duration')
         self.duration = duration
         self.trajectoryArgs = args
         self.implicitStartPos = 1
     else:
         self.trajectoryArgs = args
         self.__calcTrajectory(*args)
     Interval.__init__(self, name, self.duration)
     return
 def privInitialize(self, t):
     self.__initialize()
     if self.collNode:
         self.collNode.clearSolids()
         csolid = CollisionParabola(self.parabola, 0, 0)
         self.collNode.addSolid(csolid)
     Interval.privInitialize(self, t)
Beispiel #17
0
 def privStep(self, t):
     self.node.setFluidPos(self.__calcPos(t))
     Interval.privStep(self, t)
     if self.collNode and self.collNode.getNumSolids() > 0:
         csolid = self.collNode.modifySolid(0)
         csolid.setT1(csolid.getT2())
         csolid.setT2(t)
Beispiel #18
0
 def get_octave(self):
     octave = Interval(self.base_freq)
     octave_freq = self.scale_intervals[0].final_frequency*2
     octave.final_frequency = octave_freq
     octave.note_number = self.NUM_INTERVALS
     octave.set_note_name()
     return octave
    def __init__(self,
                 node,
                 startPos=None,
                 endPos=None,
                 duration=None,
                 startVel=None,
                 endZ=None,
                 wayPoint=None,
                 timeToWayPoint=None,
                 gravityMult=None,
                 name=None):
        """
        You may specify several different sets of input parameters.
        (If startPos is not provided, it will be obtained from the node's
        position at the time that the interval is first started. Note that
        in this case you must provide a duration of some kind.)
        
        # go from startPos to endPos in duration seconds
        startPos, endPos, duration
        # given a starting velocity, go for a specific time period
        startPos, startVel, duration
        # given a starting velocity, go until you hit a given Z plane
        startPos, startVel, endZ
        # pass through wayPoint at time 'timeToWayPoint'. Go until
        # you hit a given Z plane
        startPos, wayPoint, timeToWayPoint, endZ
        
        You may alter gravity by providing a multiplier in 'gravityMult'.
        '2.' will make gravity twice as strong, '.5' half as strong.
        '-1.' will reverse gravity
        """
        self.node = node

        if name == None:
            name = '%s-%s' % (self.__class__.__name__,
                              self.projectileIntervalNum)
            ProjectileInterval.projectileIntervalNum += 1
            """
            # attempt to add info about the caller
            file, line, func = PythonUtil.callerInfo()
            if file is not None:
                name += '-%s:%s:%s' % (file, line, func)
            """

        args = (startPos, endPos, duration, startVel, endZ, wayPoint,
                timeToWayPoint, gravityMult)
        self.implicitStartPos = 0
        if startPos is None:
            if duration is None:
                self.notify.error('must provide either startPos or duration')
            self.duration = duration
            # we can't calc the trajectory until we know our starting
            # position; delay until the interval is actually started
            self.trajectoryArgs = args
            self.implicitStartPos = 1
        else:
            self.__calcTrajectory(*args)

        Interval.__init__(self, name, self.duration)
    def window_generator(self, chrom_length, window_size):

        intervals = {}
        for i in range(1, chrom_length + 1, window_size):
            intervals[Interval(i, i + window_size - 1)] = []
        if i + window_size - 1 < chrom_length + 1:
            intervals[Interval(i + window_size, chrom_length)] = []
        return intervals
 def RecognizeInterval(self, Interval):
     """ Gives a name to an interval """
     NoteDistance = Interval.GetNoteNameDistance()
     LookupValue = self.IntervalNameLookup[NoteDistance]
     IName = LookupValue[0]
     IntervalType = LookupValue[1]
     Difference = Interval.GetDistance(
     ) - self.NominalHalfSteps[NoteDistance]
     Modifier = self.Modifiers[IntervalType][Difference]
     return IntervalName(IName, Modifier)
Beispiel #22
0
 def privStep(self, t):
     if self.state == CInterval.SPaused or t < self.currT:
         self.privInitialize(t)
     elif not (self._ParticleInterval__softStopped) and t > self.softStopT:
         self._ParticleInterval__step(self.softStopT - self.currT)
         self._ParticleInterval__softStop()
         self._ParticleInterval__step(t - self.softStopT)
     else:
         self._ParticleInterval__step(t - self.currT)
     Interval.privStep(self, t)
 def privStep(self, t):
     if self.state == CInterval.SPaused or t < self.currT:
         self.privInitialize(t)
     else:
         if not self.__softStopped and t > self.softStopT:
             self.__step(self.softStopT - self.currT)
             self.__softStop()
             self.__step(t - self.softStopT)
         else:
             self.__step(t - self.currT)
         Interval.privStep(self, t)
    def privInitialize(self, t):
        if self.state != CInterval.SPaused:
            self.__softStart()
            if self.particleEffect:
                self.particleEffect.clearToInitial()
            self.currT = 0
        if self.particleEffect:
            for forceGroup in self.particleEffect.getForceGroupList():
                forceGroup.enable()

        Interval.privInitialize(self, t)
    def __init__(self):
        """ Interval knowledge consists of interval names and an interval type.
                    The interval name is a string (e.g. "third")
                    The interval type is either 1 or 2. 
                    Intervals of type 1 can have modifiers: perfect, augmented, diminished, doubly augmented or doubly diminished.
                    Intervals of type 2 can have modifiers: major, minor, augmented, diminished, doubly augmented or doubly diminished.
                """
        self.IntervalNameLookup = {
            0: ["unison", 1],
            1: ["second", 2],
            2: ["third", 2],
            3: ["fourth", 1],
            4: ["fifth", 1],
            5: ["sixth", 2],
            6: ["seventh", 2],
            7: ["octave", 1]
        }

        self.MajorScale = ['c', 'd', 'e', 'f', 'g', 'a', 'b']

        self.ModifierKnowledgeType1 = {
            -4: "quadruply diminished",
            -3: "triply diminished",
            -2: "doubly diminished",
            -1: "diminished",
            0: "perfect",
            1: "augmented",
            2: "doubly augmented",
            3: "triply augmented",
            4: "quadruply augmented"
        }

        self.ModifierKnowledgeType2 = {
            -4: "triply diminished",
            -3: "doubly diminished",
            -2: "diminished",
            -1: "minor",
            0: "major",
            1: "augmented",
            2: "doubly augmented",
            3: "triply augmented",
            4: "quadruply augmented"
        }

        self.Modifiers = {
            1: self.ModifierKnowledgeType1,
            2: self.ModifierKnowledgeType2
        }

        self.NominalHalfSteps = {}
        for Note in self.MajorScale:
            self.NominalHalfSteps[Interval(
                self.MajorScale[0], Note).GetNoteNameDistance()] = Interval(
                    self.MajorScale[0], Note).GetDistance()
    def privInitialize(self, t):
        if self.state != CInterval.SPaused:
            self.__softStart()
            if self.particleEffect:
                self.particleEffect.clearToInitial()
            self.currT = 0
        if self.particleEffect:
            for forceGroup in self.particleEffect.getForceGroupList():
                forceGroup.enable()

        Interval.privInitialize(self, t)
 def privStep(self, t):
     if self.state == CInterval.SPaused or t < self.currT:
         # Restarting from a pause.
         self.privInitialize(t)
     else:
         if not self.__softStopped and t > self.softStopT:
             self.__step(self.softStopT - self.currT)
             self.__softStop()
             self.__step(t - self.softStopT)
         else:
             self.__step(t - self.currT)
         Interval.privStep(self, t)
Beispiel #28
0
def loadTSS():
    byGene={}
    with open(TSS,"rt") as IN:
        for line in IN:
            fields=line.rstrip().split()
            if(len(fields)!=4): continue
            (chr,pos,strand,gene)=fields
            pos=int(pos)
            rec=Interval(pos,pos+1)
            rec.chr=chr
            byGene[gene]=rec
    return byGene
Beispiel #29
0
    def __init__(self, tipo):
        assert type(tipo) == str, 'deve ser uma string'

        if (tipo == 'Uniclass'):
            self.restr = {'segmento': tipo, 'cartao': ['Básico'], 'plano_odonto': ['Básico'],
                          'limite_cred': Interval(1000, 4000)}
        elif (tipo == 'Varejo'):
            self.restr = {'segmento': tipo, 'cartao': ['Silver'], 'plano_odonto': ['Básico', 'Médio'],
                          'limite_cred': Interval(4000, 8000)}
        else:
            self.restr = {'segmento': tipo, 'cartao': ['Black', 'Platinum'], 'plano_odonto': ['Médio', 'Ouro'],
                          'limite_cred': Interval(8000, 50000)}
def getInterval(pos,exons):
    numExons=len(exons)
    for i in range(numExons):
        exon=exons[i]
        interval=None
        if(pos+2==exon.getBegin()):
            interval=Interval(exons[i-1].end,exon.getEnd())
        elif(pos==exon.getEnd()):
            interval=Interval(exon.getBegin(),exons[i+1].getBegin())
        if(interval): 
            interval.exon=i
            return interval
    return None
 def privStep(self, t):
     if self.node:
         if self.node.isEmpty():
             self.pause()
             return
     else:
         return
     self.node.setFluidPos(self.__calcPos(t))
     Interval.privStep(self, t)
     if self.collNode and self.collNode.getNumSolids() > 0:
         csolid = self.collNode.modifySolid(0)
         csolid.setT1(csolid.getT2())
         csolid.setT2(t)
Beispiel #32
0
class WebsiteMonitor:
    def __init__(self, url, checkInterval):
        self.url = url
        self.checkInterval = checkInterval
        # calculating the number of checks in an hour to initialize the history
        maxNumberOfChecksSaved = int(round(3600.0 / checkInterval))
        self.checksHistory = History(maxNumberOfChecksSaved)
        # the history may be used by other threads, thus we protect it with a lock
        self.historyLock = threading.Lock()
        # interval keeps track of the Interval instance that execute self.check every self.checkInterval
        self.interval = None
        # keeps track of when the monitor was launched
        self.startedMonitoringTime = time.time()

    def check(self):
        # HTTP HEAD request to the url of the monitored website
        # measurez
        success = True
        checkTime = time.time()
        try:
            r = requests.head(self.url, timeout=min(self.checkInterval, 5.0))
        except requests.exceptions.RequestException:
            success = False
        responseTime = time.time() - checkTime

        with self.historyLock:
            self.checksHistory.add((
                -1 if not (success) else r.status_code,
                checkTime,
                -1.0 if not (success) else responseTime,
            ))

    def startMonitoring(self):
        self.startedMonitoringTime = time.time()
        self.interval = Interval(self.checkInterval, self.check)

    def stopMonitoring(self):
        if self.interval != None:
            self.interval.cancel()
            self.interval = None

    #####
    # THREAD SAFE GETTER WITH CONDITION
    #####

    def getCheckHistoryForThePast(self, seconds):
        t = time.time()
        with self.historyLock:
            # check[1] = timestamp of the check
            return self.checksHistory.getValuesUntilCondition(
                lambda check: t - check[1] > seconds)
 def __init__(self, node, startPos = None, endPos = None, duration = None, startVel = None, endZ = None, gravityMult = None, name = None):
     self.node = node
     if name == None:
         name = '%s-%s' % (self.__class__.__name__, self.projectileIntervalNum)
         ProjectileInterval.projectileIntervalNum += 1
     
     args = (startPos, endPos, duration, startVel, endZ, gravityMult)
     self.needToCalcTraj = 0
     if startPos is None:
         self.trajectoryArgs = args
         self.needToCalcTraj = 1
     else:
         self._ProjectileInterval__calcTrajectory(*args)
     Interval.__init__(self, name, duration)
Beispiel #34
0
def loadHiC(expression):
    seen=set()
    with open(HIC,"rt") as IN:
        for line in IN:
            fields=line.rstrip().split()
            (chr1,begin1,end1,chr2,begin2,end2)=fields
            array=expression.get(chr1,None)
            if(array is None): return
            tad=Interval(int(begin1),int(end1))
            tad.type="anchor"
            tad.objects=[]
            key=chr1+" "+begin1+" "+end1
            if(key not in seen): array.append(tad)
            seen.add(key)
    def privInitialize(self, t):
        if self.state != CInterval.SPaused:
            # Restarting from a hard stop or just interrupting the
            # current play
            self.__softStart()
            if self.particleEffect:
                self.particleEffect.clearToInitial()
            self.currT = 0

        if self.particleEffect:
            for forceGroup in self.particleEffect.getForceGroupList():
                forceGroup.enable()

        Interval.privInitialize(self,t)
    def privInitialize(self, t):
        if self.state != CInterval.SPaused:
            # Restarting from a hard stop or just interrupting the
            # current play
            self.__softStart()
            if self.particleEffect:
                self.particleEffect.clearToInitial()
            self.currT = 0

        if self.particleEffect:
            for forceGroup in self.particleEffect.getForceGroupList():
                forceGroup.enable()

        Interval.privInitialize(self, t)
Beispiel #37
0
 def getRegionsAbove(self, cutoff):
     """getRegionsAbove() returns array of Intervals"""
     data = self.data
     if (self.isDiscrete()): raise Exception("track is not continuous")
     L = len(data)
     intervals = []
     begin = None
     for i in range(0, L):
         x = data[i]
         if (x > cutoff and (i == 0 or data[i - 1] <= cutoff)): begin = i
         elif (x <= cutoff and i > 0 and data[i - 1] > cutoff):
             intervals.append(Interval(begin, i))
     if (L > 0 and data[L - 1] > cutoff):
         intervals.append(Interval(begin, L))
     return intervals
Beispiel #38
0
 def getNonzeroRegions(self):
     """getNoneroRegions() returns array of Intervals"""
     data = self.data
     if (self.isDiscrete()): raise Exception("track is not continuous")
     L = len(data)
     intervals = []
     begin = None
     for i in range(0, L):
         x = data[i]
         if (x != 0 and (i == 0 or data[i - 1] == 0)): begin = i
         elif (x == 0 and i > 0 and data[i - 1] != 0):
             intervals.append(Interval(begin, i))
     if (L > 0 and data[L - 1] != 0):
         intervals.append(Interval(begin, L))
     return intervals
Beispiel #39
0
def loop():

    #initial input interval list
    while True:
        try:
            int_list=input("List of intervals?")
            

            if int_list.lower()=='quit':
                sys.exit(0)

            int_list=int_list.split(', ')
            intervals=[]

            for intv in int_list:
                
                intervals.append(Interval(intv))
            #break
           intervals=mergeOverlapping(intervals)
            
            
   

        except ValueError as message:
            print(message)
        except EOFError:
            sys.exit(0)
Beispiel #40
0
def calculate_intervals(data):
    begin = math.floor(get_minimum(data))
    end = math.ceil(get_maximum(data))
    count = round((end - begin) * 100 /
                  len(data))  # Calculation may be wrong for other data sets
    step = round((end - begin) / count, 1)

    intervals = [Interval() for i in range(count)]
    current_border = begin
    for interval in intervals:
        interval.begin = round(current_border, 1)
        interval.end = round(current_border + step, 1)
        current_border += step

    for value in data:
        if value != end:
            current_interval = intervals[int((value - begin) / step)]
        else:
            current_interval = intervals[count - 1]

        current_interval.count += 1
        current_interval.sum = round(current_interval.sum, 1) + value

    for interval in intervals:
        interval.probability = interval.count / (len(data) * step)
        if interval.count != 0:
            interval.mean = round(interval.sum / interval.count, 1)

    return intervals
Beispiel #41
0
 def computeIntervals(self, refPos):
     ops = self.ops
     n = len(ops)
     begin1 = 0
     begin2 = refPos
     for i in range(n):
         op = ops[i]
         L = op.getLength()
         end1 = begin1
         end2 = begin2
         if (op.advanceInQuery()): end1 += L
         if (op.advanceInRef()): end2 += L
         op.interval1 = Interval(begin1, end1)
         op.interval2 = Interval(begin2, end2)
         begin1 = end1
         begin2 = end2
Beispiel #42
0
def getInterval(firstTd):
    firstTd = firstTd.findAll(text=True)
    for time in range(len(TimeLessonsBegin)):
        if formatTime(firstTd[0]) == TimeLessonsBegin[time]:
            interval = Interval(time + 1, formatTime(firstTd[0]),
                                formatTime(firstTd[1]))
            return interval
    return None
Beispiel #43
0
    def conflicting(self, i: Interval, b: Tuple[str, str]) -> bool:
        """
		Check conflicting edge against interval
		@param i: Interval interval
		@param b: Tuple[str, str] edge
		@return: bool True when conflicting, otherwise False
		"""
        return not (i.empty()) and self.lowpt[i.high] > self.lowpt[b]
Beispiel #44
0
 def getContiguousRegions(self):
     """getContiguousRegions() returns an array of Interval objects
     with a "value" attribute added
     """
     data=self.data
     if(self.isDiscrete()): raise Exception("track is not continuous")
     L=len(data)
     intervals=[]
     begin=0
     for i in range(1,L):
         x=data[i]
         prev=data[i-1]
         if(x==prev): continue
         interval=Interval(begin,i)
         interval.value=prev
         intervals.append(interval)
         begin=i
     interval=Interval(begin,L)
     interval.value=data[L-1]
     intervals.append(interval)
     return intervals
Beispiel #45
0
 def insert(self, intervals, newInterval):
     
     if len(intervals) == 0:
         return [newInterval]
     
     r = []
     overlapWithNewInterval = Interval(newInterval.start, newInterval.end)
     didAddNewInterval = False
     
     for i in intervals:
         if (i.start < overlapWithNewInterval.start
               and i.end < overlapWithNewInterval.start):
             r.append(i)
         elif (i.start < overlapWithNewInterval.start
               and i.end >= overlapWithNewInterval.start
               and i.end <= overlapWithNewInterval.end):
             overlapWithNewInterval.start = i.start 
         elif (i.start < overlapWithNewInterval.start
               and i.end > overlapWithNewInterval.end):
             return intervals
         elif (i.start >= overlapWithNewInterval.start
               and i.end <= overlapWithNewInterval.end):
             pass
         elif (i.start >= overlapWithNewInterval.start
               and i.start <= overlapWithNewInterval.end
               and i.end >= overlapWithNewInterval.end):
             overlapWithNewInterval.end = i.end
         else:   # hxl: i is after overlapWithNewInterval
             if didAddNewInterval == False:
                 r.append(overlapWithNewInterval)
                 didAddNewInterval = True
             r.append(i)
     
     # hxl: It's possible that the new interval is not added yet!
     if didAddNewInterval == False:
         r.append(overlapWithNewInterval)
         didAddNewInterval = True
     return r
    def __init__(self, particleEffect, parent, worldRelative = 1, renderParent = None, duration = 0.0, softStopT = 0.0, cleanup = False, name = None):
        id = 'Particle-%d' % ParticleInterval.particleNum
        ParticleInterval.particleNum += 1
        if name == None:
            name = id
        self.particleEffect = particleEffect
        self.cleanup = cleanup
        if parent != None:
            self.particleEffect.reparentTo(parent)
        if worldRelative:
            renderParent = render
        if renderParent:
            for particles in self.particleEffect.getParticlesList():
                particles.setRenderParent(renderParent.node())

        self.__softStopped = False
        if softStopT == 0.0:
            self.softStopT = duration
        elif softStopT < 0.0:
            self.softStopT = duration + softStopT
        else:
            self.softStopT = softStopT
        Interval.__init__(self, name, duration)
        return
 def privInstant(self):
     self._ProjectileInterval__initialize()
     Interval.privInstant(self)
 def privInitialize(self, t):
     self._ProjectileInterval__initialize()
     Interval.privInitialize(self, t)
Beispiel #49
0
def parse(filehandle):

	intervalstart = False
	dimno = 0
	for line in filehandle:
		elems = [x.strip() for x in line.split('=')]
		# Filter useless lines
		if len(elems) < 2:
			continue
		if not intervalstart:
			if elems[0] == 'Object class':
				objectclass = elems[1]
				
			elif elems[0] == 'xmin':
				xmin = float(elems[1])
				
			elif elems[0] == 'xmax':
				xmax = float(elems[1])
				
			elif elems[0] == 'nx':
				size = int(elems[1])
				
			elif elems[0] == 'dx':
				shift = float(elems[1])
				
			elif elems[0] == 'x1':
				start = float(elems[1])

			elif elems[0] == 'maximumNumberOfCoefficients':
				dimensions = float(elems[1]) + 1
				intervalstart = True
				
				# Increase size to hold first Interval object as padding
				mfccTier = Tier(xmin, xmax, size+1, objectclass)
				mfccTier.shift = shift
				text = np.zeros(dimensions) 
				first = Interval(0.0, start, text)
				mfccTier.addInterval(first)

			continue
		elif intervalstart:					

			if elems[0] == 'c0':
				dimno = 0
				vec = np.zeros(dimensions)
				vec[dimno] = float(elems[1])

			elif elems[0] == 'numberOfCoefficients':
				assert int(elems[1]) <= dimensions

			elif elems[0][0] == 'c':
				dimno += 1
				#print(dimno)
				vec[dimno] = float(elems[1])
				#print(vec)
				if dimensions == dimno+1:
					#print('here, ...')
					begin = mfccTier[-1].xmax
					end = begin + mfccTier.shift
					interval = Interval(begin, end, vec)
					interval.viewable = False
					mfccTier.addInterval(interval)

	return mfccTier
Beispiel #50
0
#!/usr/bin/python


from Interval import Interval
import random


#
# Simple code for testing the Interval module, and showing how it is used
#

interval = Interval(1.5, 2.5)

for i in range(1, 100):
    interval.add(random.random() * 10)

print interval.getCount()

interval.clear()

print interval.getCount()

 def privFinalize(self):
     Interval.privFinalize(self)
     if self.cleanup and self.particleEffect:
         self.particleEffect.cleanup()
         self.particleEffect = None
def main():
    usage = "usage: %prog [options] chromInfo.bed"
    parser = OptionParser(usage)
    parser.add_option("--morgan", type="float", dest="morgan", default=100000000, help="physical length of 1 Morgan (default 100Mbp)")
    parser.add_option("--grandpaternaltwobit", type="string", dest="paternaltbf", help="2bit file representing (grand)paternal haplotype")
    parser.add_option("--grandmaternaltwobit", type="string", dest="maternaltbf", help="2bit file representing (grand)maternal haplotype")
    parser.add_option("--samplename", type="string", dest="samplename", help="sample name for which you are generating a gamete for", default="gamete")
    parser.add_option("--meiosis", type="int", dest="nmeiosis", help="meiotic event id (default 1) ", default=1)
    parser.add_option("--chromSize", type="int", dest="chromSize", help="length of chromosome", default=1000000)
    parser.add_option("--theta",  type="float", dest='theta', help='crossover rate', default=0)
    (options, args)=parser.parse_args()

    if options.maternaltbf == None:
        #pass
        sys.stderr.write("please provide maternal 2bit file!\n")
        exit(1)
    if options.paternaltbf == None:
        #pass
        sys.stderr.write("please provide paternal 2bit file!\n")
        exit(1)


    paternalname = str.split ( os.path.basename(options.paternaltbf) , '.')[0]
    maternalname = str.split ( os.path.basename(options.maternaltbf) , '.')[0]

    print paternalname, maternalname



    try:
        sys.stderr.write("opening paternal twobitfile...\n")
        twobit_paternal=bx.seq.twobit.TwoBitFile( open( options.paternaltbf ) )
    except:
        sys.stderr.write("unable to open paternal twobit file!\n")


    try:
        sys.stderr.write("opening maternal twobitfile...\n")
        twobit_maternal=bx.seq.twobit.TwoBitFile( open( options.maternaltbf ) )
    except:
        sys.stderr.write("unable to open maternal twobit file!\n")


    crossoverfh=open("sample."+options.samplename+".meiosis_"+str(options.nmeiosis)+".crossover.log", 'w')

    chromSizes=[]
    
    if options.theta == 0:
        lambdaval= float(options.chromSize)/float(options.morgan)
    else:
        lambdaval=options.theta


    sys.stderr.write("generating crossover intervals ...\n")
    
    gametesequence=[]

    chrom='1'
    
    crossoverfh.write("lambda value: " + str(lambdaval) + "\n")
    #get the number of crossovers by drawing from poisson
    n=np.random.poisson(lambdaval, 1)
    ncrossovers=n[0]
    #pick haplotype to pass
    flip=np.random.uniform(0,1)
    if flip <= .5: 
        haplotype="maternal"
    else:
        haplotype="paternal"
    intervalstring=''
    #now get the crossover points and record them in Interval format http://107.20.183.198/documentation.php#interval-format
    #if zero crossovers, then just past the entire chromosome
    if ncrossovers ==0:
        intervalstring="\t".join([haplotype, chrom, "+",'0', str(options.chromSize), str(ncrossovers),',',','])
        crossoverfh.write(chrom + " " + haplotype + " " + str(ncrossovers) + " " + str(options.chromSize) + "\n")
    #otherise randomly throw down crossover points according to uniform random
    else:
        chromsize=options.chromSize
        points=np.random.random_integers(1, chromsize, ncrossovers)
        points.sort()
        pointstrings=[]
        for p in points: pointstrings.append(str(p))
        outstring="\t".join(pointstrings)
        crossoverfh.write(chrom + " " + haplotype + " " + str(ncrossovers) + " " + ",".join(pointstrings) + "\n")
        if len(points) %2 == 0:
            #sys.stderr.write(haplotype + " " + chrom + " " + outstring +"\n")
            starts=list(points[1::2])
            ends=list(points[::2])
            ends.append(int(chromsize))
            starts.insert(0,0)
            startstrings=",".join(map(lambda x: str(x), starts))
            endstrings=",".join(map(lambda x: str(x), ends))
            intervalstring="\t".join([haplotype, chrom, "+",str(starts[0]), str(ends[-1]),str(ncrossovers), startstrings, endstrings])
               
        else:
            #sys.stderr.write(haplotype + " " + chrom + " " + outstring +"\n")
            starts=list(points[1::2])
            ends=list(points[0::2])
            starts.insert(0,0)
            startstrings=",".join(map(lambda x: str(x), starts))
            endstrings=",".join(map(lambda x: str(x), ends))
            #print starts
            #print ends
            intervalstring="\t".join([haplotype, chrom, "+",str(starts[0]), str(ends[-1]),str(ncrossovers), startstrings, endstrings])
            #print intervalstring
    print intervalstring
    intervalobj=Interval(intervalstring)
    if haplotype=='maternal':
        inbtwn_name='paternal'
    else:
        inbtwn_name='maternal'
    print intervalstring
        
    

    #extract DNA sequence from the maternal/paternal 2bit files according to the crossover intervals
    for (bedstring) in intervalobj.toBedstring():
        crossoverfh.write(bedstring+"\n")
        if haplotype=='maternal':
            (chr, start, end, name)=bedstring.split('\t')
            chr=maternalname
            bedstring="\t".join([ chr, start,end,name])
            print bedstring
            gametesequence += twoBitExtract(bedstring, twobit_maternal)
        else:
            (chr, start, end, name)=bedstring.split('\t')
            
            chr=paternalname
            bedstring="\t".join([ chr, start,end,name])
            print bedstring
            gametesequence += twoBitExtract(bedstring, twobit_paternal)
    #print "=="
    for bedstring in intervalobj.yieldInBtwnBedstring(inbtwn_name):
        crossoverfh.write(bedstring+"\n")
        if inbtwn_name=='maternal':
            (chr, start, end, name)=bedstring.split('\t')
            chr=maternalname
            bedstring="\t".join([ chr, start,end,name])
            gametesequence += twoBitExtract(bedstring, twobit_maternal)
        else:
            (chr, start, end, name)=bedstring.split('\t')
            chr=paternalname
            bedstring="\t".join([ chr, start,end,name])
            gametesequence += twoBitExtract(bedstring, twobit_paternal)
    if intervalobj.getLastSubIntervalEnd() != -1 and intervalobj.getLastSubIntervalEnd() < chromsize:
        #print inbtwn_name, chrom,  intervalobj.getLastSubIntervalEnd(), chromsize
        bedstring="\t".join(map( lambda(x): str(x), [ chrom, intervalobj.getLastSubIntervalEnd(), chromsize, inbtwn_name ] ) )
        crossoverfh.write(bedstring+"\n")
        if inbtwn_name=='maternal':
            (chr, start, end, name)=bedstring.split('\t')
            chr=maternalname
            bedstring="\t".join([ chr, start,end,name])
            gametesequence += twoBitExtract(bedstring, twobit_maternal)
        else:
            (chr, start, end, name)=bedstring.split('\t')
            chr=paternalname
            bedstring="\t".join([ chr, start,end,name])
            gametesequence += twoBitExtract(bedstring, twobit_paternal)
    #finally write out teh fasta file
    sys.stderr.write("writing gametic fasta file ... " + chrom + "\n")
    gametefastaname="_".join([chrom,"gamete", "meiosis"+str(options.nmeiosis), options.samplename])
    #writefasta("".join(gametesequence), chrom + "." + options.samplename, gametefastaname+".fa")
    writefasta("".join(gametesequence),options.samplename, options.samplename+".fa")
 def start(self,*args,**kwargs):
     self.particleEffect.clearToInitial()
     self.currT = 0
     Interval.start(self,*args,**kwargs)
 def privStep(self, t):
     self.node.setPos(self._ProjectileInterval__calcPos(t))
     Interval.privStep(self, t)
Beispiel #55
0
 def testTransposeTo(self):
         for Ch, Int in self.TranspositionTest:
                 TransposedInterval = Interval(Ch[0][0],Ch[0][1]).TransposeTo(Ch[1])
                 self.assertEqual(TransposedInterval.__repr__(), Int.__repr__())
                 print Interval(Ch[0][0],Ch[0][1]),"transposed to ",Ch[1]," gives",TransposedInterval
     else:
         begin=exons[exonIndex-1].getEnd()
         pos=exon.getBegin()-2
         end=exon.getEnd()
 else:
     if(siteType=="donor"):
         begin=exons[exonIndex-1].getEnd()
         pos=exon.getBegin()-2
         end=exon.getEnd()
     else:
         begin=exon.getBegin()
         pos=exon.getEnd()
         end=exons[exonIndex+1].getBegin()
 exclusions=exclude.get(substrate,{})
 begin=int(begin); pos=int(pos); end=int(end)
 interval=Interval(pos-70,pos+70)
 if(interval.begin<begin): interval.begin=begin
 if(interval.end>end): interval.end=end
 juncs=junctions.get(substrate,[])
 #print("substrate=",substrate)
 sum=0
 for junc in juncs:
     (substrate,begin,end,count)=junc
     key=str(begin)+"-"+str(end)
     if(exclusions.get(key,False)): 
         continue
     if(interval.contains(begin) or interval.contains(end)): sum+=int(count)
 geneCount=readCounts.get(geneID,0)
 #print("gene=",geneID)
 if(rex.find("(\S+)_\d",geneID)): geneID=rex[1]
 print(indiv,hap,geneID,transID,strand,exonIndex,siteType,interval.begin,pos,
 def privInitialize(self, t):
     self.__initialize()
     Interval.privInitialize(self, t)
 def privInstant(self):
     self.__initialize()
     Interval.privInstant(self)
 def privStep(self, t):
     self.node.setFluidPos(self.__calcPos(t))
     Interval.privStep(self, t)
Beispiel #60
0
    def __init__(self, node, startPos = None,
                 endPos = None, duration = None,
                 startVel = None, endZ = None,
                 wayPoint = None, timeToWayPoint = None,
                 gravityMult = None, name = None,
                 collNode = None):
        """
        You may specify several different sets of input parameters.
        (If startPos is not provided, it will be obtained from the node's
        position at the time that the interval is first started. Note that
        in this case you must provide a duration of some kind.)

        # go from startPos to endPos in duration seconds
        startPos, endPos, duration
        # given a starting velocity, go for a specific time period
        startPos, startVel, duration
        # given a starting velocity, go until you hit a given Z plane
        startPos, startVel, endZ
        # pass through wayPoint at time 'timeToWayPoint'. Go until
        # you hit a given Z plane
        startPos, wayPoint, timeToWayPoint, endZ

        You may alter gravity by providing a multiplier in 'gravityMult'.
        '2.' will make gravity twice as strong, '.5' half as strong.
        '-1.' will reverse gravity

        If collNode is not None, it should be an empty CollisionNode
        which will be filled with an appropriate CollisionParabola
        when the interval starts.  This CollisionParabola will be set
        to match the interval's parabola, and its t1, t2 values will
        be updated automatically as the interval plays.  It will *not*
        be automatically removed from the node when the interval
        finishes.

        """
        self.node = node
        self.collNode = collNode
        if self.collNode:
            if isinstance(self.collNode, NodePath):
                self.collNode = self.collNode.node()
            assert self.collNode.getNumSolids() == 0

        if name == None:
            name = '%s-%s' % (self.__class__.__name__,
                              self.projectileIntervalNum)
            ProjectileInterval.projectileIntervalNum += 1

        args = (startPos, endPos, duration, startVel, endZ,
                wayPoint, timeToWayPoint, gravityMult)
        self.implicitStartPos = 0
        if startPos is None:
            if duration is None:
                self.notify.error('must provide either startPos or duration')
            self.duration = duration
            # we can't calc the trajectory until we know our starting
            # position; delay until the interval is actually started
            self.trajectoryArgs = args
            self.implicitStartPos = 1
        else:
            self.trajectoryArgs = args
            self.__calcTrajectory(*args)

        Interval.__init__(self, name, self.duration)