Do relaxation for the cbpdn stage. The only parameter is the slice
    index `k` and there are no return values; all inputs and outputs are
    from and to global variables.
768739
def cbpdnmd_relax(k):
    

    mp_Z_X[k] = mp_xrlx * mp_Z_X[k] + (1 - mp_xrlx) * mp_Z_Y1[k]
    mp_DX[k] = mp_xrlx * mp_DX[k] + (1 - mp_xrlx) * (mp_Z_Y0[k] + mp_S[k])
1365445
private void setGraphParameters() {

        // Diameter is the maximum of all shortest path lengths
        // Average shortest path length is (as the name says) the average of the shortest path length between all node pairs

        double maxPathLength = 0.0;
        double shortestPathLengthSum = 0.0;
        double degreeSum = 0.0;
        double clusterCoefficientSum = 0.0;

        // iterate over all node pairs
        Set<Integer> nodes = undirectedGraph.vertexSet();

        // a hashset of the nodes which have been the start node of the computation process
        // for such nodes all path lengths have beeen already computed
        Set<Integer> wasSource = new HashSet<Integer>();

        int progress = 0;
        for (int node : nodes) {

            progress++;
            ApiUtilities.printProgressInfo(progress, nodes.size(), 100, ApiUtilities.ProgressInfoMode.TEXT, "Getting graph parameters");

            int nodeDegree = undirectedGraph.degreeOf(node);
            degreeSum += nodeDegree;
            updateDegreeDistribution(nodeDegree);


            // cluster coefficient of a node is C_v is the fraction of the connections that exist between the neighbor nodes (k_v) of a this node and all allowable connections between the neighbors (k_v(k_v -1)/2)
            // for degrees 0 or 1 there is no cluster coefficient, as there can be no connections between neighbors
            if (undirectedGraph.degreeOf(node) > 1) {
                double numberOfNeighborConnections =  getNumberOfNeighborConnections(node);
                clusterCoefficientSum += ( numberOfNeighborConnections / (nodeDegree * (nodeDegree - 1)));
            }

            // Returns the new shortestPathLengthSum and the new maxPathLength.
            // They are returned as an double array for performance reasons.
            // I do not want to create an object, as this function is called *very* often
            double[] returnValues = computeShortestPathLenghts(node, shortestPathLengthSum, maxPathLength, wasSource);
            shortestPathLengthSum = returnValues[0];
            maxPathLength         = returnValues[1];

            // save the info that the node was already used as the source of path computation
            wasSource.add(node);
        }

        if (nodes.size() > 1) {
            this.averageShortestPathLength = shortestPathLengthSum / ( nodes.size() * (nodes.size()-1) / 2 ); // sum of path lengths / (number of node pairs)
        }
        else {
            this.averageShortestPathLength = 0; // there is only one node
        }
        this.diameter = maxPathLength;
        this.averageDegree = degreeSum / nodes.size();
        this.clusterCoefficient = clusterCoefficientSum / nodes.size();
    }
1175765
private void ensureCapacityAndSetPair(int index, KeyValuePair kvp) {
        if (index < pairs.length) {
            pairs[index] = kvp;
        } else {
            pairs = java.util.Arrays.copyOf(pairs, Math.max(index + (index >> 1), DEFAULT_SIZE));
            pairs[index] = kvp;
        }
        setLastIndex(index);
    }
103615
def par_relax_AX(i):
    

    global mp_X
    global mp_Xnr
    global mp_DX
    global mp_DXnr
    mp_Xnr[mp_grp[i]:mp_grp[i+1]] = mp_X[mp_grp[i]:mp_grp[i+1]]
    mp_DXnr[i] = mp_DX[i]
    if mp_rlx != 1.0:
        grpind = slice(mp_grp[i], mp_grp[i+1])
        mp_X[grpind] = mp_rlx * mp_X[grpind] + (1-mp_rlx)*mp_Y1[grpind]
        mp_DX[i] = mp_rlx*mp_DX[i] + (1-mp_rlx)*mp_Y0[i]
510623
private void materializeKNNAndRKNNs(ArrayDBIDs ids, FiniteProgress progress) {
    // add an empty list to each rknn
    for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) {
      if(materialized_RkNN.get(iter) == null) {
        materialized_RkNN.put(iter, new TreeSet<DoubleDBIDPair>());
      }
    }

    // knn query
    List<? extends KNNList> kNNList = knnQuery.getKNNForBulkDBIDs(ids, k);
    for(DBIDArrayIter id = ids.iter(); id.valid(); id.advance()) {
      KNNList kNNs = kNNList.get(id.getOffset());
      storage.put(id, kNNs);
      for(DoubleDBIDListIter iter = kNNs.iter(); iter.valid(); iter.advance()) {
        materialized_RkNN.get(iter).add(DBIDUtil.newPair(iter.doubleValue(), id));
      }
      LOG.incrementProcessed(progress);
    }

    LOG.ensureCompleted(progress);
  }
