Calculates assignment cost between two cells taking into account the movement of cells neighbours.

        :param CellFeatures d1: detection in first frame
        :param CellFeatures d2: detection in second frame
8915
def calculate_localised_cost(self, d1, d2, neighbours, motions):
        
        my_nbrs_with_motion = [n for n in neighbours[d1] if n in motions]

        my_motion = (d1.center[0] - d2.center[0], d1.center[1] - d2.center[1])

        if my_nbrs_with_motion == []:
            distance = euclidean_dist(d1.center, d2.center) / self.scale
        else:
            # it is not in motions if there is no trace (cell is considered to vanish)
            distance = min([euclidean_dist(my_motion, motions[n]) for n in my_nbrs_with_motion]) / self.scale

        area_change = 1 - min(d1.area, d2.area) / max(d1.area, d2.area)

        return distance + self.parameters_cost_iteration["area_weight"] * area_change
883485
def _learnTransition(self, prevActiveCells, deltaLocation, newLocation):
    

    prevLocationPotentialOverlaps = self.internalConnections.computeActivity(
      prevActiveCells)
    deltaPotentialOverlaps = self.deltaConnections.computeActivity(
      deltaLocation)

    matchingDeltaSegments = np.where(
      (prevLocationPotentialOverlaps >= self.learningThreshold) &
      (deltaPotentialOverlaps >= self.learningThreshold))[0]

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

    # Remaining cells with a matching segment pair: reinforce the best matching
    # segment pair.
    candidateSegments = self.internalConnections.filterSegmentsByCell(
      matchingDeltaSegments, remainingCells)
    cellsForCandidateSegments = self.internalConnections.mapSegmentsToCells(
      candidateSegments)
    candidateSegments = matchingDeltaSegments[
      np.in1d(cellsForCandidateSegments, remainingCells)]
    onePerCellFilter = np2.argmaxMulti(
      prevLocationPotentialOverlaps[candidateSegments] +
      deltaPotentialOverlaps[candidateSegments],
      cellsForCandidateSegments)
    learningMatchingDeltaSegments = candidateSegments[onePerCellFilter]

    newDeltaSegmentCells = np.setdiff1d(remainingCells, cellsForCandidateSegments)

    for learningSegments in (learningActiveDeltaSegments,
                             learningMatchingDeltaSegments):
      self._learn(self.internalConnections, self.rng, learningSegments,
                  prevActiveCells, prevActiveCells,
                  prevLocationPotentialOverlaps,
                  self.initialPermanence, self.sampleSize,
                  self.permanenceIncrement, self.permanenceDecrement,
                  self.maxSynapsesPerSegment)
      self._learn(self.deltaConnections, self.rng, learningSegments,
                  deltaLocation, deltaLocation, deltaPotentialOverlaps,
                  self.initialPermanence, self.sampleSize,
                  self.permanenceIncrement, self.permanenceDecrement,
                  self.maxSynapsesPerSegment)

    numNewLocationSynapses = len(prevActiveCells)
    numNewDeltaSynapses = len(deltaLocation)

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

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

    newPrevLocationSegments = self.internalConnections.createSegments(
      newDeltaSegmentCells)
    newDeltaSegments = self.deltaConnections.createSegments(
      newDeltaSegmentCells)

    assert np.array_equal(newPrevLocationSegments, newDeltaSegments)

    self.internalConnections.growSynapsesToSample(
      newPrevLocationSegments, prevActiveCells, numNewLocationSynapses,
      self.initialPermanence, self.rng)
    self.deltaConnections.growSynapsesToSample(
      newDeltaSegments, deltaLocation, numNewDeltaSynapses,
      self.initialPermanence, self.rng)
207771
public static float calculate(Map<String, Integer> features1, Map<String, Integer> features2) {
        TreeSet<String> keys = new TreeSet<String>(features1.keySet());
        keys.addAll(features2.keySet());

        float sum = 0.0f;
        for (String key : keys) {
            Integer c1 = features1.get(key);
            Integer c2 = features2.get(key);

            c1 = c1 == null ? 0 : c1;
            c2 = c2 == null ? 0 : c2;
            sum += 1.0 - Math.abs(c1 - c2) / (c1 + c2);
        }

        return sum / keys.size();
    }
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)
134812
private static boolean doEquals(DerValue d1, DerValue d2) {
        synchronized (d1.data) {
            synchronized (d2.data) {
                d1.data.reset();
                d2.data.reset();
                return d1.buffer.equals(d2.buffer);
            }
        }
    }
822721
def merge(self, other_cell):
        
        tc, tc_2 = self._tc, other_cell._tc
        merged_tc = tc.merge(tc_2)
        return _Cell(merged_tc, self._parent)
