Function: findNearestSegment

Finds the index of the nearest segment on the given cell state for
the specified coordinate pair.
333142
function(state, x, y)
	{
		var index = -1;
		
		if (state.absolutePoints.length > 0)
		{
			var last = state.absolutePoints[0];
			var min = null;
			
			for (var i = 1; i < state.absolutePoints.length; i++)
			{
				var current = state.absolutePoints[i];
				var dist = mxUtils.ptSegDistSq(last.x, last.y,
					current.x, current.y, x, y);
				
				if (min == null || dist < min)
				{
					min = dist;
					index = i - 1;
				}

				last = current;
			}
		}
		
		return index;
	}
1343061
private void checkEntry(long index, Segment segment, Segment compactSegment) {
    try (Entry entry = segment.get(index)) {
      // If an entry was found, only remove the entry from the segment if it's not a tombstone that has been released.
      if (entry != null) {
        checkEntry(index, entry, segment, compactSegment);
      } else {
        compactSegment.skip(1);
      }
    }
  }
52560
def findViewsContainingPoint(self, (x, y), _filter=None):
        '''
        
        '''

        if not _filter:
            _filter = lambda v: True

        return [v for v in self.views if (v.containsPoint((x,y)) and _filter(v))]
490139
function getIntersection(segment1, segment2) {
  var p0X = segment1[0][0];
  var p0Y = segment1[0][1];
  var p1X = segment1[1][0];
  var p1Y = segment1[1][1];
  var p2X = segment2[0][0];
  var p2Y = segment2[0][1];
  var p3X = segment2[1][0];
  var p3Y = segment2[1][1];

  var s1X, s1Y, s2X, s2Y;
  s1X = p1X - p0X;
  s1Y = p1Y - p0Y;
  s2X = p3X - p2X;
  s2Y = p3Y - p2Y;
  var s, t;
  s = (-s1Y * (p0X - p2X) + s1X * (p0Y - p2Y)) / (-s2X * s1Y + s1X * s2Y);
  t = (s2X * (p0Y - p2Y) - s2Y * (p0X - p2X)) / (-s2X * s1Y + s1X * s2Y);
  if (s >= 0 && s <= 1 && t >= 0 && t <= 1) {
    return {
      x: p0X + (t * s1X),
      y: p0Y + (t * s1Y)
    };
  }
  return null; // No collision
}
464707
function (x1, y1, x2, y2) {
		var polygons = this.polygons;
		for (var i = 0, n = polygons.length; i < n; i++)
			if (polygons[i].intersectsSegment(x1, y1, x2, y2)) return this.boundingBoxes[i];
		return null;
	}
45193
public Result<FindNearestPolyResult> findNearestPoly(float[] center, float[] halfExtents, QueryFilter filter) {

        float[] nearestPt = new float[] {center[0], center[1], center[2]};

        // Get nearby polygons from proximity grid.
        Result<List<Long>> polysResult = queryPolygons(center, halfExtents, filter);
        if (polysResult.failed()) {
            return Result.of(polysResult.status, polysResult.message);
        }
        List<Long> polys = polysResult.result;
        // Find nearest polygon amongst the nearby polygons.
        long nearest = 0;
        float nearestDistanceSqr = Float.MAX_VALUE;
        for (int i = 0; i < polys.size(); ++i) {
            long ref = polys.get(i);
            Result<ClosestPointOnPolyResult> closest = closestPointOnPoly(ref, center);
            boolean posOverPoly = closest.result.isPosOverPoly();
            float[] closestPtPoly = closest.result.getClosest();

            // If a point is directly over a polygon and closer than
            // climb height, favor that instead of straight line nearest point.
            float d = 0;
            float[] diff = vSub(center, closestPtPoly);
            if (posOverPoly) {
                Tupple2<MeshTile, Poly> tilaAndPoly = m_nav.getTileAndPolyByRefUnsafe(polys.get(i));
                MeshTile tile = tilaAndPoly.first;
                d = Math.abs(diff[1]) - tile.data.header.walkableClimb;
                d = d > 0 ? d * d : 0;
            } else {
                d = vLenSqr(diff);
            }

            if (d < nearestDistanceSqr) {
                nearestPt = closestPtPoly;
                nearestDistanceSqr = d;
                nearest = ref;
            }
        }

        return Result.success(new FindNearestPolyResult(nearest, nearestPt));
    }
