In-place transportation inferring of segments

        Returns:
            This track
173957
def infer_transportation_modes(self, dt_threshold=10):
        
        self.segments = [
            segment.infer_transportation_mode(dt_threshold=dt_threshold)
            for segment in self.segments
            ]
        return self
498460
def mapTrace(trace, net, delta, verbose=False):
    
    result = []
    paths = {}
    if verbose:
        print("mapping trace with %s points" % len(trace))
    for pos in trace:
        newPaths = {}
        candidates = net.getNeighboringEdges(pos[0], pos[1], delta)
        if len(candidates) == 0 and verbose:
            print("Found no candidate edges for %s,%s" % pos)
        for edge, d in candidates:
            if paths:
                minDist = 1e400
                minPath = None
                for path, dist in paths.iteritems():
                    if dist < minDist:
                        if edge == path[-1]:
                            minPath = path
                            minDist = dist
                        elif edge in path[-1].getOutgoing():
                            minPath = path + (edge,)
                            minDist = dist
                        else:
                            minPath = path + (edge,)
                            minDist = dist + euclidean(
                                path[-1].getToNode().getCoord(),
                                edge.getFromNode().getCoord())
                if minPath:
                    newPaths[minPath] = minDist + d * d
            else:
                newPaths[(edge,)] = d * d
        if not newPaths:
            if paths:
                result += [e.getID() for e in _getMinPath(paths)]
        paths = newPaths
    if paths:
        return result + [e.getID() for e in _getMinPath(paths)]
    return result
1248896
function () {
		var series = this,
			graphPath = [],
			segmentPath,
			singlePoints = []; // used in drawTracker

		// Divide into segments and build graph and area paths
		each(series.segments, function (segment) {
			
			segmentPath = series.getSegmentPath(segment);
			
			// add the segment to the graph, or a single point for tracking
			if (segment.length > 1) {
				graphPath = graphPath.concat(segmentPath);
			} else {
				singlePoints.push(segment[0]);
			}
		});

		// Record it for use in drawGraph and drawTracker, and return graphPath
		series.singlePoints = singlePoints;
		series.graphPath = graphPath;
		
		return graphPath;
		
	}
169378
function findSquaredDistanceBetweenSegments(segmentA, segmentB) {
  findClosestPointsFromSegmentToSegment(_segmentDistance_tmpVecA, _segmentDistance_tmpVecB,
      segmentA, segmentB);
  return vec3.squaredDistance(_segmentDistance_tmpVecA, _segmentDistance_tmpVecB);
}
398919
private void estimateAllFeatures(View seedA, View seedB ) {
		List<View> open = new ArrayList<>();

		// Add features for all the other views connected to the root view and determine the translation scale factor
		addUnvistedToStack(seedA, open);
		addUnvistedToStack(seedB, open);

		// Do a breath first search. The queue is first in first out
		while( !open.isEmpty() ) {
			if( stopRequested )
				return;
			if( verbose != null )
				verbose.println("### open.size="+open.size());

			// select the view with the 3D features. This view can be estimated which the highest degree of confience
			int bestCount = countFeaturesWith3D(open.get(0));
			int bestIndex = 0;

			for (int i = 1; i < open.size(); i++) {
				int count = countFeaturesWith3D(open.get(i));
				if( count > bestCount ) {
					bestCount = count;
					bestIndex = i;
				}
			}

			View v = open.remove(bestIndex);
			if( verbose != null )
				verbose.println("   processing view="+v.index+" | 3D Features="+bestCount);

			// Determine the view's location in the 3D view. This might have been previously estimated using
			// stereo and the estimated scale factor. That will be ignored and the new estimate used instead
			if( !determinePose(v) ) {
//				// The pose could not be determined, so remove it from the graph
//				if( verbose != null )
//					verbose.println("   Removing connection");
//				for (CameraMotion m : v.connections) {
//					CameraView a = m.destination(v);
//					a.connections.remove(m);
//					graph.edges.remove(m);
//				}
//				graph.nodes.remove(v);
//
//				for (int i = 0; i < graph.nodes.size(); i++) {
//					graph.nodes.get(i).index = i;
//				}

				// TODO mark instead of remove? Need a unit test for remove
				throw new RuntimeException("Crap handle this");
			} else {
				// If possible use triangulation from stereo
				addTriangulatedFeaturesForAllEdges(v);
				triangulateNoLocation(v);

				viewsAdded.add(v);

				// Update the open list
				addUnvistedToStack(v, open);
			}
		}
	}
