Runs the QSE algorithm to compute the eigenvalues of the Hamiltonian.

        :return: Dictionary of results
506843
def _run(self) -> dict:
        
        if not self._quantum_instance.is_statevector:
            raise AquaError("Can only calculate state for QSE with statevector backends")
        ret = self._quantum_instance.execute(self.opt_circuit)
        self.ret = ret
        self._eval_count = 0
        self._solve()
        self._ret['eval_count'] = self._eval_count
        self._ret['eval_time'] = self._eval_time
        return self._ret
566481
def compute_qu(self):
        
        Kuf = features.Kuf(self.feature, self.kern, self.X)
        Kuu = features.Kuu(self.feature, self.kern, jitter=settings.jitter)

        Sig = Kuu + (self.likelihood.variance ** -1) * tf.matmul(Kuf, Kuf, transpose_b=True)
        Sig_sqrt = tf.cholesky(Sig)

        Sig_sqrt_Kuu = tf.matrix_triangular_solve(Sig_sqrt, Kuu)

        A = tf.matmul(Sig_sqrt_Kuu, Sig_sqrt_Kuu, transpose_a=True)
        mu = tf.matmul(Sig_sqrt_Kuu,
                       tf.matrix_triangular_solve(Sig_sqrt, tf.matmul(Kuf, self.Y - self.mean_function(self.X))),
                       transpose_a=True) * self.likelihood.variance ** -1.0

        return mu, A
38793
def values(self):
        
        matrix = self.data.values()[0]  # CANONICAL REPRESENTATIVE
        if matrix.num == 0:
            return
        e_names = self.edges.name
        s_names = self.select.name
        parts = [e.domain.partitions.value if e.domain.primitive else e.domain.partitions for e in self.edges]
        for c in matrix._all_combos():
            try:
                output = {n: parts[i][c[i]] for i, n in enumerate(e_names)}
            except Exception as e:
                Log.error("problem", cause=e)
            for s in s_names:
                output[s] = self.data[s][c]
            yield wrap(output)
976081
def _normalize_eigensystem(u, lv, rv):
    
    # first normalize the stationary distribution separately
    lv[:, 0] = lv[:, 0] / np.sum(lv[:, 0])

    for i in range(1, lv.shape[1]):
        # the remaining left eigenvectors to satisfy
        # <\phi_i, \phi_i>_{\mu^{-1}} = 1
        lv[:, i] = lv[:, i] / np.sqrt(np.dot(lv[:, i], lv[:, i] / lv[:, 0]))

    for i in range(rv.shape[1]):
        # the right eigenvectors to satisfy <\phi_i, \psi_j> = \delta_{ij}
        rv[:, i] = rv[:, i] / np.dot(lv[:, i], rv[:, i])

    return u, lv, rv
1134167
def get_grid_qubits(arc: SquareGrid, nodes: Iterator[int]) -> List[cirq.GridQubit]:
    

    return [cirq.GridQubit(*arc.qind_to_squind(i)) for i in nodes]
971960
def _qvm_run(self, quil_program, classical_addresses, trials,
                 measurement_noise, gate_noise, random_seed) -> np.ndarray:
        
        payload = qvm_run_payload(quil_program, classical_addresses, trials,
                                  measurement_noise, gate_noise, random_seed)
        response = post_json(self.session, self.sync_endpoint + "/qvm", payload)

        ram = response.json()

        for k in ram.keys():
            ram[k] = np.array(ram[k])

        return ram
588645
def isa_from_graph(graph: nx.Graph, oneq_type='Xhalves', twoq_type='CZ') -> ISA:
    
    all_qubits = list(range(max(graph.nodes) + 1))
    qubits = [Qubit(i, type=oneq_type, dead=i not in graph.nodes) for i in all_qubits]
    edges = [Edge(sorted((a, b)), type=twoq_type, dead=False) for a, b in graph.edges]
    return ISA(qubits, edges)
1257079
def expect(qubits, meas):
    ""
    result = {}
    i = np.arange(len(qubits))
    meas = tuple(meas)

    def to_mask(n):
        return reduce(lambda acc, im: acc | (n & (1 << im[0])) << (im[1] - im[0]), enumerate(meas), 0)

    def to_key(k):
        return tuple(1 if k & (1 << i) else 0 for i in meas)

    mask = reduce(lambda acc, v: acc | (1 << v), meas, 0)

    cnt = defaultdict(float)
    for i, v in enumerate(qubits):
        p = v.real ** 2 + v.imag ** 2
        if p != 0.0:
            cnt[i & mask] += p
    return {to_key(k): v for k, v in cnt.items()}
61792
def uncertainty_eigenvalues(self):
        
        if self.information_ is None:
            self._build_information()

        sigma_eigenvalues = _ratematrix.sigma_eigenvalues(
            self.information_, theta=self.theta_, n=self.n_states_)

        if self.n_timescales is None:
            return sigma_eigenvalues
        return np.nan_to_num(sigma_eigenvalues[:self.n_timescales+1])