245812
function detectIntersection(a, b) {
  if (a instanceof Sphere) {
    if (b instanceof Sphere) {
      return sphereCollisionDetection.sphereVsSphere(a, b);
    } else if (b instanceof Aabb) {
      return sphereCollisionDetection.sphereVsAabb(a, b);
    } else if (b instanceof Capsule) {
      return sphereCollisionDetection.sphereVsCapsule(a, b);
    } else if (b instanceof Obb) {
      return sphereCollisionDetection.sphereVsObb(a, b);
    } else {
      return sphereCollisionDetection.sphereVsPoint(a, b);
    }
  } else if (a instanceof Aabb) {
    if (b instanceof Sphere) {
      return aabbCollisionDetection.aabbVsSphere(a, b);
    } else if (b instanceof Aabb) {
      return aabbCollisionDetection.aabbVsAabb(a, b);
    } else if (b instanceof Capsule) {
      return aabbCollisionDetection.aabbVsCapsule(a, b);
    } else if (b instanceof Obb) {
      return aabbCollisionDetection.aabbVsObb(a, b);
    } else {
      return aabbCollisionDetection.aabbVsPoint(a, b);
    }
  } else if (a instanceof Capsule) {
    if (b instanceof Sphere) {
      return capsuleCollisionDetection.capsuleVsSphere(a, b);
    } else if (b instanceof Aabb) {
      return capsuleCollisionDetection.capsuleVsAabb(a, b);
    } else if (b instanceof Capsule) {
      return capsuleCollisionDetection.capsuleVsCapsule(a, b);
    } else if (b instanceof Obb) {
      return capsuleCollisionDetection.capsuleVsObb(a, b);
    } else {
      return capsuleCollisionDetection.capsuleVsPoint(a, b);
    }
  } else if (a instanceof Obb) {
    if (b instanceof Sphere) {
      return obbCollisionDetection.obbVsSphere(a, b);
    } else if (b instanceof Aabb) {
      return obbCollisionDetection.obbVsAabb(a, b);
    } else if (b instanceof Capsule) {
      return obbCollisionDetection.obbVsCapsule(a, b);
    } else if (b instanceof Obb) {
      return obbCollisionDetection.obbVsObb(a, b);
    } else {
      return obbCollisionDetection.obbVsPoint(a, b);
    }
  } else {
    if (b instanceof Sphere) {
      return sphereCollisionDetection.sphereVsPoint(b, a);
    } else if (b instanceof Aabb) {
      return aabbCollisionDetection.aabbVsPoint(b, a);
    } else if (b instanceof Capsule) {
      return capsuleCollisionDetection.capsuleVsPoint(b, a);
    } else if (b instanceof Obb) {
      return obbCollisionDetection.obbVsPoint(b, a);
    } else {
      return false;
    }
  }
}
159140
def calc_cost(self, node_a, node_b):
        
        if node_b.x - node_a.x == 0 or node_b.y - node_a.y == 0:
            # direct neighbor - distance is 1
            ng = 1
        else:
            # not a direct neighbor - diagonal movement
            ng = SQRT2

        # weight for weighted algorithms
        if self.weighted:
            ng *= node_b.weight

        return node_a.g + ng
907656
def find(self,cell_designation,cell_filter=lambda x,c: 'c' in x and x['c'] == c):
        
        res = [i for i,sc in enumerate(self.spike_containers) if cell_filter(sc.meta,cell_designation)]
        if len(res) > 0:
            return res[0]
915281
function compareCells(a, b) {
  var n = a.length
    , t = a.length - b.length
    , min = Math.min
  if(t) {
    return t
  }
  switch(n) {
    case 0:
      return 0;
    case 1:
      return a[0] - b[0];
    case 2:
      var d = a[0]+a[1]-b[0]-b[1]
      if(d) {
        return d
      }
      return min(a[0],a[1]) - min(b[0],b[1])
    case 3:
      var l1 = a[0]+a[1]
        , m1 = b[0]+b[1]
      d = l1+a[2] - (m1+b[2])
      if(d) {
        return d
      }
      var l0 = min(a[0], a[1])
        , m0 = min(b[0], b[1])
        , d  = min(l0, a[2]) - min(m0, b[2])
      if(d) {
        return d
      }
      return min(l0+a[2], l1) - min(m0+b[2], m1)
    
    //TODO: Maybe optimize n=4 as well?
    
    default:
      var as = a.slice(0)
      as.sort()
      var bs = b.slice(0)
      bs.sort()
      for(var i=0; i<n; ++i) {
        t = as[i] - bs[i]
        if(t) {
          return t
        }
      }
      return 0
  }
}
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]
483181
public static int CrowdingDistanceCompare(Solution solution1, Solution solution2)
   {
      double crowding1 = solution1.getCrowdingDistance();
      double crowding2 = solution2.getCrowdingDistance();

      if (crowding1 > crowding2)
      {
         return -1;
      }
      else if (crowding1 < crowding2)
      {
         return 1;
      }
      else
      {
         return 0;
      }
   }
