Sample this motion track into discretized motion events.

        Args:
            contact_id: contact point id
            accuracy: motion minimum difference in space
            dt: sample time difference
551556
def discretize(self, contact_id=0, accuracy=0.004, dt=0.001):
        

        if not self.event_points:
            return []

        events = []
        action_dt = accuracy / self.speed
        dt = dt or action_dt

        ep0 = self.event_points[0]
        for _ in range(int(ep0[0] / dt)):
            events.append(['s', dt])
        events.append(['d', ep0[1], contact_id])
        for i, ep in enumerate(self.event_points[1:]):
            prev_ts = self.event_points[i][0]
            curr_ts = ep[0]
            p0 = self.event_points[i][1]
            p1 = ep[1]
            if p0 == p1:
                # hold
                for _ in range(int((curr_ts - prev_ts) / dt)):
                    events.append(['s', dt])
            else:
                # move
                dpoints = track_sampling([p0, p1], accuracy)
                for p in dpoints:
                    events.append(['m', p, contact_id])
                    for _ in range(int(action_dt / dt)):
                        events.append(['s', dt])

        events.append(['u', contact_id])
        return events
417446
def _check_contact(self):
        
        collision = False
        for contact in self.sim.data.contact[: self.sim.data.ncon]:
            if (
                self.sim.model.geom_id2name(contact.geom1) in self.finger_names
                or self.sim.model.geom_id2name(contact.geom2) in self.finger_names
            ):
                collision = True
                break
        return collision