569150
def _get_bandgap_eigenval(eigenval_fname, outcar_fname):
        """"""
        with open(outcar_fname, "r") as f:
            parser = OutcarParser()
            nelec = next(iter(filter(lambda x: "number of electrons" in x, parser.parse(f.readlines()))))["number of electrons"]
        with open(eigenval_fname, "r") as f:
            eigenval_info = list(EigenvalParser().parse(f.readlines()))
        # spin_polarized = (2 == len(next(filter(lambda x: "kpoint" in x, eigenval_info))["occupancies"][0]))
        # if spin_polarized:
        all_energies = [zip(*x["energies"]) for x in eigenval_info if "energies" in x]
        spin_energies = zip(*all_energies)
        gaps = [VaspParser._get_bandgap_from_bands(x, nelec/2.0) for x in spin_energies]
        return min(gaps)
934394
def atoms_order(self):
        
        if not len(self):  # for empty containers
            return {}
        elif len(self) == 1:  # optimize single atom containers
            return dict.fromkeys(self, 2)

        params = {n: (int(node), tuple(sorted(int(edge) for edge in self._adj[n].values())))
                  for n, node in self.atoms()}
        newlevels = {}
        countprime = iter(primes)
        weights = {x: newlevels.get(y) or newlevels.setdefault(y, next(countprime))
                   for x, y in sorted(params.items(), key=itemgetter(1))}

        tries = len(self) * 4

        numb = len(set(weights.values()))
        stab = 0

        while tries:
            oldnumb = numb
            neweights = {}
            countprime = iter(primes)

            # weights[n] ** 2 NEED for differentiation of molecules like A-B or any other complete graphs.
            tmp = {n: reduce(mul, (weights[x] for x in m), weights[n] ** 2) for n, m in self._adj.items()}

            weights = {x: (neweights.get(y) or neweights.setdefault(y, next(countprime)))
                       for x, y in sorted(tmp.items(), key=itemgetter(1))}

            numb = len(set(weights.values()))
            if numb == len(self):  # each atom now unique
                break
            elif numb == oldnumb:
                x = Counter(weights.values())
                if x[min(x)] > 1:
                    if stab == 3:
                        break
                elif stab >= 2:
                    break

                stab += 1
            elif stab:
                stab = 0

            tries -= 1
            if not tries and numb < oldnumb:
                warning('morgan. number of attempts exceeded. uniqueness has decreased. next attempt will be made')
                tries = 1
        else:
            warning('morgan. number of attempts exceeded')

        return weights
1072756
private function tql2(): void
    {
        for ($i = 1; $i < $this->n; ++$i) {
            $this->e[$i - 1] = $this->e[$i];
        }

        $this->e[$this->n - 1] = 0.0;
        $f = 0.0;
        $tst1 = 0.0;
        $eps = 2.0 ** -52.0;

        for ($l = 0; $l < $this->n; ++$l) {
            // Find small subdiagonal element
            $tst1 = max($tst1, abs($this->d[$l]) + abs($this->e[$l]));
            $m = $l;
            while ($m < $this->n) {
                if (abs($this->e[$m]) <= $eps * $tst1) {
                    break;
                }

                ++$m;
            }

            // If m == l, $this->d[l] is an eigenvalue,
            // otherwise, iterate.
            if ($m > $l) {
                do {
                    // Compute implicit shift
                    $g = $this->d[$l];
                    $p = ($this->d[$l + 1] - $g) / (2.0 * $this->e[$l]);
                    $r = hypot($p, 1.0);
                    if ($p < 0) {
                        $r *= -1;
                    }

                    $this->d[$l] = $this->e[$l] / ($p + $r);
                    $this->d[$l + 1] = $this->e[$l] * ($p + $r);
                    $dl1 = $this->d[$l + 1];
                    $h = $g - $this->d[$l];
                    for ($i = $l + 2; $i < $this->n; ++$i) {
                        $this->d[$i] -= $h;
                    }

                    $f += $h;
                    // Implicit QL transformation.
                    $p = $this->d[$m];
                    $c = 1.0;
                    $c2 = $c3 = $c;
                    $el1 = $this->e[$l + 1];
                    $s = $s2 = 0.0;
                    for ($i = $m - 1; $i >= $l; --$i) {
                        $c3 = $c2;
                        $c2 = $c;
                        $s2 = $s;
                        $g = $c * $this->e[$i];
                        $h = $c * $p;
                        $r = hypot($p, $this->e[$i]);
                        $this->e[$i + 1] = $s * $r;
                        $s = $this->e[$i] / $r;
                        $c = $p / $r;
                        $p = $c * $this->d[$i] - $s * $g;
                        $this->d[$i + 1] = $h + $s * ($c * $g + $s * $this->d[$i]);
                        // Accumulate transformation.
                        for ($k = 0; $k < $this->n; ++$k) {
                            $h = $this->V[$k][$i + 1];
                            $this->V[$k][$i + 1] = $s * $this->V[$k][$i] + $c * $h;
                            $this->V[$k][$i] = $c * $this->V[$k][$i] - $s * $h;
                        }
                    }

                    $p = -$s * $s2 * $c3 * $el1 * $this->e[$l] / $dl1;
                    $this->e[$l] = $s * $p;
                    $this->d[$l] = $c * $p;
                    // Check for convergence.
                } while (abs($this->e[$l]) > $eps * $tst1);
            }

            $this->d[$l] += $f;
            $this->e[$l] = 0.0;
        }

        // Sort eigenvalues and corresponding vectors.
        for ($i = 0; $i < $this->n - 1; ++$i) {
            $k = $i;
            $p = $this->d[$i];
            for ($j = $i + 1; $j < $this->n; ++$j) {
                if ($this->d[$j] < $p) {
                    $k = $j;
                    $p = $this->d[$j];
                }
            }

            if ($k != $i) {
                $this->d[$k] = $this->d[$i];
                $this->d[$i] = $p;
                for ($j = 0; $j < $this->n; ++$j) {
                    $p = $this->V[$j][$i];
                    $this->V[$j][$i] = $this->V[$j][$k];
                    $this->V[$j][$k] = $p;
                }
            }
        }
    }