644100
void transit(State source, Action act, State target)
    {
        int deprel = 0;
        int[] deprel_inference = new int[]{deprel};
        if (ActionUtils.is_shift(act))
        {
            target.shift(source);
        }
        else if (ActionUtils.is_left_arc(act, deprel_inference))
        {
            deprel = deprel_inference[0];
            target.left_arc(source, deprel);
        }
        else if (ActionUtils.is_right_arc(act, deprel_inference))
        {
            deprel = deprel_inference[0];
            target.right_arc(source, deprel);
        }
        else
        {
            System.err.printf("unknown transition in transit: %d-%d", act.name(), act.rel());
        }
    }
145746
def get_trajectories(self, index, rollout_length, history_length):
        
        indexes = np.arange(index - rollout_length + 1, index + 1, dtype=int)
        return self.get_transitions(indexes, history_length)
758099
def get_segments(self):
        """"""
        # Chunking
        chunk = {k: v.isChecked() for k, v in self.chunk.items()}
        lock_to_staging = self.lock_to_staging.get_value()
        epoch_dur = self.epoch_param['dur'].get_value()
        epoch_overlap = self.epoch_param['overlap_val'].value()
        epoch_step = None
        epoch = None

        if chunk['epoch']:
            if lock_to_staging:
                epoch = 'locked'
            else:
                epoch = 'unlocked'

                if self.epoch_param['step'].isChecked():
                    epoch_step = self.epoch_param['step_val'].get_value()

                    if epoch_step <= 0:
                        epoch_step = 0.1

        # Which channel(s)
        self.chan = self.get_channels() # chan name without group
        if not self.chan:
            return

        # Which event type(s)
        chan_full = None
        evt_type = None

        if chunk['event']:

            if self.evt_chan_only.get_value():
                chan_full = [i + ' (' + self.idx_group.currentText() + ''
                           ')' for i in self.chan]

            evt_type = self.idx_evt_type.selectedItems()
            if not evt_type:
                return
            else:
                evt_type = [x.text() for x in evt_type]

        # Which cycle(s)
        cycle = self.cycle = self.get_cycles()

        # Which stage(s)
        stage = self.idx_stage.selectedItems()
        if not stage:
            stage = self.stage = None
        else:
            stage = self.stage = [
                    x.text() for x in self.idx_stage.selectedItems()]

        # Concatenation
        cat = {k: v.get_value() for k, v in self.cat.items()}
        cat = (int(cat['cycle']), int(cat['stage']),
               int(cat['discontinuous']), int(cat['evt_type']))

        # Artefact event rejection
        reject_event = self.reject_event.get_value()
        if reject_event == 'channel-specific':
            chan_full = [i + ' (' + self.idx_group.currentText() + ''
                           ')' for i in self.chan]
            reject_artf = True
        elif reject_event == 'from any channel':
            reject_artf = True
        else:
            reject_artf = False

        # Other options
        min_dur = self.min_dur.get_value()
        reject_epoch = self.reject_epoch.get_value()

        # Generate title for summary plot
        self.title = self.make_title(chan_full, cycle, stage, evt_type)

        segments = fetch(self.parent.info.dataset,
                         self.parent.notes.annot, cat=cat,
                         evt_type=evt_type, stage=stage, cycle=cycle,
                         chan_full=chan_full, epoch=epoch,
                         epoch_dur=epoch_dur, epoch_overlap=epoch_overlap,
                         epoch_step=epoch_step, reject_epoch=reject_epoch,
                         reject_artf=reject_artf, min_dur=min_dur)

        return segments