1214587
def _determine_impact_coordtransform(self,deltaAngleTrackImpact,
                                         nTrackChunksImpact,
                                         timpact,impact_angle):
        """"""
        # Integrate the progenitor backward to the time of impact
        self._gap_progenitor_setup()
        # Sign of delta angle tells us whether the impact happens to the
        # leading or trailing arm, self._sigMeanSign contains this info
        if impact_angle > 0.:
            self._gap_leading= True
        else:
            self._gap_leading= False
        if (self._gap_leading and not self._leading) \
                or (not self._gap_leading and self._leading):
            raise ValueError('Modeling leading (trailing) impact for trailing (leading) arm; this is not allowed because it is nonsensical in this framework')
        self._gap_sigMeanSign= 1.
        if (self._gap_leading and self._progenitor_Omega_along_dOmega/self._sigMeanSign < 0.) \
                or (not self._gap_leading and self._progenitor_Omega_along_dOmega/self._sigMeanSign > 0.):
            self._gap_sigMeanSign= -1.
        # Determine how much orbital time is necessary for the progenitor's orbit at the time of impact to cover the part of the stream near the impact; we cover the whole leading (or trailing) part of the stream
        if nTrackChunksImpact is None:
            #default is floor(self._deltaAngleTrackImpact/0.15)+1
            self._nTrackChunksImpact= int(numpy.floor(self._deltaAngleTrackImpact/0.15))+1
        else:
            self._nTrackChunksImpact= nTrackChunksImpact
        if self._nTrackChunksImpact < 4: self._nTrackChunksImpact= 4
        dt= self._deltaAngleTrackImpact\
            /self._progenitor_Omega_along_dOmega\
            /self._sigMeanSign*self._gap_sigMeanSign
        self._gap_trackts= numpy.linspace(0.,2*dt,2*self._nTrackChunksImpact-1) #to be sure that we cover it
        #Instantiate an auxiliaryTrack, which is an Orbit instance at the mean frequency of the stream, and zero angle separation wrt the progenitor; prog_stream_offset is the offset between this track and the progenitor at zero angle (same as in streamdf, but just done at the time of impact rather than the current time)
        prog_stream_offset=\
            _determine_stream_track_single(self._aA,
                                           self._gap_progenitor,
                                           self._timpact, # around the t of imp
                                           self._progenitor_angle-self._timpact*self._progenitor_Omega,
                                           self._gap_sigMeanSign,
                                           self._dsigomeanProgDirection,
                                           lambda da: super(streamgapdf,self).meanOmega(da,offset_sign=self._gap_sigMeanSign,tdisrupt=self._tdisrupt-self._timpact,use_physical=False),
                                           0.) #angle = 0
        auxiliaryTrack= Orbit(prog_stream_offset[3])
        if dt < 0.:
            self._gap_trackts= numpy.linspace(0.,-2.*dt,2.*self._nTrackChunksImpact-1)
            #Flip velocities before integrating
            auxiliaryTrack= auxiliaryTrack.flip()
        auxiliaryTrack.integrate(self._gap_trackts,self._pot)
        if dt < 0.:
            #Flip velocities again
            auxiliaryTrack._orb.orbit[:,1]= -auxiliaryTrack._orb.orbit[:,1]
            auxiliaryTrack._orb.orbit[:,2]= -auxiliaryTrack._orb.orbit[:,2]
            auxiliaryTrack._orb.orbit[:,4]= -auxiliaryTrack._orb.orbit[:,4]
        #Calculate the actions, frequencies, and angle for this auxiliary orbit
        acfs= self._aA.actionsFreqs(auxiliaryTrack(0.),maxn=3,
                                    use_physical=False)
        auxiliary_Omega= numpy.array([acfs[3],acfs[4],acfs[5]]).reshape(3\
)
        auxiliary_Omega_along_dOmega= \
            numpy.dot(auxiliary_Omega,self._dsigomeanProgDirection)
        # compute the transformation using _determine_stream_track_single
        allAcfsTrack= numpy.empty((self._nTrackChunksImpact,9))
        alljacsTrack= numpy.empty((self._nTrackChunksImpact,6,6))
        allinvjacsTrack= numpy.empty((self._nTrackChunksImpact,6,6))
        thetasTrack= numpy.linspace(0.,self._deltaAngleTrackImpact,
                                    self._nTrackChunksImpact)
        ObsTrack= numpy.empty((self._nTrackChunksImpact,6))
        ObsTrackAA= numpy.empty((self._nTrackChunksImpact,6))
        detdOdJps= numpy.empty((self._nTrackChunksImpact))
        if self._multi is None:
            for ii in range(self._nTrackChunksImpact):
                multiOut= _determine_stream_track_single(self._aA,
                                           auxiliaryTrack,
                                           self._gap_trackts[ii]*numpy.fabs(self._progenitor_Omega_along_dOmega/auxiliary_Omega_along_dOmega), #this factor accounts for the difference in frequency between the progenitor and the auxiliary track, no timpact bc gap_tracks is relative to timpact
                                           self._progenitor_angle-self._timpact*self._progenitor_Omega,
                                           self._gap_sigMeanSign,
                                           self._dsigomeanProgDirection,
                                           lambda da: super(streamgapdf,self).meanOmega(da,offset_sign=self._gap_sigMeanSign,tdisrupt=self._tdisrupt-self._timpact,use_physical=False),
                                           thetasTrack[ii])
                allAcfsTrack[ii,:]= multiOut[0]
                alljacsTrack[ii,:,:]= multiOut[1]
                allinvjacsTrack[ii,:,:]= multiOut[2]
                ObsTrack[ii,:]= multiOut[3]
                ObsTrackAA[ii,:]= multiOut[4]
                detdOdJps[ii]= multiOut[5]
        else:
            multiOut= multi.parallel_map(\
                (lambda x: _determine_stream_track_single(self._aA,
                                           auxiliaryTrack,
                                           self._gap_trackts[x]*numpy.fabs(self._progenitor_Omega_along_dOmega/auxiliary_Omega_along_dOmega), #this factor accounts for the difference in frequency between the progenitor and the auxiliary track, no timpact bc gap_tracks is relative to timpact
                                           self._progenitor_angle-self._timpact*self._progenitor_Omega,
                                           self._gap_sigMeanSign,
                                           self._dsigomeanProgDirection,
                                           lambda da: super(streamgapdf,self).meanOmega(da,offset_sign=self._gap_sigMeanSign,tdisrupt=self._tdisrupt-self._timpact,use_physical=False),
                                           thetasTrack[x])),
                range(self._nTrackChunksImpact),
                numcores=numpy.amin([self._nTrackChunksImpact,
                                     multiprocessing.cpu_count(),
                                     self._multi]))
            for ii in range(self._nTrackChunksImpact):
                allAcfsTrack[ii,:]= multiOut[ii][0]
                alljacsTrack[ii,:,:]= multiOut[ii][1]
                allinvjacsTrack[ii,:,:]= multiOut[ii][2]
                ObsTrack[ii,:]= multiOut[ii][3]
                ObsTrackAA[ii,:]= multiOut[ii][4]
                detdOdJps[ii]= multiOut[ii][5]
        #Repeat the track calculation using the previous track, to get closer to it
        for nn in range(self.nTrackIterations):
            if self._multi is None:
                for ii in range(self._nTrackChunksImpact):
                    multiOut= _determine_stream_track_single(self._aA,
                                                             Orbit(ObsTrack[ii,:]),
                                                             0.,
                                                             self._progenitor_angle-self._timpact*self._progenitor_Omega,
                                                             self._gap_sigMeanSign,
                                                             self._dsigomeanProgDirection,
                                                             lambda da: super(streamgapdf,self).meanOmega(da,offset_sign=self._gap_sigMeanSign,tdisrupt=self._tdisrupt-self._timpact,use_physical=False),
                                                             thetasTrack[ii])
                    allAcfsTrack[ii,:]= multiOut[0]
                    alljacsTrack[ii,:,:]= multiOut[1]
                    allinvjacsTrack[ii,:,:]= multiOut[2]
                    ObsTrack[ii,:]= multiOut[3]
                    ObsTrackAA[ii,:]= multiOut[4]
                    detdOdJps[ii]= multiOut[5]
            else:
                multiOut= multi.parallel_map(\
                    (lambda x: _determine_stream_track_single(self._aA,Orbit(ObsTrack[x,:]),0.,
                                                              self._progenitor_angle-self._timpact*self._progenitor_Omega,
                                                              self._gap_sigMeanSign,
                                                              self._dsigomeanProgDirection,
                                                              lambda da: super(streamgapdf,self).meanOmega(da,offset_sign=self._gap_sigMeanSign,tdisrupt=self._tdisrupt-self._timpact,use_physical=False),
                                                              thetasTrack[x])),
                    range(self._nTrackChunksImpact),
                    numcores=numpy.amin([self._nTrackChunksImpact,
                                         multiprocessing.cpu_count(),
                                         self._multi]))
                for ii in range(self._nTrackChunksImpact):
                    allAcfsTrack[ii,:]= multiOut[ii][0]
                    alljacsTrack[ii,:,:]= multiOut[ii][1]
                    allinvjacsTrack[ii,:,:]= multiOut[ii][2]
                    ObsTrack[ii,:]= multiOut[ii][3]
                    ObsTrackAA[ii,:]= multiOut[ii][4]
                    detdOdJps[ii]= multiOut[ii][5]
        #Store the track
        self._gap_thetasTrack= thetasTrack
        self._gap_ObsTrack= ObsTrack
        self._gap_ObsTrackAA= ObsTrackAA
        self._gap_allAcfsTrack= allAcfsTrack
        self._gap_alljacsTrack= alljacsTrack
        self._gap_allinvjacsTrack= allinvjacsTrack
        self._gap_detdOdJps= detdOdJps
        self._gap_meandetdOdJp= numpy.mean(self._gap_detdOdJps)
        self._gap_logmeandetdOdJp= numpy.log(self._gap_meandetdOdJp)
        #Also calculate _ObsTrackXY in XYZ,vXYZ coordinates
        self._gap_ObsTrackXY= numpy.empty_like(self._gap_ObsTrack)
        TrackX= self._gap_ObsTrack[:,0]*numpy.cos(self._gap_ObsTrack[:,5])
        TrackY= self._gap_ObsTrack[:,0]*numpy.sin(self._gap_ObsTrack[:,5])
        TrackZ= self._gap_ObsTrack[:,3]
        TrackvX, TrackvY, TrackvZ=\
            bovy_coords.cyl_to_rect_vec(self._gap_ObsTrack[:,1],
                                        self._gap_ObsTrack[:,2],
                                        self._gap_ObsTrack[:,4],
                                        self._gap_ObsTrack[:,5])
        self._gap_ObsTrackXY[:,0]= TrackX
        self._gap_ObsTrackXY[:,1]= TrackY
        self._gap_ObsTrackXY[:,2]= TrackZ
        self._gap_ObsTrackXY[:,3]= TrackvX
        self._gap_ObsTrackXY[:,4]= TrackvY
        self._gap_ObsTrackXY[:,5]= TrackvZ
        return None
