Build a k-d tree from the given set of data.
505274
private Node buildNode(double[][] data, int begin, int end) {
        int d = data[0].length;

        // Allocate the node
        Node node = new Node(d);

        // Fill in basic info
        node.count = end - begin;
        node.index = begin;

        // Calculate the bounding box
        double[] lowerBound = new double[d];
        double[] upperBound = new double[d];

        for (int i = 0; i < d; i++) {
            lowerBound[i] = data[index[begin]][i];
            upperBound[i] = data[index[begin]][i];
        }

        for (int i = begin + 1; i < end; i++) {
            for (int j = 0; j < d; j++) {
                double c = data[index[i]][j];
                if (lowerBound[j] > c) {
                    lowerBound[j] = c;
                }
                if (upperBound[j] < c) {
                    upperBound[j] = c;
                }
            }
        }

        // Calculate bounding box stats
        double maxRadius = -1;
        int splitIndex = -1;
        for (int i = 0; i < d; i++) {
            node.center[i] = (lowerBound[i] + upperBound[i]) / 2;
            node.radius[i] = (upperBound[i] - lowerBound[i]) / 2;
            if (node.radius[i] > maxRadius) {
                maxRadius = node.radius[i];
                splitIndex = i;
            }
        }

        // If the max spread is 0, make this a leaf node
        if (maxRadius < 1E-10) {
            node.lower = node.upper = null;
            System.arraycopy(data[index[begin]], 0, node.sum, 0, d);

            if (end > begin + 1) {
                int len = end - begin;
                for (int i = 0; i < d; i++) {
                    node.sum[i] *= len;
                }
            }

            node.cost = 0;
            return node;
        }

        // Partition the data around the midpoint in this dimension. The
        // partitioning is done in-place by iterating from left-to-right and
        // right-to-left in the same way that partioning is done in quicksort.
        double splitCutoff = node.center[splitIndex];
        int i1 = begin, i2 = end - 1, size = 0;
        while (i1 <= i2) {
            boolean i1Good = (data[index[i1]][splitIndex] < splitCutoff);
            boolean i2Good = (data[index[i2]][splitIndex] >= splitCutoff);

            if (!i1Good && !i2Good) {
                int temp = index[i1];
                index[i1] = index[i2];
                index[i2] = temp;
                i1Good = i2Good = true;
            }

            if (i1Good) {
                i1++;
                size++;
            }

            if (i2Good) {
                i2--;
            }
        }

        // Create the child nodes
        node.lower = buildNode(data, begin, begin + size);
        node.upper = buildNode(data, begin + size, end);

        // Calculate the new sum and opt cost
        for (int i = 0; i < d; i++) {
            node.sum[i] = node.lower.sum[i] + node.upper.sum[i];
        }

        double[] mean = new double[d];
        for (int i = 0; i < d; i++) {
            mean[i] = node.sum[i] / node.count;
        }

        node.cost = getNodeCost(node.lower, mean) + getNodeCost(node.upper, mean);
        return node;
    }
1196906
def from_data( name, coors, ngroups, conns, mat_ids, descs, igs = None ):
        
        if igs is None:
            igs = range( len( conns ) )
        mesh = Mesh(name)
        mesh._set_data(coors = coors,
                       ngroups = ngroups,
                       conns = [conns[ig] for ig in igs],
                       mat_ids = [mat_ids[ig] for ig in igs],
                       descs = [descs[ig] for ig in igs])
        mesh._set_shape_info()
        return mesh