151766
def q(segmentation, s1, s2):
    
    index1 = find_index(segmentation, s1)
    index2 = find_index(segmentation, s2)
    return index1 == index2
900638
private void sortTracksForEstimation() {
		// reset data structures
		planeSamples.reset();
		farAngles.reset();
		tracksOnPlane.clear();
		tracksFar.clear();

		// list of active tracks
		List<PointTrack> active = tracker.getActiveTracks(null);

		for (PointTrack t : active) {
			VoTrack p = t.getCookie();

			// compute normalized image coordinate
			pixelToNorm.compute(t.x, t.y, n);

			// rotate pointing vector into plane reference frame
			pointing.set(n.x, n.y, 1);
			GeometryMath_F64.mult(cameraToPlane.getR(), pointing, pointing);
			pointing.normalize();

			if (p.onPlane) {
				// see if it still intersects the plane
				if (pointing.y > 0) {
					// create data structure for robust motion estimation
					PlanePtPixel ppp = planeSamples.grow();
					ppp.normalizedCurr.set(n);
					ppp.planeKey.set(p.ground);

					tracksOnPlane.add(t);
				}
			} else {
				// if the point is not on the plane visually and (optionally) if it passes a strict y-axis rotation
				// test, consider using the point for estimating rotation.
				boolean allGood = pointing.y < 0;
				if (strictFar) {
					allGood = isRotationFromAxisY(t, pointing);
				}
				// is it still above the ground plane and only has motion consistent with rotation on ground plane axis
				if (allGood) {
					computeAngleOfRotation(t, pointing);
					tracksFar.add(t);
				}
			}
		}
	}
36813
void robotMove(int nx, int ny)
    {
        oldX = x;
        oldY = y;
        x = nx;
        y = ny;
        wx = nx;
        wy = ny;
        mx = x - oldX;
        my = y - oldY;
        moved = true;
    }
749446
def inferObjectsWithRandomMovements(self):
    
    for objectName, objectFeatures in self.objects.iteritems():
      self.reset()

      inferred = False
      prevTouchSequence = None

      for _ in xrange(4):

        while True:
          touchSequence = list(objectFeatures)
          random.shuffle(touchSequence)

          if prevTouchSequence is not None:
            if touchSequence[0] == prevTouchSequence[-1]:
              continue

          break

        for i, feature in enumerate(touchSequence):
          locationOnObject = (feature["top"] + feature["height"]/2,
                              feature["left"] + feature["width"]/2)
          self.move(objectName, locationOnObject)

          featureName = feature["name"]
          featureSDR = self.features[featureName]
          self.sense(featureSDR, learn=False)

          inferred = (
            set(self.objectLayer.getActiveCells()) ==
            set(self.objectRepresentations[objectName]) and

            set(self.inputLayer.getActiveCells()) ==
            set(self.inputRepresentations[(objectName,
                                           locationOnObject,
                                           featureName)]) and

            set(self.getActiveLocationCells()) ==
            set(self.locationRepresentations[(objectName, locationOnObject)]))

          if inferred:
            break

        prevTouchSequence = touchSequence

        if inferred:
          break