896018
function subdivideLoop(cells, positions) {
  var edges       = nskel(cells, 1)
  var e_incidence = top.incidence(edges, cells)
  var dual        = top.dual(cells, positions.length)
  var npositions  = []
  var ncells      = []
  var e_indices   = new Array(edges.length)
  var v_indices   = new Array(positions.length)
  
  for(var i=0; i<e_indices.length; ++i) {
    e_indices[i] = -1
  }
  for(var i=0; i<v_indices.length; ++i) {
    v_indices[i] = -1
  }
  
  for(var f=0; f<cells.length; ++f) {
    var face = cells[f]
    
    for(var d=0; d<3; ++d) {
      var v = face[d]
      var u = face[(d+1)%3]
      e[0] = v
      e[1] = u
      var e_ptr = top.findCell(edges, e)
      var e_idx = e_indices[e_ptr]
      
      if(e_idx >= 0) {
        e_verts[d] = e_idx
      } else {
        //Compute edge-vertex
        var wing = e_incidence[e_ptr]
        var v0 = positions[u]
        var v1 = positions[v]
        var vertex = new Array(3)
        
        if(wing.length === 2) {
          var v2 = positions[opposite(u, v, cells[wing[0]])]
          var v3 = positions[opposite(u, v, cells[wing[1]])]
          
          for(var i=0; i<3; ++i) {
            vertex[i] = (3.0 * (v0[i] + v1[i]) + v2[i] + v3[i]) / 8.0
          }
        } else {
          for(var i=0; i<3; ++i) {
            vertex[i] = 0.5 * (v0[i] + v1[i])
          }
        }
        
        //Store vertex and continue
        e_indices[e_ptr] = e_verts[d] = npositions.length
        npositions.push(vertex)
      }
      
      if(v_indices[v] >= 0) {
        v_verts[d] = v_indices[v]
      } else {
        //Compute vertex-vertex weight
        
        //First, extract vertex neighborhood (slow and stupid here)
        var star = dual[v]
        var nbhd = [v]
        for(var i=0; i<star.length; ++i) {
          var tri = cells[star[i]]
          for(var j=0; j<3; ++j) {
            if(nbhd.indexOf(tri[j]) !== -1) {
              nbhd.push(tri[j])
            }
          }
        }
        
        //Next, compute weights
        var beta = (star.length === 3 ? 3.0/16.0 : 3.0/(8.0*star.length) )
        var center_weight = 1.0 - star.length * beta
        
        //Finally sum up weights
        var pos  = positions[v]
        var vertex = [0.1,0.1,0.1]
        for(var i=0; i<3; ++i) {
          vertex[i] = center_weight * pos[i]
        }
        for(var i=1; i<nbhd.length; ++i) {
          var p = positions[nbhd[i]]
          for(var j=0; j<3; ++j) {
            vertex[j] += beta * p[j]
          }
        }

        //Store result and continue        
        v_verts[d] = v_indices[v] = npositions.length
        npositions.push(vertex)
      }
    }
    
    //Add subdivided faces
    ncells.push([v_verts[0], e_verts[0], e_verts[2]],
                [e_verts[0], e_verts[1], e_verts[2]],
                [e_verts[0], v_verts[1], e_verts[1]],
                [e_verts[1], v_verts[2], e_verts[2]])
  }
  
  return { positions: npositions, cells: ncells }
}
714485
def jaccard_similarity(self,s1,s2):
        
        a1 = self.inferred_types(s1)
        a2 = self.inferred_types(s2)
        num_union = len(a1.union(a2))
        if num_union == 0:
            return 0.0
        return len(a1.intersection(a2)) / num_union
486860
def dict_update_union(d1, d2):
    
    for k in d2:
        if k in d1:
            d1[k].update(d2[k])
        else:
            d1[k] = d2[k]
953655
def _sensoryComputeLearningMode(self, anchorInput):
    
    overlaps = self.connections.computeActivity(anchorInput,
                                                self.connectedPermanence)
    activeSegments = np.where(overlaps >= self.activationThreshold)[0]

    potentialOverlaps = self.connections.computeActivity(anchorInput)
    matchingSegments = np.where(potentialOverlaps >=
                                self.learningThreshold)[0]

    # Cells with a active segment: reinforce the segment
    cellsForActiveSegments = self.connections.mapSegmentsToCells(
      activeSegments)
    learningActiveSegments = activeSegments[
      np.in1d(cellsForActiveSegments, self.activeCells)]
    remainingCells = np.setdiff1d(self.activeCells, cellsForActiveSegments)

    # Remaining cells with a matching segment: reinforce the best
    # matching segment.
    candidateSegments = self.connections.filterSegmentsByCell(
      matchingSegments, remainingCells)
    cellsForCandidateSegments = (
      self.connections.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.connections, self.rng, learningSegments,
                  anchorInput, potentialOverlaps,
                  self.initialPermanence, self.sampleSize,
                  self.permanenceIncrement, self.permanenceDecrement,
                  self.maxSynapsesPerSegment)

    # Remaining cells without a matching segment: grow one.
    numNewSynapses = len(anchorInput)

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

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

    newSegments = self.connections.createSegments(newSegmentCells)

    self.connections.growSynapsesToSample(
      newSegments, anchorInput, numNewSynapses,
      self.initialPermanence, self.rng)
    self.activeSegments = activeSegments
    self.sensoryAssociatedCells = self.activeCells
79907
def _diff(d1,d2):
    '''
        
    '''
    d = {}
    ds = _diff_internal(d1,d2)
    for key in ds['vdiff']:
        d[key] = d1[key]
    for key in ds['kdiff']:
        d[key] = d1[key]
    return(d)