Returns the parent of the specified cluster

@param relation the relation storing the objects
@param child the child to search the parent for
@param clustersMap the map containing the clusters
@return the parent of the specified cluster
343028
private Pair<long[], ArrayModifiableDBIDs> findParent(Relation<V> relation, Pair<long[], ArrayModifiableDBIDs> child, Object2ObjectMap<long[], List<ArrayModifiableDBIDs>> clustersMap) {
    Centroid child_centroid = ProjectedCentroid.make(child.first, relation, child.second);

    Pair<long[], ArrayModifiableDBIDs> result = null;
    int resultCardinality = -1;

    long[] childPV = child.first;
    int childCardinality = BitsUtil.cardinality(childPV);
    for(long[] parentPV : clustersMap.keySet()) {
      int parentCardinality = BitsUtil.cardinality(parentPV);
      if(parentCardinality >= childCardinality || (resultCardinality != -1 && parentCardinality <= resultCardinality)) {
        continue;
      }

      long[] pv = BitsUtil.andCMin(childPV, parentPV);
      if(BitsUtil.equal(pv, parentPV)) {
        List<ArrayModifiableDBIDs> parentList = clustersMap.get(parentPV);
        for(ArrayModifiableDBIDs parent : parentList) {
          NumberVector parent_centroid = ProjectedCentroid.make(parentPV, relation, parent);
          double d = weightedDistance(child_centroid, parent_centroid, parentPV);
          if(d <= 2 * epsilon) {
            result = new Pair<>(parentPV, parent);
            resultCardinality = parentCardinality;
            break;
          }
        }
      }
    }

    return result;
  }
418136
private TreeNode getParentTreeNode(TreeNode child) {
        TreeNode parentTreeNode = parentIndex.get(child);

        if (parentTreeNode == null)
            return null;

        // Makes sure the parent node is still present in the tree
        else if (contains(parentTreeNode.getQueryNode()))
            return parentTreeNode;
        else
            throw new RuntimeException("Internal error: points to a parent that is not (anymore) in the tree");
    }
1265163
public Clustering<MeanModel> run(Relation<NumberVector> relation) {
    final int dim = RelationUtil.dimensionality(relation);
    CFTree tree = cffactory.newTree(relation.getDBIDs(), relation);
    // The CFTree does not store points. We have to reassign them (and the
    // quality is better than if we used the initial assignment, because centers
    // move in particular in the beginning, so we always had many outliers.
    Map<ClusteringFeature, ModifiableDBIDs> idmap = new HashMap<ClusteringFeature, ModifiableDBIDs>(tree.leaves);
    for(DBIDIter iter = relation.iterDBIDs(); iter.valid(); iter.advance()) {
      ClusteringFeature cf = tree.findLeaf(relation.get(iter));
      ModifiableDBIDs ids = idmap.get(cf);
      if(ids == null) {
        idmap.put(cf, ids = DBIDUtil.newArray(cf.n));
      }
      ids.add(iter);
    }
    Clustering<MeanModel> result = new Clustering<>("BIRCH-leaves", "BIRCH leaves");
    for(Map.Entry<ClusteringFeature, ModifiableDBIDs> ent : idmap.entrySet()) {
      ClusteringFeature leaf = ent.getKey();
      double[] center = new double[dim];
      for(int i = 0; i < dim; i++) {
        center[i] = leaf.centroid(i);
      }
      result.addToplevelCluster(new Cluster<>(ent.getValue(), new MeanModel(center)));
    }
    return result;
  }
247156
def reverse_query(cls, parent_class, relation_key, child):
        
        q = leancloud.Query(parent_class)
        q.equal_to(relation_key, child._to_pointer())
        return q