1079308
def get_point_source_position(self, id):
        

        pts = self._point_sources.values()[id]

        return pts.position.get_ra(), pts.position.get_dec()
161971
def watch_zone(self, zone_id):
        
        r = yield from self._send_cmd(
                "WATCH %s ON" % (zone_id.device_str(), ))
        self._watched_zones.add(zone_id)
        return r
521598
def _interpolate_stream_track(self):
        """"""
        if hasattr(self,'_interpolatedThetasTrack'):
            return None #Already did this
        TrackX= self._ObsTrack[:,0]*numpy.cos(self._ObsTrack[:,5])
        TrackY= self._ObsTrack[:,0]*numpy.sin(self._ObsTrack[:,5])
        TrackZ= self._ObsTrack[:,3]
        TrackvX, TrackvY, TrackvZ=\
            bovy_coords.cyl_to_rect_vec(self._ObsTrack[:,1],
                                        self._ObsTrack[:,2],
                                        self._ObsTrack[:,4],
                                        self._ObsTrack[:,5])
        #Interpolate
        self._interpTrackX=\
            interpolate.InterpolatedUnivariateSpline(self._thetasTrack,
                                                     TrackX,k=3)
        self._interpTrackY=\
            interpolate.InterpolatedUnivariateSpline(self._thetasTrack,
                                                     TrackY,k=3)
        self._interpTrackZ=\
            interpolate.InterpolatedUnivariateSpline(self._thetasTrack,
                                                     TrackZ,k=3)
        self._interpTrackvX=\
            interpolate.InterpolatedUnivariateSpline(self._thetasTrack,
                                                     TrackvX,k=3)
        self._interpTrackvY=\
            interpolate.InterpolatedUnivariateSpline(self._thetasTrack,
                                                     TrackvY,k=3)
        self._interpTrackvZ=\
            interpolate.InterpolatedUnivariateSpline(self._thetasTrack,
                                                     TrackvZ,k=3)
        #Now store an interpolated version of the stream track
        self._interpolatedThetasTrack=\
            numpy.linspace(0.,self._deltaAngleTrack,
                           self.nInterpolatedTrackChunks)
        self._interpolatedObsTrackXY= numpy.empty((len(self._interpolatedThetasTrack),6))
        self._interpolatedObsTrackXY[:,0]=\
            self._interpTrackX(self._interpolatedThetasTrack)
        self._interpolatedObsTrackXY[:,1]=\
            self._interpTrackY(self._interpolatedThetasTrack)
        self._interpolatedObsTrackXY[:,2]=\
            self._interpTrackZ(self._interpolatedThetasTrack)
        self._interpolatedObsTrackXY[:,3]=\
            self._interpTrackvX(self._interpolatedThetasTrack)
        self._interpolatedObsTrackXY[:,4]=\
            self._interpTrackvY(self._interpolatedThetasTrack)
        self._interpolatedObsTrackXY[:,5]=\
            self._interpTrackvZ(self._interpolatedThetasTrack)
        #Also in cylindrical coordinates
        self._interpolatedObsTrack= \
            numpy.empty((len(self._interpolatedThetasTrack),6))
        tR,tphi,tZ= bovy_coords.rect_to_cyl(self._interpolatedObsTrackXY[:,0],
                                            self._interpolatedObsTrackXY[:,1],
                                            self._interpolatedObsTrackXY[:,2])
        tvR,tvT,tvZ=\
            bovy_coords.rect_to_cyl_vec(self._interpolatedObsTrackXY[:,3],
                                        self._interpolatedObsTrackXY[:,4],
                                        self._interpolatedObsTrackXY[:,5],
                                        tR,tphi,tZ,cyl=True)
        self._interpolatedObsTrack[:,0]= tR
        self._interpolatedObsTrack[:,1]= tvR
        self._interpolatedObsTrack[:,2]= tvT
        self._interpolatedObsTrack[:,3]= tZ
        self._interpolatedObsTrack[:,4]= tvZ
        self._interpolatedObsTrack[:,5]= tphi
        return None