1349725
def optimizor(molecules, sort_order, ensemble_size, options):
    
    # set variables
    ncpu = options.ncpu
    score_field = options.score_field

    # generate an exhaustive list of all possible ensembles
    ensemble_list = make_ensemble_list(molecules, score_field, ensemble_size)

    # set number of processors.
    if not ncpu:
        ncpu = multiprocessing.cpu_count()

    if ncpu > 1:
        print("Determining the performance of {d} ensembles using {n} processors".format(d=len(ensemble_list), n=ncpu))

        if ncpu > len(ensemble_list):
            ncpu = len(ensemble_list)

        jobs = []
        output_queue = multiprocessing.Queue()

        for ensemble_chunk in chunker(ensemble_list, ncpu):
            p = multiprocessing.Process(target=evaluate,
                                        args=(molecules, ensemble_chunk, sort_order, options, output_queue))
            jobs.append(p)
            p.start()

        # collect results into a dictionary
        results = {}
        for i in range(len(jobs)):
            results.update(output_queue.get())

        # stop jobs
        for j in jobs:
            j.join()

    else:
        print("Determining the performance of {d} ensembles using {n} processor".format(d=len(ensemble_list), n=ncpu))
        results = evaluate(molecules, ensemble_list, sort_order, options)

    # peel away the best performing ensemble
    ensemble = screener.find_best_ensemble(results, options)

    # write out the best performing ensemble
    output.write_ensemble(list(ensemble), options)

    # temp 2/9/15 generate and return a list of auc values and ef at fpf = 0.001 to build up a histogram
    nd = max([results[x].ef.keys() for x in results.keys()][0])
    n = int(round(0.001 * nd))
    ef_list = [results[x].get_prop(n, 'ef') for x in results.keys()]
    auc_list = [results[x].get_prop('auc') for x in results.keys()]
    # auc_list = [[results[x].get_prop('auc'), results[x].get_prop('ensemble')] for x in results.keys()]
    return auc_list, ef_list
1109380
def _compute_Lp_matrix(self):
        
        self.Lp = sum([1/self.eigen_values[i]
                      * np.outer(self.eigen_basis[:, i], self.eigen_basis[:, i])
                      for i in range(1, self.eigen_values.size)])
1318453
def compute(self, runner_results, setup=False, poll=False, ignore_errors=False):
        '''  '''

        for (host, value) in runner_results.get('contacted', {}).iteritems():
            if not ignore_errors and (('failed' in value and bool(value['failed'])) or
                ('rc' in value and value['rc'] != 0)):
                self._increment('failures', host)
            elif 'skipped' in value and bool(value['skipped']):
                self._increment('skipped', host)
            elif 'changed' in value and bool(value['changed']):
                if not setup and not poll:
                    self._increment('changed', host)
                self._increment('ok', host)
            else:
                if not poll or ('finished' in value and bool(value['finished'])):
                    self._increment('ok', host)

        for (host, value) in runner_results.get('dark', {}).iteritems():
            self._increment('dark', host)
129561
def eigen_table(self):
        """"""
        idx = ["Eigenvalue", "Variability (%)", "Cumulative (%)"]
        table = pd.DataFrame(
            np.array(
                [self.eigenvalues, self.inertia, self.cumulative_inertia]
            ),
            columns=["F%s" % i for i in range(1, self.keep + 1)],
            index=idx,
        )

        return table
86038
def eigenvalues_hadamard(matrix1, matrix2):
    

    matrix1 = array(matrix1)  # as arrays
    matrix2 = array(matrix2)

    eig_a = eigvalsh(matrix1)  # eigenvalues (optimized for Hermitian matrices)
    eig_b = eigvalsh(matrix2)

    return eig_a, eig_b