337466
public Clustering<Model> run(Database database, Relation<V> relation) {
    // current dimensionality associated with each seed
    int dim_c = RelationUtil.dimensionality(relation);

    if(dim_c < l) {
      throw new IllegalStateException("Dimensionality of data < parameter l! " + "(" + dim_c + " < " + l + ")");
    }

    // current number of seeds
    int k_c = Math.min(relation.size(), k_i * k);

    // pick k0 > k points from the database
    List<ORCLUSCluster> clusters = initialSeeds(relation, k_c);

    double beta = FastMath.exp(-FastMath.log(dim_c / (double) l) * FastMath.log(1 / alpha) / FastMath.log(k_c / (double) k));

    IndefiniteProgress cprogress = LOG.isVerbose() ? new IndefiniteProgress("Current number of clusters:", LOG) : null;

    while(k_c > k) {
      // find partitioning induced by the seeds of the clusters
      assign(relation, clusters);

      // determine current subspace associated with each cluster
      for(ORCLUSCluster cluster : clusters) {
        if(cluster.objectIDs.size() > 0) {
          cluster.basis = findBasis(relation, cluster, dim_c);
        }
      }

      // reduce number of seeds and dimensionality associated with
      // each seed
      k_c = (int) Math.max(k, k_c * alpha);
      dim_c = (int) Math.max(l, dim_c * beta);
      merge(relation, clusters, k_c, dim_c, cprogress);
      if(cprogress != null) {
        cprogress.setProcessed(clusters.size(), LOG);
      }
    }
    assign(relation, clusters);

    LOG.setCompleted(cprogress);

    // get the result
    Clustering<Model> r = new Clustering<>("ORCLUS clustering", "orclus-clustering");
    for(ORCLUSCluster c : clusters) {
      r.addToplevelCluster(new Cluster<Model>(c.objectIDs, ClusterModel.CLUSTER));
    }
    return r;
  }
735339
public void createRelationFieldMap(Props props)
   {
      byte[] fieldMapData = null;
      for (Integer key : RELATION_KEYS)
      {
         fieldMapData = props.getByteArray(key);
         if (fieldMapData != null)
         {
            break;
         }
      }

      if (fieldMapData == null)
      {
         populateDefaultData(getDefaultRelationData());
      }
      else
      {
         createFieldMap(fieldMapData);
      }
   }
157978
public function persist(PersistenceContext $context, ParentChildMap $map)
    {
        /** @var Row[] $parentRows */
        $parentRows = [];
        /** @var object[] $children */
        $children = [];

        foreach ($map->getItems() as $key => $item) {
            $parentRow = $item->getParent();

            $hasChild = (bool)$item->getChild();
            if ($hasChild) {
                $parentRows[$key] = $parentRow;
                $children[$key]   = $item->getChild();
            }

            if ($this->objectIssetColumnName && !$this->isWithinValueObject) {
                $parentRow->setColumn($this->objectIssetColumnName, $hasChild);
            }
        }

        $this->disableLazyLoadingForRelations(function () use ($context, $children, $parentRows) {
            $this->mapper->persistAllToRows($context, $children, $parentRows);
        });
    }
1366707
@SuppressWarnings("unchecked")
  protected void fromHierarchicalMap(Map<String, Object> map) {

    for (Entry<String, Object> entry : map.entrySet()) {
      SimpleConfigProperties child = (SimpleConfigProperties) getChild(entry.getKey(), true);
      Object childObject = entry.getValue();
      if (childObject instanceof Map) {
        child.fromHierarchicalMap((Map<String, Object>) childObject);
      } else {
        child.value = childObject.toString();
      }
    }
  }
802885
public Clustering<Model> run(Relation<V> relation) {
    final DBIDs ids = relation.getDBIDs();

    // Degenerate result:
    if(ids.size() < minpts) {
      Clustering<Model> result = new Clustering<>("DBSCAN Clustering", "dbscan-clustering");
      result.addToplevelCluster(new Cluster<Model>(ids, true, ClusterModel.CLUSTER));
      return result;
    }

    double gridwidth = this.gridwidth; // local copy.
    if(gridwidth < 2. * epsilon) {
      LOG.warning("Invalid grid width (less than 2*epsilon, recommended 10*epsilon). Increasing grid width automatically.");
      gridwidth = 2. * epsilon;
    }
    return new Instance<V>(getDistanceFunction(), epsilon, minpts, gridwidth).run(relation);
  }
770048
public Clustering<PrototypeModel<O>> run(Relation<O> relation) {
    RangeQuery<O> rq = relation.getRangeQuery(getDistanceFunction(), threshold);

    ModifiableDBIDs seen = DBIDUtil.newHashSet(relation.size());
    Clustering<PrototypeModel<O>> clustering = new Clustering<>("Prototype clustering", "prototype-clustering");

    int queries = 0;
    FiniteProgress prog = LOG.isVerbose() ? new FiniteProgress("Leader clustering", relation.size(), LOG) : null;
    for(DBIDIter it = relation.iterDBIDs(); it.valid() && seen.size() < relation.size(); it.advance()) {
      if(seen.contains(it)) {
        continue;
      }
      DoubleDBIDList res = rq.getRangeForDBID(it, threshold);
      ++queries;
      ModifiableDBIDs ids = DBIDUtil.newArray(res.size());
      for(DBIDIter cand = res.iter(); cand.valid(); cand.advance()) {
        if(seen.add(cand)) {
          LOG.incrementProcessed(prog);
          ids.add(cand);
        }
      }
      assert (ids.size() > 0 && ids.contains(it));
      PrototypeModel<O> mod = new SimplePrototypeModel<>(relation.get(it));
      clustering.addToplevelCluster(new Cluster<>(ids, mod));
    }
    LOG.statistics(new LongStatistic(this.getClass().getName() + ".queries", queries));
    LOG.ensureCompleted(prog);
    return clustering;
  }