439838
def _build_tree(self, position, momentum, slice_var, direction, depth, stepsize):
        

        # Parameter names in algorithm (here -> representation in algorithm)
        # position -> theta, momentum -> r, slice_var -> u, direction -> v, depth ->j, stepsize -> epsilon
        # candidate_set_size -> n, accept_set_bool -> s
        if depth == 0:
            # Take single leapfrog step in the given direction (direction * stepsize)
            position_bar, momentum_bar, candidate_set_size, accept_set_bool =\
                self._initalize_tree(position, momentum, slice_var, direction * stepsize)

            return (position_bar, momentum_bar, position_bar, momentum_bar, position_bar,
                    candidate_set_size, accept_set_bool)

        else:
            # Build left and right subtrees
            (position_backward, momentum_backward, position_forward, momentum_forward, position_bar,
             candidate_set_size, accept_set_bool) = self._build_tree(position, momentum,
                                                                     slice_var, direction, depth - 1, stepsize)
            if accept_set_bool == 1:
                if direction == -1:
                    # Build tree in backward direction
                    (position_backward, momentum_backward, _, _, position_bar2, candidate_set_size2,
                     accept_set_bool2) = self._build_tree(position_backward, momentum_backward,
                                                          slice_var, direction, depth - 1, stepsize)
                else:
                    # Build tree in forward direction
                    (_, _, position_forward, momentum_forward, position_bar2, candidate_set_size2,
                     accept_set_bool2) = self._build_tree(position_forward, momentum_forward,
                                                          slice_var, direction, depth - 1, stepsize)

                if np.random.rand() < candidate_set_size2 / (candidate_set_size2 + candidate_set_size):
                    position_bar = position_bar2

                accept_set_bool, candidate_set_size =\
                    self._update_acceptance_criteria(position_forward, position_backward, momentum_forward,
                                                     momentum_backward, accept_set_bool2, candidate_set_size,
                                                     candidate_set_size2)

            return (position_backward, momentum_backward, position_forward, momentum_forward,
                    position_bar, candidate_set_size, accept_set_bool)
781650
private void buildCoverTree() {
        ArrayList<DistanceSet> pointSet = new ArrayList<>();
        ArrayList<DistanceSet> consumedSet = new ArrayList<>();

        E point = data[0];
        int idx = 0;
        double maxDist = -1;

        for (int i = 1; i < data.length; i++) {
            DistanceSet set = new DistanceSet(i);
            double dist = distance.d(point, data[i]);
            set.dist.add(dist);
            pointSet.add(set);
            if (dist > maxDist) {
                maxDist = dist;
            }
        }

        root = batchInsert(idx, getScale(maxDist), getScale(maxDist), pointSet, consumedSet);
    }
1154080
public KdTree construct(List<P> points , boolean trackIndexes )
	{
		GrowQueue_I32 indexes = null;
		if( trackIndexes ) {
			indexes = new GrowQueue_I32();
			indexes.resize(points.size());
			for (int i = 0; i < indexes.size; i++) {
				indexes.data[i] = i;
			}
		}

		KdTree tree = memory.requestTree(splitter.getPointLength());

		if( points.size() == 1 ) {
			tree.root = createLeaf(points,indexes);
		} else if( points.size() > 1 ) {
			tree.root = computeBranch(points, indexes );
		}

		return tree;
	}
701422
def _build_tree(self, side):
        
        if not self.nn_ready[side]:
            self.kdtree[side]   = scipy.spatial.cKDTree(self.data[side], compact_nodes=False, balanced_tree=False) # Those options are required with scipy >= 0.16
            self.nn_ready[side] = True
1312643
def split(cls, dataset, start, end, datatype, **kwargs):
        
        objs = []
        if datatype is None:
            for d in dataset.data[start: end]:
                objs.append(dataset.clone(d, datatype=cls.subtypes))
            return objs
        elif not dataset.data:
            return objs
        ds = cls._inner_dataset_template(dataset)
        for d in dataset.data:
            ds.data = d
            if datatype == 'array':
                obj = ds.array(**kwargs)
            elif datatype == 'dataframe':
                obj = ds.dframe(**kwargs)
            elif datatype == 'columns':
                if ds.interface.datatype == 'dictionary':
                    obj = dict(ds.data)
                else:
                    obj = ds.columns(**kwargs)
            else:
                raise ValueError("%s datatype not support" % datatype)
            objs.append(obj)
        return objs
553491
def build(cls, data, *args, **kwargs):
        
        assert isinstance(data, Data)
        if data.is_continuous_class:
            fitness_func = gain_variance
        else:
            fitness_func = get_gain
        
        t = cls(data=data, *args, **kwargs)
        t._data = data
        t.sample_count = len(data)
        t._tree = create_decision_tree(
            data=data,
            attributes=data.attribute_names,
            class_attr=data.class_attribute_name,
            fitness_func=fitness_func,
            wrapper=t,
        )
        return t