334404
def report_and_save_keywords(self,relaxation_kwds,precomputed_kwds):
        """"""
        report_name = os.path.join(self.backup_dir,'relaxation_keywords.txt')
        pretty_relax_kwds = pprint.pformat(relaxation_kwds,indent=4)
        with open(report_name,'w') as wf:
            wf.write(pretty_relax_kwds)
        wf.close()

        origin_name = os.path.join(self.backup_dir,'relaxation_keywords.pyc')
        with open(origin_name,'wb') as ro:
            pickle.dump(relaxation_kwds,ro,protocol=pickle.HIGHEST_PROTOCOL)
        ro.close()

        if relaxation_kwds['presave']:
            precomp_kwds_name = os.path.join(self.backup_dir,
                                             'precomputed_keywords.pyc')
            with open(precomp_kwds_name, 'wb') as po:
                pickle.dump(precomputed_kwds, po,
                            protocol=pickle.HIGHEST_PROTOCOL)
            po.close()
39496
def _exec_loop(self, a, bd_all, mask):
        """"""

        npt = bd_all.shape[0]
        n = self.X_ADJUSTED.shape[0]
        kvalues = np.zeros(npt)
        sigmasq = np.zeros(npt)

        a_inv = scipy.linalg.inv(a)

        for j in np.nonzero(~mask)[0]:   # Note that this is the same thing as range(npt) if mask is not defined,
            bd = bd_all[j]               # otherwise it takes the non-masked elements.
            if np.any(np.absolute(bd) <= self.eps):
                zero_value = True
                zero_index = np.where(np.absolute(bd) <= self.eps)
            else:
                zero_value = False
                zero_index = None

            b = np.zeros((n+1, 1))
            b[:n, 0] = - self.variogram_function(self.variogram_model_parameters, bd)
            if zero_value:
                b[zero_index[0], 0] = 0.0
            b[n, 0] = 1.0

            x = np.dot(a_inv, b)
            kvalues[j] = np.sum(x[:n, 0] * self.VALUES)
            sigmasq[j] = np.sum(x[:, 0] * -b[:, 0])

        return kvalues, sigmasq
1196532
def init_pp(X, n_clusters, random_state):
    
    x_squared_norms = row_norms(X, squared=True).compute()
    logger.info("Initializing with k-means++")
    with _timer("initialization of %2d centers" % n_clusters, _logger=logger):
        centers = sk_k_means._k_init(
            X, n_clusters, random_state=random_state, x_squared_norms=x_squared_norms
        )

    return centers
585739
def Hk(self, k, m_pred, P_pred):  # returns state iteration matrix
        

        return self.H[:, :, int(self.index[self.H_time_var_index, k])]
956400
def ConvBPDNOptionsDefaults(method='admm'):
    

    dflt = copy.deepcopy(cbpdn_class_label_lookup(method).Options.defaults)
    if method == 'admm':
        dflt.update({'MaxMainIter': 1, 'AutoRho':
                     {'Period': 10, 'AutoScaling': False,
                      'RsdlRatio': 10.0, 'Scaling': 2.0,
                      'RsdlTarget': 1.0}})
    else:
        dflt.update({'MaxMainIter': 1, 'BackTrack':
                     {'gamma_u': 1.2, 'MaxIter': 50}})
    return dflt
684725
def step_group(k):
    

    cbpdn_xstep(k)
    if mp_xrlx != 1.0:
        cbpdn_relax(k)
    cbpdn_ystep(k)
    cbpdn_ustep(k)
    ccmod_setcoef(k)
    ccmod_xstep(k)
    if mp_drlx != 1.0:
        ccmod_relax(k)
14725
private Pair<KNNQuery<O>, KNNQuery<O>> getKNNQueries(Database database, Relation<O> relation, StepProgress stepprog) {
    DistanceQuery<O> distQ = database.getDistanceQuery(relation, reachabilityDistanceFunction, DatabaseQuery.HINT_HEAVY_USE);
    // "HEAVY" flag for knnReach since it is used more than once
    KNNQuery<O> knnReach = database.getKNNQuery(distQ, kreach, DatabaseQuery.HINT_HEAVY_USE, DatabaseQuery.HINT_OPTIMIZED_ONLY, DatabaseQuery.HINT_NO_CACHE);
    // No optimized kNN query - use a preprocessor!
    if(!(knnReach instanceof PreprocessorKNNQuery)) {
      if(stepprog != null) {
        if(referenceDistanceFunction.equals(reachabilityDistanceFunction)) {
          stepprog.beginStep(1, "Materializing neighborhoods w.r.t. reference neighborhood distance function.", LOG);
        }
        else {
          stepprog.beginStep(1, "Not materializing neighborhoods w.r.t. reference neighborhood distance function, but materializing neighborhoods w.r.t. reachability distance function.", LOG);
        }
      }
      int kpreproc = (referenceDistanceFunction.equals(reachabilityDistanceFunction)) ? Math.max(kreach, krefer) : kreach;
      knnReach = DatabaseUtil.precomputedKNNQuery(database, relation, reachabilityDistanceFunction, kpreproc);
    }

    // knnReach is only used once
    KNNQuery<O> knnRefer;
    if(referenceDistanceFunction == reachabilityDistanceFunction || referenceDistanceFunction.equals(reachabilityDistanceFunction)) {
      knnRefer = knnReach;
    }
    else {
      // do not materialize the first neighborhood, since it is used only once
      knnRefer = QueryUtil.getKNNQuery(relation, referenceDistanceFunction, krefer);
    }

    return new Pair<>(knnRefer, knnReach);
  }