174538
public PointerDensityHierarchyRepresentationResult run(Database db, Relation<O> relation) {
    final DistanceQuery<O> distQ = db.getDistanceQuery(relation, getDistanceFunction());
    final KNNQuery<O> knnQ = db.getKNNQuery(distQ, minPts);
    // We need array addressing later.
    final ArrayDBIDs ids = DBIDUtil.ensureArray(relation.getDBIDs());

    // 1. Compute the core distances
    // minPts + 1: ignore query point.
    final WritableDoubleDataStore coredists = computeCoreDists(ids, knnQ, minPts);

    final int numedges = ids.size() - 1;
    DoubleLongHeap heap = new DoubleLongMinHeap(numedges);
    // 2. Build spanning tree.
    FiniteProgress mprog = LOG.isVerbose() ? new FiniteProgress("Computing minimum spanning tree (n-1 edges)", numedges, LOG) : null;
    PrimsMinimumSpanningTree.processDense(ids, //
        new HDBSCANAdapter(ids, coredists, distQ), //
        new HeapMSTCollector(heap, mprog, LOG));
    LOG.ensureCompleted(mprog);
    // Storage for pointer representation:
    WritableDBIDDataStore pi = DataStoreUtil.makeDBIDStorage(ids, DataStoreFactory.HINT_HOT | DataStoreFactory.HINT_STATIC);
    WritableDoubleDataStore lambda = DataStoreUtil.makeDoubleStorage(ids, DataStoreFactory.HINT_HOT | DataStoreFactory.HINT_STATIC, Double.POSITIVE_INFINITY);
    convertToPointerRepresentation(ids, heap, pi, lambda);

    return new PointerDensityHierarchyRepresentationResult(ids, pi, lambda, distQ.getDistanceFunction().isSquared(), coredists);
  }
559065
private void resolveParents(final Map<Integer, Set<GeoName>> childMap) throws IOException {
        Map<Integer, GeoName> parentMap = new HashMap<Integer, GeoName>();
        Map<Integer, Set<GeoName>> grandParentMap = new HashMap<Integer, Set<GeoName>>();
        for (Integer parentId : childMap.keySet()) {
            // Lucene query used to look for exact match on the "geonameID" field
            Query q = NumericRangeQuery.newIntRange(GEONAME_ID.key(), parentId, parentId, true, true);
            TopDocs results = indexSearcher.search(q, null, 1, POPULATION_SORT);
            if (results.scoreDocs.length > 0) {
                Document doc = indexSearcher.doc(results.scoreDocs[0].doc);
                GeoName parent = BasicGeoName.parseFromGeoNamesRecord(doc.get(GEONAME.key()), doc.get(PREFERRED_NAME.key()));
                parentMap.put(parent.getGeonameID(), parent);
                if (!parent.isAncestryResolved()) {
                    Integer grandParentId = PARENT_ID.getValue(doc);
                    if (grandParentId != null) {
                        Set<GeoName> geos = grandParentMap.get(grandParentId);
                        if (geos == null) {
                            geos = new HashSet<GeoName>();
                            grandParentMap.put(grandParentId, geos);
                        }
                        geos.add(parent);
                    }
                }
            } else {
                LOG.error("Unable to find parent GeoName [{}]", parentId);
            }
        }

        // find all parents of the parents
        if (!grandParentMap.isEmpty()) {
            resolveParents(grandParentMap);
        }

        // set parents of children
        for (Integer parentId : childMap.keySet()) {
            GeoName parent = parentMap.get(parentId);
            if (parent == null) {
                LOG.info("Unable to find parent with ID [{}]", parentId);
                continue;
            }
            for (GeoName child : childMap.get(parentId)) {
                child.setParent(parent);
            }
        }
    }
