Takes cluster structure and nearest neighbour information of a datapoint,
    Returns concatenated soap vectors for each nearest
    neighbour (up to 3). Top, bridge, hollow fill the initial
    zero soap vector from left to right.
484691
def get_nnsoap(obj, first_shell, alphas, betas, rcut=6, nmax=10, lmax=9, all_atomtypes=[]):
    

    soap_vector = []
    nnn = len(first_shell)
    for tbh in range(0,3):
        try:
            atom_idx = first_shell[tbh]
        except:
            soap_vector.append(soap_zero)
        else:
            Hpos = []
            print(atom_idx)
            pos = obj.get_positions()[atom_idx]
            Hpos.append(pos)
            x = soapPy.get_soap_locals(obj, Hpos, myAlphas, myBetas, rCut=rcut, NradBas=nmax, Lmax=lmax,crossOver=False, all_atomtypes=all_atomtypes)
            soap_zero = np.zeros(x.shape)
            soap_vector.append(x)
    print(len(soap_vector), soap_vector[0].shape, soap_vector[1].shape, soap_vector[2].shape)
    print("exemplary soapvalues",soap_vector[0][0,1], soap_vector[1][0,1], soap_vector[2][0,1])
    soap_array = np.hstack(soap_vector)
    return soap_array
270230
@Override
	public ClusteringTreeNode nearestChild(double[] pointA) {
		assert (this.projections.size() > 0 &&
				this.projections.get(0).length == pointA.length);
		int minBucketProjection = -1;
		int minSize = Integer.MAX_VALUE;
		Iterator<double[]> iIterProjections = this.projections.iterator();
		Iterator<CuckooHashing<List<ClusteringTreeNode>>> iIterBuckets = this.buckets
				.iterator();
		int size = this.projections.size();
		for (int i = 0; i < size; i++) {
			long bucketNumber = calcBucketNumber(project(pointA,
					iIterProjections.next()));
			List<ClusteringTreeNode> currentBucket = iIterBuckets.next().get(
					bucketNumber);
			int bucketSize;
			if (currentBucket != null
					&& (bucketSize = currentBucket.size()) <= minSize) {
				minBucketProjection = i;
				minSize = bucketSize;
			}
		}
		if (minBucketProjection == -1) {
			return null;
		}

		long bucketNumber = calcBucketNumber(project(pointA,
				minBucketProjection));
		double minDistance = Double.POSITIVE_INFINITY;
		ClusteringTreeNode min = null;
		// for (int i = -1; i <= 1; i++) {
		List<ClusteringTreeNode> currentBucket = this.buckets.get(
				minBucketProjection).get(bucketNumber);// + i);
		if (currentBucket != null) {
			for (ClusteringTreeNode node : currentBucket) {
				double d = Metric.distance(pointA, node.getCenter());
				if (d < minDistance) {
					minDistance = d;
					min = node;
				}
			}
		}
		// }
		return min;
	}
1262481
def cluster(self, dist_type='cosine', run_clustering=True,
                 dendro=True, views=['N_row_sum', 'N_row_var'],
                 linkage_type='average', sim_mat=False, filter_sim=0.1,
                 calc_cat_pval=False, run_enrichr=None, enrichrgram=None):
    '''
    
    '''
    initialize_net.viz(self)

    make_clust_fun.make_clust(self, dist_type=dist_type, run_clustering=run_clustering,
                                   dendro=dendro,
                                   requested_views=views,
                                   linkage_type=linkage_type,
                                   sim_mat=sim_mat,
                                   filter_sim=filter_sim,
                                   calc_cat_pval=calc_cat_pval,
                                   run_enrichr=run_enrichr,
                                   enrichrgram=enrichrgram)
929436
def get_sitecenteredsoap(obj, first_shell, alphas, betas, rcut=6, nmax=10, lmax=9, all_atomtypes=[]):
    

    soap_vector = []
    nnn = len(first_shell)
    center_of_atoms = 1.0 / nnn * np.mean(obj.get_positions()[first_shell], axis = 0)
    #print("center of atoms", center_of_atoms)
    Hpos = [center_of_atoms]
    soap_vector = soapPy.get_soap_locals(obj, Hpos, myAlphas, myBetas, rCut=rcut, NradBas=nmax, Lmax=lmax,crossOver=False, all_atomtypes=all_atomtypes)
    #print(len(soap_vector), soap_vector.shape)
    #print("exemplary soapvalues",soap_vector[0,0], soap_vector[0,1], soap_vector[0,2])
    return soap_vector