248100
function(length, opt) {

            var segments = this.segments;
            var numSegments = segments.length;
            if (numSegments === 0) return null; // if segments is an empty array

            var fromStart = true;
            if (length < 0) {
                fromStart = false; // negative lengths mean start calculation from end point
                length = -length; // absolute value
            }

            opt = opt || {};
            var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision;
            var segmentSubdivisions = (opt.segmentSubdivisions === undefined) ? this.getSegmentSubdivisions({ precision: precision }) : opt.segmentSubdivisions;
            // not using localOpt

            var lastValidSegment; // visible AND differentiable (with a tangent)
            var l = 0; // length so far
            for (var i = (fromStart ? 0 : (numSegments - 1)); (fromStart ? (i < numSegments) : (i >= 0)); (fromStart ? (i++) : (i--))) {

                var segment = segments[i];
                var subdivisions = segmentSubdivisions[i];
                var d = segment.length({ precision: precision, subdivisions: subdivisions });

                if (segment.isDifferentiable()) {
                    if (length <= (l + d)) {
                        return segment.tangentAtLength(((fromStart ? 1 : -1) * (length - l)), { precision: precision, subdivisions: subdivisions });
                    }

                    lastValidSegment = segment;
                }

                l += d;
            }

            // if length requested is higher than the length of the path, return tangent of endpoint of last valid segment
            if (lastValidSegment) {
                var t = (fromStart ? 1 : 0);
                return lastValidSegment.tangentAtT(t);
            }

            // if no valid segment, return null
            return null;
        }
923403
def _findSegment(self, x):
        '''
        
        '''
        iLeft = 0
        iRight = len(self.xData) - 1
        while True:
            if iRight - iLeft <= 1:
                return iLeft
            i = (iRight + iLeft) / 2
            if x < self.xData[i]:
                iRight = i
            else:
                iLeft = i
1246165
function FindMaxSeparation(poly1, xf1, poly2, xf2) {
  var count1 = poly1.m_count;
  var count2 = poly2.m_count;
  var n1s = poly1.m_normals;
  var v1s = poly1.m_vertices;
  var v2s = poly2.m_vertices;
  var xf = Transform.mulTXf(xf2, xf1);

  var bestIndex = 0;
  var maxSeparation = -Infinity;
  for (var i = 0; i < count1; ++i) {
    // Get poly1 normal in frame2.
    var n = Rot.mulVec2(xf.q, n1s[i]);
    var v1 = Transform.mulVec2(xf, v1s[i]);

    // Find deepest point for normal i.
    var si = Infinity;
    for (var j = 0; j < count2; ++j) {
      var sij = Vec2.dot(n, v2s[j]) - Vec2.dot(n, v1);
      if (sij < si) {
        si = sij;
      }
    }

    if (si > maxSeparation) {
      maxSeparation = si;
      bestIndex = i;
    }
  }

  // used to keep last FindMaxSeparation call values
  FindMaxSeparation._maxSeparation = maxSeparation;
  FindMaxSeparation._bestIndex = bestIndex;
}
682280
function getNearestDataPoint(mouseX) {
            let dateFromInvertedX = xScale.invert(mouseX);
            let bisectDate = d3Array.bisector(getDate).left;
            let dataEntryIndex = bisectDate(dataByDate, dateFromInvertedX, 1);
            let dataEntryForXPosition = dataByDate[dataEntryIndex];
            let previousDataEntryForXPosition = dataByDate[dataEntryIndex - 1];
            let nearestDataPoint;

            if (previousDataEntryForXPosition && dataEntryForXPosition) {
                nearestDataPoint = findOutNearestDate(dateFromInvertedX, dataEntryForXPosition, previousDataEntryForXPosition);
            } else {
                nearestDataPoint = dataEntryForXPosition;
            }

            return nearestDataPoint;
        }
14539
function makeLooped(state, fromSegments, toSegments) {
		var end = Math.min(fromSegments.length, toSegments.length);

		for (var i = 0; i < end; ++i) {
			var fromSegment = fromSegments[i];
			var toSegment = toSegments[i];

			if (toSegment.reachable) {
				fromSegment.nextSegments.push(toSegment);
			}
			if (fromSegment.reachable) {
				toSegment.prevSegments.push(fromSegment);
			}
			fromSegment.allNextSegments.push(toSegment);
			toSegment.allPrevSegments.push(fromSegment);

			if (toSegment.allPrevSegments.length >= 2) {
				CodePathSegment.markPrevSegmentAsLooped(toSegment, fromSegment);
			}

			state.notifyLooped(fromSegment, toSegment);
		}
	}