790219
def set_up_phase(self, training_info, model, source):
        
        # To parameter groups handles properly filtering parameters that don't require gradient
        self._optimizer_instance = self.optimizer_factory.instantiate(model)
        self._source = source

        self.special_callback = CycleCallback(
            self._optimizer_instance,
            max_lr=self.max_lr, min_lr=self.min_lr, cycles=self.cycles,
            cycle_len=self.cycle_len, cycle_mult=self.cycle_mult, interpolate=self.interpolate,
            init_iter=self.init_iter, init_lr=self.init_lr
        )

        return self._optimizer_instance
39046
def cbpdn_xstep(k):
    

    YU = mp_Z_Y[k] - mp_Z_U[k]
    b = mp_DSf[k] + mp_xrho * sl.rfftn(YU, None, mp_cri.axisN)
    if mp_cri.Cd == 1:
        Xf = sl.solvedbi_sm(mp_Df, mp_xrho, b, axis=mp_cri.axisM)
    else:
        Xf = sl.solvemdbi_ism(mp_Df, mp_xrho, b, mp_cri.axisM, mp_cri.axisC)
    mp_Z_X[k] = sl.irfftn(Xf, mp_cri.Nv, mp_cri.axisN)
782238
private void merge(Relation<V> relation, List<ORCLUSCluster> clusters, int k_new, int d_new, IndefiniteProgress cprogress) {
    ArrayList<ProjectedEnergy> projectedEnergies = new ArrayList<>((clusters.size() * (clusters.size() - 1)) >>> 1);
    for(int i = 0; i < clusters.size(); i++) {
      for(int j = i + 1; j < clusters.size(); j++) {
        // projected energy of c_ij in subspace e_ij
        ORCLUSCluster c_i = clusters.get(i);
        ORCLUSCluster c_j = clusters.get(j);

        projectedEnergies.add(projectedEnergy(relation, c_i, c_j, i, j, d_new));
      }
    }

    while(clusters.size() > k_new) {
      if(cprogress != null) {
        cprogress.setProcessed(clusters.size(), LOG);
      }
      // find the smallest value of r_ij
      ProjectedEnergy minPE = Collections.min(projectedEnergies);

      // renumber the clusters by replacing cluster c_i with cluster c_ij
      // and discarding cluster c_j
      for(int c = 0; c < clusters.size(); c++) {
        if(c == minPE.i) {
          clusters.remove(c);
          clusters.add(c, minPE.cluster);
        }
        if(c == minPE.j) {
          clusters.remove(c);
        }
      }

      // remove obsolete projected energies and renumber the others ...
      int i = minPE.i, j = minPE.j;
      for(Iterator<ProjectedEnergy> it = projectedEnergies.iterator(); it.hasNext();) {
        ProjectedEnergy pe = it.next();
        if(pe.i == i || pe.i == j || pe.j == i || pe.j == j) {
          it.remove();
        }
        else {
          if(pe.i > j) {
            pe.i -= 1;
          }
          if(pe.j > j) {
            pe.j -= 1;
          }
        }
      }

      // ... and recompute them
      ORCLUSCluster c_ij = minPE.cluster;
      for(int c = 0; c < clusters.size(); c++) {
        if(c < i) {
          projectedEnergies.add(projectedEnergy(relation, clusters.get(c), c_ij, c, i, d_new));
        }
        else if(c > i) {
          projectedEnergies.add(projectedEnergy(relation, clusters.get(c), c_ij, i, c, d_new));
        }
      }
    }
  }
601293
def prune_loop_for_kic(self, loops_segments, search_radius, expected_min_loop_length = None, expected_max_loop_length = None, generate_pymol_session = False):
        ''''''
        return self.prune_structure_according_to_loop_definitions(loops_segments, search_radius, expected_min_loop_length = expected_min_loop_length, expected_max_loop_length = expected_max_loop_length, generate_pymol_session = generate_pymol_session, check_sequence = True, keep_Ca_buttress_atoms = True)
810316
def step(self):
        """"""

        # If the nproc parameter of __init__ is zero, just iterate
        # over the K consensus instances instead of using
        # multiprocessing to do the computations in parallel. This is
        # useful for debugging and timing comparisons.
        if self.nproc == 0:
            for k in range(self.xstep.cri.K):
                step_group(k)
        else:
            self.pool.map(step_group, range(self.xstep.cri.K))

        ccmod_ystep()
        ccmod_ustep()
        cbpdn_setdict()