935037
def get_closest_clusters(cluster_id, cluster_ids, sim_func, max_n=None):
    """"""
    l = [(_as_scalar(candidate), _as_scalar(sim_func(cluster_id, candidate)))
         for candidate in _as_scalars(cluster_ids)]
    l = sorted(l, key=itemgetter(1), reverse=True)
    max_n = None or len(l)
    return l[:max_n]
781387
def get_projection_on_elements(self, structure):
        
        dico = {}
        for spin in self.data.keys():
            dico[spin] = [[defaultdict(float)
                           for i in range(self.nkpoints)]
                          for j in range(self.nbands)]

        for iat in range(self.nions):
            name = structure.species[iat].symbol
            for spin, d in self.data.items():
                for k, b in itertools.product(range(self.nkpoints),
                                              range(self.nbands)):
                    dico[spin][b][k][name] = np.sum(d[k, b, iat, :])

        return dico
1036110
def array(self):
        
        return np.geomspace(self.start, self.stop, self.num, self.endpoint)
1271330
private Vec[][] makeTemplates(Frame dataset, double[] ratios) {
    Vec anyVec = dataset.anyVec();
    final long[][] espcPerSplit = computeEspcPerSplit(anyVec.espc(), anyVec.length(), ratios);
    final int num = dataset.numCols(); // number of columns in input frame
    final int nsplits = espcPerSplit.length; // number of splits
    final String[][] domains = dataset.domains(); // domains
    final byte[] types = new byte[num];
    int j=0;
    for (Vec v : dataset.vecs()) types[j++] = v.get_type();

    Vec[][] t = new Vec[nsplits][/*num*/]; // resulting vectors for all
    for (int i=0; i<nsplits; i++) {
      // vectors for j-th split
      Key vkey = Vec.newKey();
      int rowLayout = Vec.ESPC.rowLayout(vkey,espcPerSplit[i]);
      t[i] = new Vec(vkey,rowLayout).makeCons(num, 0, domains, types);
    }
    return t;
  }
1370326
def get_structure_with_nodes(self):
        
        new_s = Structure.from_sites(self.structure)
        for v in self.vnodes:
            new_s.append("X", v.frac_coords)
        return new_s
611351
def cluster_assignments(self):
        
        array = javabridge.call(self.jobject, "getClusterAssignments", "()[D")
        if array is None:
            return None
        else:
            return javabridge.get_env().get_double_array_elements(array)
1234250
def make_clust(net, dist_type='cosine', run_clustering=True, dendro=True,
                          requested_views=['pct_row_sum', 'N_row_sum'],
                          linkage_type='average', sim_mat=False, filter_sim=0.1,
                          calc_cat_pval=False, sim_mat_views=['N_row_sum'],
                          run_enrichr=None, enrichrgram=None):
  '''
  
  '''
  from copy import deepcopy
  import scipy
  from . import calc_clust, run_filter, make_views, make_sim_mat, cat_pval
  from . import enrichr_functions as enr_fun

  df = net.dat_to_df()

  threshold = 0.0001
  df = run_filter.df_filter_row_sum(df, threshold)
  df = run_filter.df_filter_col_sum(df, threshold)

  # default setting
  define_cat_colors = False

  if run_enrichr is not None:
    df = enr_fun.add_enrichr_cats(df, 'row', run_enrichr)

    define_cat_colors = True

  # calculate initial view with no row filtering
  net.df_to_dat(df, define_cat_colors=True)


  inst_dm = calc_clust.cluster_row_and_col(net, dist_type=dist_type,
                                linkage_type=linkage_type,
                                run_clustering=run_clustering,
                                dendro=dendro, ignore_cat=False,
                                calc_cat_pval=calc_cat_pval)

  all_views = []
  send_df = deepcopy(df)

  if 'N_row_sum' in requested_views:
    all_views = make_views.N_rows(net, send_df, all_views,
                                  dist_type=dist_type, rank_type='sum')

  if 'N_row_var' in requested_views:
    all_views = make_views.N_rows(net, send_df, all_views,
                                  dist_type=dist_type, rank_type='var')

  if 'pct_row_sum' in requested_views:
    all_views = make_views.pct_rows(net, send_df, all_views,
                                    dist_type=dist_type, rank_type='sum')

  if 'pct_row_var' in requested_views:
    all_views = make_views.pct_rows(net, send_df, all_views,
                                    dist_type=dist_type, rank_type='var')

  which_sim = []

  if sim_mat == True:
    which_sim = ['row', 'col']
  elif sim_mat == 'row':
    which_sim = ['row']
  elif sim_mat == 'col':
    which_sim = ['col']

  if sim_mat is not False:
    sim_net = make_sim_mat.main(net, inst_dm, which_sim, filter_sim, sim_mat_views)

    net.sim = {}

    for inst_rc in which_sim:
      net.sim[inst_rc] = sim_net[inst_rc].viz

      if inst_rc == 'row':
        other_rc = 'col'
      elif inst_rc == 'col':
        other_rc = 'row'

      # keep track of cat_colors
      net.sim[inst_rc]['cat_colors'][inst_rc] = net.viz['cat_colors'][inst_rc]
      net.sim[inst_rc]['cat_colors'][other_rc] = net.viz['cat_colors'][inst_rc]

  else:
    net.sim = {}

  net.viz['views'] = all_views

  if enrichrgram != None:
    # toggle enrichrgram functionality from back-end
    net.viz['enrichrgram'] = enrichrgram

  if 'enrichrgram_lib' in net.dat:
    net.viz['enrichrgram'] = True
    net.viz['enrichrgram_lib'] = net.dat['enrichrgram_lib']

  if 'row_cat_bars' in net.dat:
    net.viz['row_cat_bars'] = net.dat['row_cat_bars']