493257
def df_to_dat(net, df, define_cat_colors=False):
  '''
  
  '''
  from . import categories

  # check if df has unique values
  df['mat'] = make_unique_labels.main(net, df['mat'])

  net.dat['mat'] = df['mat'].values
  net.dat['nodes']['row'] = df['mat'].index.tolist()
  net.dat['nodes']['col'] = df['mat'].columns.tolist()

  for inst_rc in ['row', 'col']:

    if type(net.dat['nodes'][inst_rc][0]) is tuple:
      # get the number of categories from the length of the tuple
      # subtract 1 because the name is the first element of the tuple
      num_cat = len(net.dat['nodes'][inst_rc][0]) - 1

      net.dat['node_info'][inst_rc]['full_names'] = net.dat['nodes']\
          [inst_rc]

      for inst_rcat in range(num_cat):
        net.dat['node_info'][inst_rc]['cat-' + str(inst_rcat)] = \
          [i[inst_rcat + 1] for i in net.dat['nodes'][inst_rc]]

      net.dat['nodes'][inst_rc] = [i[0] for i in net.dat['nodes'][inst_rc]]

  if 'mat_up' in df:
    net.dat['mat_up'] = df['mat_up'].values
    net.dat['mat_dn'] = df['mat_dn'].values

  if 'mat_orig' in df:
    net.dat['mat_orig'] = df['mat_orig'].values

  categories.dict_cat(net, define_cat_colors=define_cat_colors)
635218
def _L(dfs_data):
    """L(T) = {v | the first w in Adj[v] corresponds to a frond vw}."""
    node_set = set()
    for v, adj in list(dfs_data['adj'].items()):
        w = adj[0]
        if is_frond(v, w, dfs_data):
            node_set.add(v)
    return list(node_set)
1154967
def load(self, dataset_keys, previous_datasets=None):
        """"""
        all_datasets = previous_datasets or DatasetDict()
        datasets = DatasetDict()

        # Include coordinates in the list of datasets to load
        dsids = [self.get_dataset_key(ds_key) for ds_key in dataset_keys]
        coordinates = self._get_coordinates_for_dataset_keys(dsids)
        all_dsids = list(set().union(*coordinates.values())) + dsids

        for dsid in all_dsids:
            if dsid in all_datasets:
                continue
            coords = [all_datasets.get(cid, None)
                      for cid in coordinates.get(dsid, [])]
            ds = self._load_dataset_with_area(dsid, coords)
            if ds is not None:
                all_datasets[dsid] = ds
                if dsid in dsids:
                    datasets[dsid] = ds
        self._load_ancillary_variables(all_datasets)

        return datasets
668170
def mdl(ll, k, data):
    

    """
    N - no. of genes
    n - no. of cells 
    k - no. of cell types
    R - sum(Dataset) i.e. total no. of reads

    function TotCost = TotBits(N,m,p,R,C)
        # C is the cost from the cost function
        TotCost = C + (N*m + m*p)*(log(R/(N*p)));
    """
    N, m = data.shape
    cost = ll + (N*m + m*k)*(np.log(data.sum()/(N*k)))
    return cost
778970
public void buildTree(INDArray x) {
        this.X = x;
        for(int i = 0; i < x.rows(); i++) {
            root.getIndices().add(i);
        }



        RPUtils.buildTree(this,root,rpHyperPlanes,
                x,maxSize,0,similarityFunction);
    }
1328866
public void partition(int k) {
        double[][] reps = new double[nodes.size()][];
        int i = 0;
        for (Node neuron : nodes)
            reps[i++] = neuron.w;

        double[][] proximity = new double[nodes.size()][];
        for (i = 0; i < nodes.size(); i++) {
            proximity[i] = new double[i+1];
            for (int j = 0; j < i; j++)
                proximity[i][j] = Math.distance(reps[i], reps[j]);
        }
        
        Linkage linkage = new UPGMALinkage(proximity);
        HierarchicalClustering hc = new HierarchicalClustering(linkage);
        y = hc.partition(k);
    }
289810
def _build_tree(self):
        

        groups = self._groups or self.get_children_paths(self.root_path)
        for group in groups:
            node = Node(name=group, parent=self.root)
            self.root.children.append(node)
            self._init_sub_groups(node)
400462
def build(cls: Type[T], data: Generic) -> T:
        """"""
        fields = fields_dict(cls)
        kwargs: Dict[str, Any] = {}
        for key, value in data.items():
            if key in fields:
                if isinstance(value, Mapping):
                    t = fields[key].type
                    if issubclass(t, Auto):
                        value = t.build(value)
                    else:
                        value = Auto.generate(value, name=key.title())
                kwargs[key] = value
            else:
                log.debug(f"got unknown attribute {key} for {cls.__name__}")
        return cls(**kwargs)
1188681
def from_dict(self, data, recursive=1):
        
        # Find other linked resources
        data = self._encode_resource(data, recursive=recursive)
        self.data = data