198829
def motion_cb(self, viewer, button, data_x, data_y):
        
        self.showxy(viewer, data_x, data_y)
        return True
208319
def update(self, source_clock_sample, target_clock_sample):
        
        if self._resolved_time is None or self.source_clock_overflow_period is None:
            self._resolved_time = decimal.Decimal(source_clock_sample)
            self._prev_source_sample = source_clock_sample
            self._prev_target_sample = target_clock_sample
        else:
            # Time between updates in the target clock domain
            tgt_delta = target_clock_sample - self._prev_target_sample
            self._prev_target_sample = target_clock_sample
            assert tgt_delta >= 0

            # Time between updates in the source clock domain
            src_delta = source_clock_sample - self._prev_source_sample
            self._prev_source_sample = source_clock_sample

            # Using the target clock we can resolve the integer ambiguity (number of overflows)
            full_cycles = int(round((tgt_delta - src_delta) / float(self.source_clock_overflow_period), 0))

            # Updating the source clock now; in two steps, in order to avoid error accumulation in floats
            self._resolved_time += decimal.Decimal(full_cycles * self.source_clock_overflow_period)
            self._resolved_time += decimal.Decimal(src_delta)

        return self._resolved_time
571946
def doTimestep(self, locationSDR, transitionSDR, featureSDR,
                 egocentricLocation, learn):
    

    for monitor in self.monitors.values():
      monitor.beforeTimestep(locationSDR, transitionSDR, featureSDR,
                             egocentricLocation, learn)

    params = {
      "newLocation": locationSDR,
      "deltaLocation": transitionSDR,
      "featureLocationInput": self.inputLayer.getActiveCells(),
      "featureLocationGrowthCandidates": self.inputLayer.getPredictedActiveCells(),
      "learn": learn,
    }
    self.locationLayer.compute(**params)
    for monitor in self.monitors.values():
      monitor.afterLocationCompute(**params)

    params = {
      "activeColumns": featureSDR,
      "basalInput": self.locationLayer.getActiveCells(),
      "apicalInput": self.objectLayer.getActiveCells(),
    }
    self.inputLayer.compute(**params)
    for monitor in self.monitors.values():
      monitor.afterInputCompute(**params)

    params = {
      "feedforwardInput": self.inputLayer.getActiveCells(),
      "feedforwardGrowthCandidates": self.inputLayer.getPredictedActiveCells(),
      "learn": learn,
    }
    self.objectLayer.compute(**params)
    for monitor in self.monitors.values():
      monitor.afterObjectCompute(**params)