768792
private ArrayList<SameLengthMotifs> SeparateMotifsByClustering(ArrayList<String[]> clusterTSIdx,
      SameLengthMotifs sameLenMotifs) {
    ArrayList<SameLengthMotifs> newResult = new ArrayList<SameLengthMotifs>();
    if (clusterTSIdx.size() > 1) {
      ArrayList<SAXMotif> subsequences = sameLenMotifs.getSameLenMotifs();
      for (String[] idxesInCluster : clusterTSIdx) {
        SameLengthMotifs newIthSLM = new SameLengthMotifs();
        ArrayList<SAXMotif> sameLenSS = new ArrayList<SAXMotif>();
        int minL = sameLenMotifs.getMinMotifLen();
        int maxL = sameLenMotifs.getMaxMotifLen();

        for (String i : idxesInCluster) {
          SAXMotif ssI = subsequences.get(Integer.parseInt(i));
          int len = ssI.getPos().getEnd() - ssI.getPos().getStart();
          if (len < minL) {
            minL = len;
          }
          else if (len > maxL) {
            maxL = len;
          }
          sameLenSS.add(ssI);
        }

        newIthSLM.setSameLenMotifs(sameLenSS);
        newIthSLM.setMaxMotifLen(maxL);
        newIthSLM.setMinMotifLen(minL);
        newResult.add(newIthSLM);
      }
    }
    else {
      newResult.add(sameLenMotifs);
    }

    return newResult;
  }
714096
private void computePrincipleVectors(int numPrincipleVectors) {

        // Group all of the sspace's vectors into a Matrix so that we can
        // cluster them
        final int numTerms = sspace.getWords().size();
        final List<DoubleVector> termVectors = 
            new ArrayList<DoubleVector>(numTerms);
        String[] termAssignments = new String[numTerms];
        int k = 0;
        for (String term : sspace.getWords()) {
            termVectors.add(Vectors.asDouble(sspace.getVector(term)));
            termAssignments[k++] = term;
        }

        Random random = new Random();

        final DoubleVector[] principles = new DoubleVector[numPrincipleVectors];
        for (int i = 0; i < principles.length; ++i)
            principles[i] = new DenseVector(sspace.getVectorLength());

        // Randomly assign the data set to different intitial clusters 
        final MultiMap<Integer,Integer> clusterAssignment = 
            new HashMultiMap<Integer,Integer>();
        for (int i = 0; i < numTerms; ++i) 
            clusterAssignment.put(random.nextInt(numPrincipleVectors), i);
        
        int numIters = 1;
        for (int iter = 0; iter < numIters; ++iter) {
            verbose(LOGGER, "Computing principle vectors (round %d/%d)", iter+1, numIters);
            // Compute the centroids
            for (Map.Entry<Integer,Set<Integer>> e
                     : clusterAssignment.asMap().entrySet()) {
                int cluster = e.getKey();
                DoubleVector principle = new DenseVector(sspace.getVectorLength());
                principles[cluster] = principle;
                for (Integer row : e.getValue())
                    VectorMath.add(principle, termVectors.get(row));
            }

            // Reassign each element to the centroid to which it is closest
            clusterAssignment.clear();
            final int numThreads = workQueue.availableThreads();
            Object key = workQueue.registerTaskGroup(numThreads);

            for (int threadId_ = 0; threadId_ < numThreads; ++threadId_) {
                final int threadId = threadId_;
                workQueue.add(key, new Runnable() {
                        public void run() {
                            // Thread local cache of all the cluster assignments
                            MultiMap<Integer,Integer> clusterAssignment_ = 
                                new HashMultiMap<Integer,Integer>();
                            // For each of the vectors that this thread is
                            // responsible for, find the principle vector to
                            // which it is closest
                            for (int i = threadId; i < numTerms; i += numThreads) {
                                DoubleVector v = termVectors.get(i);
                                double highestSim = -Double.MAX_VALUE;
                                int pVec = -1;
                                for (int j = 0; j < principles.length; ++j) {
                                    DoubleVector principle = principles[j];
                                    double sim = Similarity.cosineSimilarity(
                                        v, principle);
                                    assert sim >= -1 && sim <= 1 : "similarity "
                                        + " to principle vector " + j + " is "
                                        + "outside the expected range: " + sim;
                                    if (sim > highestSim) {
                                        highestSim = sim;
                                        pVec = j;
                                    }
                                }
                                assert pVec != -1 : "Could not find match to "
                                    + "any of the " + principles.length + 
                                    " principle vectors";
                                clusterAssignment_.put(pVec, i);
                            }
                            // Once all the vectors for this thread have been
                            // mapped, update the thread-shared mapping.  Do
                            // this here, rather than for each comparison to
                            // minimize the locking
                            synchronized (clusterAssignment) {
                                clusterAssignment.putAll(clusterAssignment_);
                            }
                        }
                    });
            }
            workQueue.await(key);
        }

        double mean = numTerms / (double)numPrincipleVectors;
        double variance = 0d;
        for (Map.Entry<Integer,Set<Integer>> e
                 : clusterAssignment.asMap().entrySet()) {
            Set<Integer> rows = e.getValue();
            Set<String> terms = new HashSet<String>();
            for (Integer i : rows)
                terms.add(termAssignments[i]);
             verbose(LOGGER, "Principle vectod %d is closest to %d terms",
                     e.getKey(), terms.size());
            double diff = mean - terms.size();
            variance += diff * diff;
            principleVectorToNearestTerms.putMany(
                principles[e.getKey()], terms);
        }

        verbose(LOGGER, "Average number terms per principle vector: %f, "+
                "(%f stddev)", mean, Math.sqrt(variance / numPrincipleVectors));
    }