582741
@Pure
	@SuppressWarnings("checkstyle:cyclomaticcomplexity")
	public PT getStartingPointFor(int index) {
		if ((index < 1) || (this.segmentList.size() <= 1)) {
			if (this.startingPoint != null) {
				return this.startingPoint;
			}
		} else {
			int idx = index;
			ST currentSegment = this.segmentList.get(idx);
			ST previousSegment = this.segmentList.get(--idx);

			// Because the two segments are the same
			// we must go deeper in the path elements
			// to detect the right segment
			int count = 0;
			while ((previousSegment != null) && (previousSegment.equals(currentSegment))) {
				currentSegment = previousSegment;
				idx--;
				previousSegment = (idx >= 0) ? this.segmentList.get(idx) : null;
				count++;
			}

			if (count > 0) {
				PT sp = null;
				if (previousSegment != null) {
					final PT p1 = currentSegment.getBeginPoint();
					final PT p2 = currentSegment.getEndPoint();
					final PT p3 = previousSegment.getBeginPoint();
					final PT p4 = previousSegment.getEndPoint();

					assert p1 != null && p2 != null && p3 != null && p4 != null;
					if (p1.equals(p3) || p1.equals(p4)) {
						sp = p1;
					} else if (p2.equals(p3) || p2.equals(p4)) {
						sp = p2;
					}

				} else {
					sp = this.startingPoint;
				}
				if (sp != null) {
					return ((count % 2) == 0) ? sp : currentSegment.getOtherSidePoint(sp);
				}

			} else if ((currentSegment != null) && (previousSegment != null)) {
				// if the two segments are different
				// it is simple to detect the
				// common point
				final PT p1 = currentSegment.getBeginPoint();
				final PT p2 = currentSegment.getEndPoint();
				final PT p3 = previousSegment.getBeginPoint();
				final PT p4 = previousSegment.getEndPoint();

				assert p1 != null && p2 != null && p3 != null && p4 != null;
				if (p1.equals(p3) || p1.equals(p4)) {
					return p1;
				}
				if (p2.equals(p3) || p2.equals(p4)) {
					return p2;
				}
			}
		}

		return null;
	}
573128
function adjustStartPoint(rowIndex, cellIndex, cell, isSelectedCell) {
            if (rowIndex === _startPoint.rowPos && _startPoint.colPos >= cell.cellIndex && cell.cellIndex <= cellIndex && !isSelectedCell) {
                _startPoint.colPos++;
            }
        }
716951
def calcRelativeSegCoords(self):   
        """"""

        from .. import sim

        localPopGids = list(set(sim.net.gid2lid.keys()).intersection(set(self.cellGids)))
        if localPopGids: 
            cell = sim.net.cells[sim.net.gid2lid[localPopGids[0]]]
        else:
            return -1

        ix = 0  # segment index

        p3dsoma = cell.getSomaPos()
        nseg = sum([sec['hObj'].nseg for sec in list(cell.secs.values())])
        
        p0 = np.zeros((3, nseg))  # hold the coordinates of segment starting points
        p1 = np.zeros((3, nseg))  # hold the coordinates of segment end points
        d0 = np.zeros(nseg) 
        d1 = np.zeros(nseg) 

        for sec in list(cell.secs.values()):
            hSec = sec['hObj']
            hSec.push()
            n3d = int(h.n3d())  # get number of n3d points in each section
            p3d = np.zeros((3, n3d))  # to hold locations of 3D morphology for the current section
            l3d = np.zeros(n3d)  # to hold locations of 3D morphology for the current section
            diam3d = np.zeros(n3d)  # to diameters

            for i in range(n3d):
                p3d[0, i] = h.x3d(i) - p3dsoma[0]
                p3d[1, i] = h.y3d(i) - p3dsoma[1]  # shift coordinates such to place soma at the origin.
                p3d[2, i] = h.z3d(i) - p3dsoma[2]
                diam3d[i] = h.diam3d(i)
                l3d[i] = h.arc3d(i)

            l3d /= hSec.L                  # normalize
            nseg = hSec.nseg
            
            l0 = np.zeros(nseg)     # keep range of segment starting point 
            l1 = np.zeros(nseg)     # keep range of segment ending point 
            
            for iseg, seg in enumerate(hSec):
                l0[iseg] = seg.x - 0.5*1/nseg   # x (normalized distance along the section) for the beginning of the segment
                l1[iseg] = seg.x + 0.5*1/nseg   # x for the end of the segment

            p0[0, ix:ix+nseg] = np.interp(l0, l3d, p3d[0, :])
            p0[1, ix:ix+nseg] = np.interp(l0, l3d, p3d[1, :])
            p0[2, ix:ix+nseg] = np.interp(l0, l3d, p3d[2, :])
            d0[ix:ix+nseg] = np.interp(l0, l3d, diam3d[:])

            p1[0, ix:ix+nseg] = np.interp(l1, l3d, p3d[0, :])
            p1[1, ix:ix+nseg] = np.interp(l1, l3d, p3d[1, :])
            p1[2, ix:ix+nseg] = np.interp(l1, l3d, p3d[2, :])
            d1[ix:ix+nseg] = np.interp(l1, l3d, diam3d[:])
            ix += nseg
            h.pop_section() 

        self._morphSegCoords = {}

        self._morphSegCoords['p0'] = p0
        self._morphSegCoords['p1'] = p1

        self._morphSegCoords['d0'] = d0
        self._morphSegCoords['d1'] = d1

        return self._morphSegCoords