1080277
def _sample_aAt(self,n):
        """"""
        # Use streamdf's _sample_aAt to generate unperturbed frequencies,
        # angles
        Om,angle,dt= super(streamgapdf,self)._sample_aAt(n)
        # Now rewind angles by timpact, apply the kicks, and run forward again
        dangle_at_impact= angle-numpy.tile(self._progenitor_angle.T,(n,1)).T\
            -(Om-numpy.tile(self._progenitor_Omega.T,(n,1)).T)*self._timpact
        dangle_par_at_impact= numpy.dot(dangle_at_impact.T,
                                        self._dsigomeanProgDirection)\
                                        *self._gap_sigMeanSign
        # Calculate and apply kicks (points not yet released have zero kick)
        dOr= self._kick_interpdOr(dangle_par_at_impact)
        dOp= self._kick_interpdOp(dangle_par_at_impact)
        dOz= self._kick_interpdOz(dangle_par_at_impact)
        Om[0,:]+= dOr
        Om[1,:]+= dOp
        Om[2,:]+= dOz
        angle[0,:]+=\
            self._kick_interpdar(dangle_par_at_impact)+dOr*self._timpact
        angle[1,:]+=\
            self._kick_interpdap(dangle_par_at_impact)+dOp*self._timpact
        angle[2,:]+=\
            self._kick_interpdaz(dangle_par_at_impact)+dOz*self._timpact
        return (Om,angle,dt)