163673
private void computeMatrixTopoGraphClusters_(int geometry_a, int geometry_b) {
		boolean bRelationKnown = false;

		int id_a = m_topo_graph.getGeometryID(geometry_a);
		int id_b = m_topo_graph.getGeometryID(geometry_b);

		for (int cluster = m_topo_graph.getFirstCluster(); cluster != -1; cluster = m_topo_graph
				.getNextCluster(cluster)) {
			// Invoke relational predicates
			switch (m_predicates_cluster) {
			case Predicates.AreaPointPredicates:
				bRelationKnown = areaPointPredicates_(cluster, id_a, id_b);
				break;
			case Predicates.LinePointPredicates:
				bRelationKnown = linePointPredicates_(cluster, id_a, id_b);
				break;
			case Predicates.PointPointPredicates:
				bRelationKnown = pointPointPredicates_(cluster, id_a, id_b);
				break;
			default:
				throw GeometryException.GeometryInternalError();
			}

			if (bRelationKnown)
				break;
		}

		if (!bRelationKnown)
			setRemainingPredicatesToFalse_();
	}
1139393
def nn_dims(self, x, y, dims_x, dims_y, k=1, radius=np.inf, eps=0.0, p=2):
        
        if self.size > 0:
            dists, idxes = Dataset.nn_dims(self, x, y, dims_x, dims_y, k, radius, eps, p)
        else:
            return self.buffer.nn_dims(x, y, dims_x, dims_y, k, radius, eps, p)
        if self.buffer.size > 0:
            buffer_dists, buffer_idxes = self.buffer.nn_dims(x, y, dims_x, dims_y, k, radius, eps, p)
            buffer_idxes = [i + self.size for i in buffer_idxes]
            ziped = zip(dists, idxes)
            buffer_ziped = zip(buffer_dists, buffer_idxes)
            sorted_dists_idxes = sorted(ziped + buffer_ziped, key=lambda di:di[0])
            knns = sorted_dists_idxes[:k]
            return [knn[0] for knn in knns], [knn[1] for knn in knns] 
        else:
            return dists, idxes
184453
private void clusterIt() {

		dendrogram = new LinkedPair[numItems-1];


		logger.debug("Initial matrix: \n"+matrixToString());


		for (int m=0;m<numItems-1;m++) {

			updateIndicesToCheck(m);
			LinkedPair pair = getClosestPair();
			merge(pair);
			dendrogram[m] = pair;

			//if (debug) {
			//	System.out.println("Matrix after iteration "+m+" (merged "+pair.getFirst()+","+pair.getSecond()+")");
			//	printMatrix();
			//}
		}

	}
1232258
def nodes_geometry(self):
        

        nodes = np.array([
            n for n in self.transforms.nodes()
            if 'geometry' in self.transforms.node[n]
        ])

        return nodes