736841
public function persist(PersistenceContext $context, ParentChildrenMap $map)
    {
        $primaryKey        = $map->getPrimaryKeyColumn();
        $relatedPrimaryKey = $this->mapper->getPrimaryTable()->getPrimaryKeyColumnName();
        $children          = $map->getAllChildren();
        $rows              = $this->reference->syncRelated($context, [], $children);

        /** @var Row[] $childRowMap */
        $childRowMap = [];
        foreach ($children as $key => $child) {
            $childRowMap[Identity::hash($child)] = $rows[$key];
        }

        // Clear join rows and reinsert to sync
        if ($map->hasAnyParentsWithPrimaryKeys()) {
            $delete = Delete::from($this->joinTable)
                ->where($this->getInvalidatedRelationExpr($map));
            $context->queue($delete);
        }

        $parentIdColumn  = $this->parentForeignKeyColumn->getName();
        $relatedIdColumn = $this->relatedForeignKeyColumn->getName();
        $joinTableRows   = [];

        foreach ($map->getItems() as $item) {
            $parent = $item->getParent();

            foreach ($item->getChildren() as $child) {
                $joinRow = new Row($this->joinTable);

                if ($parent->hasColumn($primaryKey)) {
                    $joinRow->setColumn($parentIdColumn, $parent->getColumn($primaryKey));
                } else {
                    $parent->onInsertPrimaryKey(function ($id) use ($joinRow, $parentIdColumn) {
                        $joinRow->setColumn($parentIdColumn, $id);
                    });
                }

                $childRow = $childRowMap[Identity::hash($child)];
                if ($childRow->hasColumn($relatedPrimaryKey)) {
                    $joinRow->setColumn($relatedIdColumn, $childRow->getColumn($relatedPrimaryKey));
                } else {
                    $childRow->onInsertPrimaryKey(function ($id) use ($joinRow, $relatedIdColumn) {
                        $joinRow->setColumn($relatedIdColumn, $id);
                    });
                }

                $joinTableRows[] = $joinRow;
            }
        }

        if (!empty($joinTableRows)) {
            $context->upsert(new RowSet($this->joinTable, $joinTableRows));
        }
    }
902335
private static Map<String,List<Node>> getChildNodes(Node parent) {
		if (parent==null)
			return Collections.emptyMap();

		Map<String,List<Node>> children = new HashMap<String,List<Node>>();

		NodeList nodes = parent.getChildNodes();
		int nNodes = nodes.getLength();
		for (int i=0; i<nNodes; i++) {
			Node node = nodes.item(i);
			if (node.getNodeType()!=Node.ELEMENT_NODE)
				continue;

			String name = node.getNodeName();
			List<Node> namesakes = children.get(name);
			if (namesakes==null) {
				namesakes = new ArrayList<Node>();
				children.put(name, namesakes);
			}
			namesakes.add(node);
		}

		return children;
	}
873032
public <T> List<T> getChildEntries(Class<?> parentClass, String parentId,
			Class<T> classs) throws RedmineException {
		final EntityConfig<T> config = getConfig(classs);
		final URI uri = getURIConfigurator().getChildObjectsURI(parentClass,
				parentId, classs);

		HttpGet http = new HttpGet(uri);
		String response = getCommunicator().sendRequest(http);
		final JSONObject responseObject;
		try {
			responseObject = RedmineJSONParser.getResponse(response);
			return JsonInput.getListNotNull(responseObject,
					config.multiObjectName, config.parser);
		} catch (JSONException e) {
			throw new RedmineFormatException("Bad categories response " + response, e);
		}
	}
562658
List<V> get( K key ) {
        List<V> result = map.get( key );
        if( parent != null ) {
            List<V> resultParent = parent.get( key );
            if( result == null ) {
                return resultParent;
            } else if( resultParent == null ){
                return result;
            } else {
                for( V value : resultParent ) {
                    if( !result.contains( value ) ) {
                        result.add( value );
                    }
                }
            }
        }
        return result;
    }
672734
public <T> List<T> getChildEntries(Class<?> parentClass, String parentKey, Class<T> classs) throws RedmineException {
		final EntityConfig<T> config = getConfig(classs);
		final URI uri = getURIConfigurator().getChildObjectsURI(parentClass,
				parentKey, classs, new BasicNameValuePair("limit", String.valueOf(objectsPerPage)));

		HttpGet http = new HttpGet(uri);
		String response = send(http);
		final JSONObject responseObject;
		try {
			responseObject = RedmineJSONParser.getResponse(response);
			return JsonInput.getListNotNull(responseObject, config.multiObjectName, config.parser);
		} catch (JSONException e) {
			throw new RedmineFormatException("Bad categories response " + response, e);
		}
	}