696819
def pre_save(cls, sender, instance, *args, **kwargs):
        
        instance.constant_contact_id = str(instance.data['id'])
350826
function get($id = null)
        {
            # get the current microtime
            $now = microtime(true);

            # if no $id name is given for the interval
            if ($id == null) {
                # give it a counter interval name
                $cnt = count($this->intervals) ;
                $cnt++;
                $id = "~interval $cnt";
            }

            # if starting the stop watch
            if ($this->startTime == false) {
                # set start time interval to zero
                $incr = 0;
                # note the starting time
                $this->startTime = $now;
            } else {
                # compute time since the prior interval
                $incr = $now - $this->lastInterval;

                # if calling for microseconds round the time to microseconds otherwise to milliseconds
                $incr = ($this->microsec)
                    ? round($incr, 6)
                    : round($incr, 3);
            }

            # add it to the interval array
            $this->addInterval($id, $incr);

            # update the last interval time
            $this->lastInterval  = $now;

        }
1022415
public void record(double sample, TimeUnit timeUnit) {
        rotate();
        final long sampleNanos = (long) TimeUtils.convert(sample, timeUnit, TimeUnit.NANOSECONDS);
        for (AtomicLong max : ringBuffer) {
            updateMax(max, sampleNanos);
        }
    }
1277159
def send_to_contact(self, obj_id, contact_id):
        
        response = self._client.session.post(
            '{url}/{id}/send/contact/{contact_id}'.format(
                url=self.endpoint_url, id=obj_id, contact_id=contact_id
            )
        )
        return self.process_response(response)
759666
def _generate_time_steps(self, trajectory_list):
    """"""
    for single_trajectory in trajectory_list:
      assert isinstance(single_trajectory, trajectory.Trajectory)

      # Skip writing trajectories that have only a single time-step -- this
      # could just be a repeated reset.

      if single_trajectory.num_time_steps <= 1:
        continue

      for index, time_step in enumerate(single_trajectory.time_steps):

        # The first time-step doesn't have reward/processed_reward, if so, just
        # setting it to 0.0 / 0 should be OK.
        raw_reward = time_step.raw_reward
        if not raw_reward:
          raw_reward = 0.0

        processed_reward = time_step.processed_reward
        if not processed_reward:
          processed_reward = 0

        action = time_step.action
        if action is None:
          # The last time-step doesn't have action, and this action shouldn't be
          # used, gym's spaces have a `sample` function, so let's just sample an
          # action and use that.
          action = self.action_space.sample()
        action = gym_spaces_utils.gym_space_encode(self.action_space, action)

        if six.PY3:
          # py3 complains that, to_example cannot handle np.int64 !

          action_dtype = self.action_space.dtype
          if action_dtype in [np.int64, np.int32]:
            action = list(map(int, action))
          elif action_dtype in [np.float64, np.float32]:
            action = list(map(float, action))

          # same with processed_reward.
          processed_reward = int(processed_reward)

        assert time_step.observation is not None

        yield {
            TIMESTEP_FIELD: [index],
            ACTION_FIELD:
                action,
            # to_example errors on np.float32
            RAW_REWARD_FIELD: [float(raw_reward)],
            PROCESSED_REWARD_FIELD: [processed_reward],
            # to_example doesn't know bools
            DONE_FIELD: [int(time_step.done)],
            OBSERVATION_FIELD:
                gym_spaces_utils.gym_space_encode(self.observation_space,
                                                  time_step.observation),
        }
557688
def segments_touch_2D(ab, cd):
    '''
    
    '''
    return segments_colinear(ab, cd) | np.isfinite(segment_intersection_2D(ab, cd)[0])
280900
def _create_attach_record(self, id, timed):
        
        record = {}

        record[self._foreign_key] = self._parent.get_key()

        record[self._other_key] = id

        if timed:
            record = self._set_timestamps_on_attach(record)

        return record