1017479
def _learnFeatureLocationPair(self, newLocation, featureLocationInput,
                                featureLocationGrowthCandidates):
    

    potentialOverlaps = self.featureLocationConnections.computeActivity(
      featureLocationInput)
    matchingSegments = np.where(potentialOverlaps > self.learningThreshold)[0]

    # Cells with a active segment pair: reinforce the segment
    cellsForActiveSegments = self.featureLocationConnections.mapSegmentsToCells(
      self.activeFeatureLocationSegments)
    learningActiveSegments = self.activeFeatureLocationSegments[
      np.in1d(cellsForActiveSegments, newLocation)]
    remainingCells = np.setdiff1d(newLocation, cellsForActiveSegments)

    # Remaining cells with a matching segment pair: reinforce the best matching
    # segment pair.
    candidateSegments = self.featureLocationConnections.filterSegmentsByCell(
      matchingSegments, remainingCells)
    cellsForCandidateSegments = (
      self.featureLocationConnections.mapSegmentsToCells(
        candidateSegments))
    candidateSegments = candidateSegments[
      np.in1d(cellsForCandidateSegments, remainingCells)]
    onePerCellFilter = np2.argmaxMulti(potentialOverlaps[candidateSegments],
                                       cellsForCandidateSegments)
    learningMatchingSegments = candidateSegments[onePerCellFilter]

    newSegmentCells = np.setdiff1d(remainingCells, cellsForCandidateSegments)

    for learningSegments in (learningActiveSegments,
                             learningMatchingSegments):
      self._learn(self.featureLocationConnections, self.rng, learningSegments,
                  featureLocationInput, featureLocationGrowthCandidates,
                  potentialOverlaps,
                  self.initialPermanence, self.sampleSize,
                  self.permanenceIncrement, self.permanenceDecrement,
                  self.maxSynapsesPerSegment)

    numNewSynapses = len(featureLocationInput)

    if self.sampleSize != -1:
      numNewSynapses = min(numNewSynapses, self.sampleSize)

    if self.maxSynapsesPerSegment != -1:
      numNewSynapses = min(numNewSynapses, self.maxSynapsesPerSegment)

    newSegments = self.featureLocationConnections.createSegments(
      newSegmentCells)

    self.featureLocationConnections.growSynapsesToSample(
      newSegments, featureLocationGrowthCandidates, numNewSynapses,
      self.initialPermanence, self.rng)
224939
def closest_cell_center(self,x,y):
        
        return self.matrixidx2sheet(*self.sheet2matrixidx(x,y))
214941
public static int find(
		MemorySegment[] segments1, int offset1, int numBytes1,
		MemorySegment[] segments2, int offset2, int numBytes2) {
		if (numBytes2 == 0) { // quick way 1.
			return offset1;
		}
		if (inFirstSegment(segments1, offset1, numBytes1) &&
			inFirstSegment(segments2, offset2, numBytes2)) {
			byte first = segments2[0].get(offset2);
			int end = numBytes1 - numBytes2 + offset1;
			for (int i = offset1; i <= end; i++) {
				// quick way 2: equal first byte.
				if (segments1[0].get(i) == first &&
					segments1[0].equalTo(segments2[0], i, offset2, numBytes2)) {
					return i;
				}
			}
			return -1;
		} else {
			return findInMultiSegments(segments1, offset1, numBytes1, segments2, offset2, numBytes2);
		}
	}