1129914
def inferObjectsWithRandomMovements(self, objectPlacements, maxTouches=20,
                                      settlingTime=2):
    

    for monitor in self.monitors.values():
      monitor.afterPlaceObjects(objectPlacements)

    for objectName, objectDict in self.objects.iteritems():
      self.reset()

      visitCounts = defaultdict(int)

      learnedObjectPlacement = self.learnedObjectPlacements[objectName]

      allocentricLocation = random.choice(objectDict.keys())
      nextTransitionSDR = np.empty(0, dtype="uint32")

      # Traverse the object until it is inferred.
      success = False

      for _ in xrange(maxTouches):
        featureName = objectDict[allocentricLocation]
        egocentricLocation = (allocentricLocation[0] +
                              objectPlacements[objectName][0],
                              allocentricLocation[1] +
                              objectPlacements[objectName][1])
        featureSDR = self.features[featureName]

        steps = ([nextTransitionSDR] +
                 [np.empty(0)]*settlingTime)
        for transitionSDR in steps:
          self.doTimestep(np.empty(0), transitionSDR, featureSDR,
                          egocentricLocation, learn=False)

        visitCounts[allocentricLocation] += 1

        # We should eventually infer the egocentric location where we originally
        # learned this location on the object.
        learnedEgocentricLocation = (
          allocentricLocation[0] + learnedObjectPlacement[0],
          allocentricLocation[1] + learnedObjectPlacement[1])

        if (set(self.objectLayer.getActiveCells()) ==
            set(self.objectRepresentations[objectName]) and

            set(self.inputLayer.getActiveCells()) ==
            set(self.inputRepresentations[(featureName,
                                           learnedEgocentricLocation)]) and

            set(self.locationLayer.getActiveCells()) ==
            set(self.locations[learnedEgocentricLocation])):
          success = True
          break
        else:
          allocentricLocation, transitionName = self._selectTransition(
            allocentricLocation, objectDict, visitCounts)
          nextTransitionSDR = self.transitions[transitionName]
938054
void estimateTranslation( DMatrixRMaj R , List<AssociatedPair> points , Vector3D_F64 T )
	{
		final int N = points.size();
		W.reshape(N*2,3);
		y.reshape(N*2,1);
		Wty.reshape(3,1);

		DMatrix3x3 Rtmp = new DMatrix3x3();
		ConvertDMatrixStruct.convert(R,Rtmp);

		int indexY = 0,indexW = 0;
		for (int i = 0; i < N; i++) {
			AssociatedPair p = points.get(i);

			// rotate into camera frame
			double u1 = Rtmp.a11*p.p1.x + Rtmp.a12*p.p1.y;
			double u2 = Rtmp.a21*p.p1.x + Rtmp.a22*p.p1.y;
			double u3 = Rtmp.a31*p.p1.x + Rtmp.a32*p.p1.y;

			W.data[indexW++] = 1;
			W.data[indexW++] = 0;
			W.data[indexW++] = -p.p2.x;
			W.data[indexW++] = 0;
			W.data[indexW++] = 1;
			W.data[indexW++] = -p.p2.y;

			y.data[indexY++] = p.p2.x*u3 - u1;
			y.data[indexY++] = p.p2.y*u3 - u2;
		}

		//======= Compute Pseudo Inverse
		// WW = inv(W^T*W)
		CommonOps_DDRM.multTransA(W,W,WW);
		CommonOps_DDRM.invert(WW);

		// W^T*y
		CommonOps_DDRM.multTransA(W,y,Wty);

		// translation = inv(W^T*W)*W^T*y
		W.reshape(3,1);
		CommonOps_DDRM.mult(WW,Wty,W);

		T.x = W.data[0];
		T.y = W.data[1];
		T.z = W.data[2];
	}
70886
def reverse_segment(path, n1, n2):
    
    q = path.copy()
    if n2 > n1:
        q[n1:(n2+1)] = path[n1:(n2+1)][::-1]
        return q
    else:
        seg = np.hstack((path[n1:], path[:(n2+1)]))[::-1]
        brk = len(q) - n1
        q[n1:] = seg[:brk]
        q[:(n2+1)] = seg[brk:]
        return q
523845
def infer_transportation_mode(self, clf, min_time):
        
        self.transportation_modes = speed_clustering(clf, self.points, min_time)
        return self
842895
function estimateCost(from, endPoints) {

        var min = Infinity;

        for (var i = 0, len = endPoints.length; i < len; i++) {
            var cost = from.manhattanDistance(endPoints[i]);
            if (cost < min) min = cost;
        }

        return min;
    }