numpy.real

Here are the examples of the python api numpy.real taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

498 Examples 7

5 Source : local_energy.py
with MIT License
from HUJI-Deep

    def add_energy_to_logs(self, logs):
        logs['energy/energy'] = numpy.real(self.exact_variational.energy_observable.current_energy)
        logs['energy/local_energy_variance'] = numpy.real(self.exact_variational.energy_observable.current_local_energy_variance)
        if self.true_ground_state_energy is not None:
            logs['energy/relative_error'] = (self.true_ground_state_energy - numpy.real(self.exact_variational.energy_observable.current_energy)) \
                                            / self.true_ground_state_energy
        
    def on_batch_end(self, batch, logs=None):

5 Source : local_energy_stats.py
with MIT License
from HUJI-Deep

    def add_energy_stats_to_logs(self, logs, generator, prefix=""):
        logs['%senergy/energy' % prefix] = numpy.real(generator.current_energy)
        logs['%senergy/local_energy_variance' % prefix] = numpy.real(generator.current_local_energy_variance)
        if self.true_ground_state_energy is not None:
            logs['%senergy/relative_error' % prefix] = (self.true_ground_state_energy - numpy.real(
                generator.current_energy)) / self.true_ground_state_energy

    def on_batch_end(self, batch, logs=None):

3 Source : matrix.py
with MIT License
from ADicksonLab

def eig_weights(transmat):
    """
    Calculates the weights as the top eigenvector of the transition matrix.

    Input:

    transmat -- An N x N transition matrix as a numpy array or in
                scipy sparse coo format.  Columns should sum to 1.
                Indices: [to][from]

    Output:     An array of weights of size N.
    """

    vals, vecs = scipy.sparse.linalg.eigs(transmat,k=1)
    return np.real(vecs[:,0])/np.real(vecs[:,0].sum())

def mult_weights(transmat,tol=1e-6):

3 Source : _ode.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def _wrap(self, t, y, *f_args):
        f = self.cf(*((t, y[::2] + 1j * y[1::2]) + f_args))
        # self.tmp is a real-valued array containing the interleaved
        # real and imaginary parts of f.
        self.tmp[::2] = real(f)
        self.tmp[1::2] = imag(f)
        return self.tmp

    def _wrap_jac(self, t, y, *jac_args):

3 Source : _ode.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def set_initial_value(self, y, t=0.0):
        """Set initial conditions y(t) = y."""
        y = asarray(y)
        self.tmp = zeros(y.size * 2, 'float')
        self.tmp[::2] = real(y)
        self.tmp[1::2] = imag(y)
        return ode.set_initial_value(self, self.tmp, t)

    def integrate(self, t, step=False, relax=False):

3 Source : test_basic.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_airye(self):
        a = special.airye(0.01)
        b = special.airy(0.01)
        b1 = [None]*4
        for n in range(2):
            b1[n] = b[n]*exp(2.0/3.0*0.01*sqrt(0.01))
        for n in range(2,4):
            b1[n] = b[n]*exp(-abs(real(2.0/3.0*0.01*sqrt(0.01))))
        assert_array_almost_equal(a,b1,6)

    def test_bi_zeros(self):

3 Source : test_basic.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_pbdv_seq(self):
        pbn = special.pbdn_seq(1,.1)
        pbv = special.pbdv_seq(1,.1)
        assert_array_almost_equal(pbv,(real(pbn[0]),real(pbn[1])),4)

    def test_pbdv_points(self):

3 Source : ECD_pulse_construction.py
with MIT License
from alec-eickbusch

    def make_wave(self, pad=False):
        wave = gaussian_wave(sigma=self.sigma, chop=self.chop)
        return np.real(wave), np.imag(wave)


class FakeStorage:

3 Source : ECD_pulse_construction.py
with MIT License
from alec-eickbusch

def plot_trajs_complex(alpha_g, alpha_e=None, bound=None, ax=None):
    if ax is None:
        fig, ax = plt.subplots()
    ax.plot(np.real(alpha_g), np.imag(alpha_g), label="g")
    ax.fill_between(np.real(alpha_g), np.imag(alpha_g), alpha=0.2)
    if alpha_e is not None:
        ax.plot(np.real(alpha_e), np.imag(alpha_e), label="e")
        ax.fill_between(np.real(alpha_e), np.imag(alpha_e), alpha=0.2)
    if bound is not None:
        ax.set_xlim([-bound, bound])
        ax.set_ylim([-bound, bound])
    ax.grid()
    ax.legend(frameon=False)


def plot_trajs_linear(alpha_g, alpha_e=None):

3 Source : fourier.py
with MIT License
from AlexShkarin

def get_real_part(ft):
    """
    Get the fourier transform of the real part only from the fourier transform of a complex variable.
    """
    re_ft=wrap(ft).copy()
    re_ft[1:,1]=(ft[1:,1]+ft[:0:-1,1].conjugate())*0.5
    re_ft[0,1]=np.real(ft[0,1])
    return re_ft.cont

def get_imag_part(ft):

3 Source : centralities.py
with MIT License
from andrenarchy

def get_eigenvector_centralities(nodes: List[Node], definitions: Definitions) -> numpy.array:
    """Compute trust graph eigenvector centralities"""
    trust_graph = get_trust_graph(definitions)
    adjacency_matrix = get_adjacency_matrix(nodes, trust_graph)
    eigenvalues, eigenvectors = eig(adjacency_matrix, left=True, right=False)
    index = numpy.argsort(numpy.real(eigenvalues))[-1]
    centralities = numpy.abs(eigenvectors[:, index])
    return centralities / numpy.max(centralities)

def get_subgraph_centralities(nodes: List[Node], definitions: Definitions) -> numpy.array:

3 Source : centralities.py
with MIT License
from andrenarchy

def get_quorum_eigenvector_centralities(nodes: List[Node], definitions: Definitions) -> numpy.array:
    """Compute quorum eigenvector centralities"""
    fbas = (get_is_slice_contained(definitions), set(nodes))
    hyperedge_list = list(enumerate_quorums(fbas))
    incidence_matrix = get_hypergraph_incidence_matrix(nodes, hyperedge_list)
    MMT = incidence_matrix.dot(incidence_matrix.T)
    eigenvalues, eigenvectors = eig(MMT)
    index = numpy.argsort(numpy.real(eigenvalues))[-1]
    centralities = numpy.abs(eigenvectors[:, index])
    return centralities / numpy.max(centralities)

def get_quorum_subgraph_centralities(nodes: List[Node], definitions: Definitions) -> numpy.array:

3 Source : centralities.py
with MIT License
from andrenarchy

def get_quorum_intersection_eigenvector_centralities(nodes: List[Node],
                                                     definitions: Definitions) -> numpy.array:
    """Compute quorum intersection eigenvector centralities"""
    fbas = (get_is_slice_contained(definitions), set(nodes))
    quorums = list(enumerate_quorums(fbas))
    hyperedge_list = list([a.intersection(b) for a, b in combinations(quorums, 2)])
    incidence_matrix = get_hypergraph_incidence_matrix(nodes, hyperedge_list)
    MMT = incidence_matrix.dot(incidence_matrix.T)
    eigenvalues, eigenvectors = eig(MMT)
    index = numpy.argsort(numpy.real(eigenvalues))[-1]
    centralities = numpy.abs(eigenvectors[:, index])
    return centralities / numpy.max(centralities)

def get_quorum_intersection_subgraph_centralities(nodes: List[Node],

3 Source : centralities.py
with MIT License
from andrenarchy

def get_intactness_eigenvector_centralities(nodes: List[Node], definitions: Definitions,
                                            get_ill_behaved_weight: Callable[[Set[Node]], float]
                                            ) -> numpy.array:
    """Compute intactness eigenvector centralities"""
    M = get_intactness_matrix(nodes, definitions, get_ill_behaved_weight)
    eigenvalues, eigenvectors = eig(M)
    index = numpy.argsort(numpy.real(eigenvalues))[-1]
    centralities = numpy.abs(eigenvectors[:, index])
    return centralities / numpy.max(centralities)

def get_intactness_ls_centralities(nodes: List[Node], definitions: Definitions,

3 Source : centralities.py
with MIT License
from andrenarchy

def get_hierarchical_intactness_eigenvector_centralities(
        nodes: List[Node], definitions: Definitions,
        get_ill_behaved_weight: Callable[[Set[Node]], float]
        ) -> numpy.array:
    """Compute hierarchical intactness eigenvector centralities"""
    M = get_hierarchical_intactness_matrix(nodes, definitions, get_ill_behaved_weight)
    eigenvalues, eigenvectors = eig(M)
    index = numpy.argsort(numpy.real(eigenvalues))[-1]
    centralities = numpy.abs(eigenvectors[:, index])
    return centralities / numpy.max(centralities)

def get_hierarchical_intactness_ls_centralities(

3 Source : centralities.py
with MIT License
from andrenarchy

def get_minimal_intactness_eigenvector_centralities(
        nodes: List[Node], definitions: Definitions,
        get_ill_behaved_weight: Callable[[Set[Node]], float]
        ) -> numpy.array:
    """Compute minimal intactness eigenvector centralities"""
    M = get_minimal_intactness_matrix(nodes, definitions, get_ill_behaved_weight)
    eigenvalues, eigenvectors = eig(M)
    index = numpy.argsort(numpy.real(eigenvalues))[-1]
    centralities = numpy.abs(eigenvectors[:, index])
    return centralities / numpy.max(centralities)

def get_minimal_intactness_ls_centralities(

3 Source : Markov.py
with BSD 3-Clause "New" or "Revised" License
from aristoteleo

    def compute_stationary_distribution(self):
        # if self.W is None:
        # self.eigsys()
        _, vecs = sp.linalg.eigs(self.P, k=1, which="LR")
        p = np.abs(np.real(vecs[:, 0]))
        p = p / np.sum(p)
        return p

    def diffusion_map_embedding(self, n_dims=2, t=1):

3 Source : Markov.py
with BSD 3-Clause "New" or "Revised" License
from aristoteleo

    def compute_stationary_distribution(self, method="eig"):
        if self.p_st is None:
            if method == "null":
                p = np.abs(np.real(null_space(self.P)[:, 0].flatten()))
                p = p / np.sum(p)
                self.p_st = p
            else:
                if self.D is None:
                    self.eigsys()
                p = np.abs(np.real(self.W[:, 0]))
                p = p / np.sum(p)
                self.p_st = p
        return self.p_st

    def simulate_random_walk(self, init_idx, tspan):

3 Source : transforms.py
with MIT License
from asteroid-team

def from_numpy(array, dim: int = -2):
    """Convert complex numpy array to complex-like torch tensor.

    Args:
        array (np.array): array to be converted.
        dim(int, optional): the frequency (or equivalent) dimension along which
            real and imaginary values are concatenated.

    Returns:
        :class:`torch.Tensor`:
            Corresponding torch.Tensor (complex axis in dim `dim`=
    """
    import numpy as np  # Hub-importable

    return torch.cat([torch.from_numpy(np.real(array)), torch.from_numpy(np.imag(array))], dim=dim)


@script_if_tracing

3 Source : spectrum.py
with GNU General Public License v3.0
from barahona-research-group

def eval_spectrum_adj(graph):
    """"""
    return np.real(nx.linalg.spectrum.adjacency_spectrum(graph))


def eigenvalue_ratio(graph, i, j):

3 Source : spectrum.py
with GNU General Public License v3.0
from barahona-research-group

def eval_spectrum_modularity(graph):
    """"""
    return np.real(nx.linalg.spectrum.modularity_spectrum(graph))


@lru_cache(maxsize=None)

3 Source : spectrum.py
with GNU General Public License v3.0
from barahona-research-group

def eval_spectrum_laplacian(graph):
    """"""
    return np.real(nx.linalg.spectrum.laplacian_spectrum(graph))


class Spectrum(FeatureClass):

3 Source : simple_model.py
with MIT License
from bill9800

def mel_real_imag_expand(mel_data):
    # expand the mel data to 2X data with true real and image number
    D = np.zeros((mel_data.shape[0],mel_data.shape[1]*2))
    D[:,::2] = np.real(mel_data)
    D[:,1::2] = np.imag(mel_data)
    return D

def rev_gain(gain,max,sr,fft_size,n_mel):

3 Source : math_utils_test.py
with MIT License
from CEMES-CNRS

    def test_ift(self):
        omega_max = utils.l2w(300)
        omega0 = utils.l2w(800)
        Npts = 2 ** 10
        omega_grid, time_grid = mutils.ftAxis(Npts, omega_max)
        signal_temp = np.sin(omega0 * time_grid) * mutils.gauss1D(time_grid, 0, 100, 1)
        signal_omega = mutils.ft(signal_temp)
        assert np.all(signal_temp == pytest.approx(np.real(mutils.ift(signal_omega))))
        with pytest.raises(Exception):
            mutils.ift(signal_temp, 2)

        with pytest.raises(TypeError):
            mutils.ift(signal_temp, 1.5)
        with pytest.raises(TypeError):
            mutils.ift(signal_temp, "40")

    def test_ft2(self):

3 Source : retweetedgeanalyzerbatch.py
with GNU General Public License v3.0
from cgseife

def comparray_to_reallist(arr):
    inlist = arr.tolist()
    outlist = []
    for tuple in inlist:
        realpart = numpy.real(tuple)
        imagpart = numpy.imag(tuple)
        valsquared = realpart*realpart + imagpart*imagpart
        val = numpy.sqrt(valsquared)
        outlist.append(val)
    return outlist;

def print_list(inlist, file = sys.stdout, delimiter = "\t",endchar = "\n"):

3 Source : kernel.py
with GNU General Public License v3.0
from ComputationalCryoEM

    def circularize(self):
        logger.info("Circularizing kernel")
        kernel = np.real(ifftn(self.kernel))
        kernel = mdim_fftshift(kernel)

        for dim in range(self.ndim):
            logger.info(f"Circularizing dimension {dim}")
            kernel = self.circularize_1d(kernel, dim)

        xx = fftn(mdim_ifftshift(kernel))
        return xx

    def circularize_1d(self, kernel, dim):

3 Source : kernel.py
with GNU General Public License v3.0
from ComputationalCryoEM

    def toeplitz(self, L=None):
        """
        Compute the 3D Toeplitz matrix corresponding to this Fourier Kernel
        :param L: The size of the volumes to be convolved (default M/2, where the dimensions of this Fourier Kernel
            are MxMxM
        :return: An six-dimensional Toeplitz matrix of size L describing the convolution of a volume with this kernel
        """
        if L is None:
            L = int(self.M / 2)

        A = np.eye(L**3, dtype=self.dtype)
        for i in range(L**3):
            A[:, i] = np.real(vol_to_vec(self.convolve_volume(vec_to_vol(A[:, i]))))

        A = vecmat_to_volmat(A)
        return A

3 Source : test_complexPCA.py
with GNU General Public License v3.0
from ComputationalCryoEM

    def testSmallFitTransform(self):
        # Reals
        pca = PCA(n_components=self.components_small)
        Y1 = pca.fit_transform(self.X_small)

        # Complex
        cpca = ComplexPCA(n_components=self.components_small)
        Y2 = cpca.fit_transform(self.X_small.astype(complex_type(self.dtype)))

        # Real part should be the same.
        self.assertTrue(np.allclose(np.real(Y2), Y1))
        # Imag part should be zero.
        self.assertTrue(np.allclose(np.imag(Y2), 0))

    def testLargeFitTransform(self):

3 Source : inverse.py
with MIT License
from cperales

def lapack_zhesv(a, b):
    """
    Inverse matrix usando LAPACK zhesv.

    :param a:
    :param b:
    :return:
    """
    x_zhesv = np.real(la.lapack.zhesv(a=a, b=b)[2])
    return x_zhesv


def lapack_posv(a, b):

3 Source : methods.py
with BSD 3-Clause "New" or "Revised" License
from d-bouvier

def _cast_complex2real(val_by_term, cast_mode):
    """Cast dictionary of values sorted by term from complex to real. """

    _val_by_term = dict()
    for (n, k) in val_by_term.keys():
        if (not n % 2) and (k == n//2):
            _val_by_term[(n, k)] = np.real(val_by_term[(n, k)])
        else:
            _val_by_term[(n, k)] = _complex2real(val_by_term[(n, k)],
                                                 cast_mode=cast_mode)
    return _val_by_term


#========================================#

kwargs_docstring_common_pre = """

3 Source : methods.py
with BSD 3-Clause "New" or "Revised" License
from d-bouvier

    def _corresponding_sigs(self, out_per_phase, phase):
        if phase:
            phase_conj = self.nb_phase - phase
            return np.concatenate((np.real(out_per_phase[phase]),
                                   np.real(out_per_phase[phase_conj]),
                                   np.imag(out_per_phase[phase]),
                                   np.imag(out_per_phase[phase_conj])))
        else:
            return np.real(out_per_phase[0])

    def _fft_mat_condition_numbers(self, p):

3 Source : functions_general.py
with Apache License 2.0
from DanPorter

def complex2str(val, fmt='6.1f'):
    """
    Convert complex number to string
    """

    rl = np.real(val)
    im = np.imag(val)
    fmt1 = '%' + fmt
    fmt2 = '%-' + fmt
    if im >= 0:
        return (fmt1 + ' + i' + fmt2) % (rl, im)
    elif im   <   0:
        return (fmt1 + ' - i' + fmt2) % (rl, np.abs(im))


def multi_replace(string, old=[], new=[]):

3 Source : csdm.py
with BSD 3-Clause "New" or "Revised" License
from deepanshs

    def real(self):
        """Return a csdm object with only the real part of the dependent variable
        components."""
        return np.real(self)

    @property

3 Source : LangevinDiffusion2D.py
with Apache License 2.0
from DelSquared

def animate(state, t):

    # Plot initial plot so that we can change underlying data later
    plt.plot(np.real(state[0,0]),np.real(state[2,0]), 'r.',markersize=15)

    # Set limits of plot
    plt.xlim([-1, 10])
    plt.ylim([-1, 10])
    # Animate the position of the pendulum in time
    for i in range(1, state.shape[1] - 1):
        plt.plot(np.real(state[0,i-1]),np.real(state[2,i-1]), 'w.',markersize=20)
        plt.plot(np.real(state[0,i]),np.real(state[2,i]), 'r.',markersize=15)

        plt.draw()
        plt.pause(0.05)

plt.figure(figsize=(12, 6))

3 Source : LangevinOscillator.py
with Apache License 2.0
from DelSquared

def LangevinOscillator (x,t): #Defining the ODE
  z=x[0]+1j*x[1]
  print("z=",z)
  dz=1j*(w+g*R(t))*z
  print("dz=",dz)
  return np.real(dz),np.imag(dz)

t=np.linspace(0,1000,100000)

3 Source : gradients.py
with MIT License
from DTUWindEnergy

    def __call__(self, x, extrapolate=None):
        y = scipy_PchipInterpolator.__call__(self, np.real(x), extrapolate=extrapolate)
        if np.iscomplexobj(x):
            dy = scipy_PchipInterpolator.__call__(self, np.real(x), nu=1, extrapolate=extrapolate)
            y = y + x.imag * dy * 1j
        return y


class UnivariateSpline(scipy_UnivariateSpline):

3 Source : gradients.py
with MIT License
from DTUWindEnergy

    def __call__(self, x, ext=None):
        y = scipy_UnivariateSpline.__call__(self, np.real(x), ext=ext)
        if np.iscomplexobj(x):
            dy = scipy_UnivariateSpline.__call__(self, np.real(x), nu=1, ext=ext)
            y = y + x.imag * dy * 1j
        return y


def erf(z):

3 Source : wavefront.py
with MIT License
from ehpor

	def real(self):
		'''The real part of the wavefront as function of 2D position on the plane.
		'''
		return np.real(self.electric_field)

	@property

3 Source : wavefront.py
with MIT License
from ehpor

def jones_to_mueller(jones_matrix):
	'''Convert a Jones matrix to a Mueller matrix.

	Parameters
	----------
	jones_matrix : ndarray or tensor field
		The Jones matrix/matrices to convert to Mueller matrix/matrices.

	Returns
	-------
	ndarray or tensor Field
		The Mueller matrix/matrices.
	'''
	return np.real(field_dot(_U_matrix, field_dot(field_kron(jones_matrix, jones_matrix.conj()), _U_matrix.conj().T)))

3 Source : uccvqeabc.py
with GNU Lesser General Public License v3.0
from evangelistalab

    def gradient_ary_feval(self, params):
        grads = self.measure_gradient(params)

        if(self._noise_factor > 1e-14):
            grads = [np.random.normal(np.real(grad_m), self._noise_factor) for grad_m in grads]

        self._curr_grad_norm = np.linalg.norm(grads)
        self._res_vec_evals += 1
        self._res_m_evals += len(self._tamps)

        return np.asarray(grads)

    def report_iteration(self, x):

3 Source : simulation.py
with MIT License
from fancompute

    def compute_index_shift(self):
        """ Computes array of nonlinear refractive index shift"""

        _ = self.solve_fields()
        _ = self.solve_fields_nl()
        index_nl = np.sqrt(np.real(self.eps_r + self.eps_nl))
        index_lin = np.sqrt(np.real(self.eps_r))
        return np.abs(index_nl - index_lin)

    def plt_abs(self, nl=False, cbar=True, outline=True, ax=None, vmin=None, vmax=None, logscale=False, tiled_y=1):

3 Source : nonlinearities.py
with MIT License
from fancompute

    def forward_pass(self, X: np.ndarray):
        X_re = np.real(X)
        X_im = np.imag(X)
        return (X_re > 0) * X_re + 1j * (X_im > 0) * X_im

    def df_dRe(self, a: np.ndarray, b: np.ndarray) -> np.ndarray:

3 Source : nonlinearities.py
with MIT License
from fancompute

    def forward_pass(self, X: np.ndarray):
        X_re = np.real(X)
        X_im = np.imag(X)
        return (X_re > 0) * (X_im > 0) * X

    def df_dRe(self, a: np.ndarray, b: np.ndarray) -> np.ndarray:

3 Source : ConstellationDiagram.py
with GNU General Public License v2.0
from FastNFT

    def __init__(self, constellation):
        """Constructor.

        Parameters
        ----------

        constellation : object
            The constellation from which the symbols passed to plot(...) are
            drawn. Has to be of a class derived from BaseConstellation.
        """
        self._constellation = constellation

        # Set ranges for plotting
        max_real = 1.5*np.max(np.abs(np.real(self._constellation.alphabet)))
        max_imag = 1.5*np.max(np.abs(np.imag(self._constellation.alphabet)))
        self._axis = 1.5 * np.max([max_real, max_imag]) * np.array([-1., 1.])

    def plot(self, symbols, show_bits=False, title=None, new_fig=False):

3 Source : utils.py
with MIT License
from fedimser

def cast_to_real(x):
    """Converts complex np.array (known to be real) to real dtype."""
    ans = np.real(x)
    assert np.allclose(x, ans)
    return ans


def skip_identities(gates):

3 Source : qst.py
with MIT License
from feihoo87

def rhoToV(rho):
    """密度矩阵转相干矢
    """
    dim = rho.shape[0]
    x = (np.real(rho[i, j]) for i, j in combinations(range(dim), 2))
    y = (np.imag(rho[i, j]) for i, j in combinations(range(dim), 2))
    z = (np.real(rho[i, i]) for i in range(1, dim))
    return np.asarray(list(chain(x, y, z)))


def vToRho(V):

3 Source : distortion.py
with MIT License
from feihoo87

def extractKernel(sig_in, sig_out, sample_rate, bw=None, skip=0):
    corr = fft(sig_in) / fft(sig_out)
    ker = np.real(ifftshift(ifft(corr)))
    if bw is not None and bw   <   0.5 * sample_rate:
        k = np.exp(-0.5 * np.linspace(-3.0, 3.0, int(2 * sample_rate / bw))**2)
        ker = np.convolve(ker, k / k.sum(), mode='same')
    return ker[int(skip):len(ker) - int(skip)]


def zDistortKernel(dt: float, params: Sequence[tuple]) -> np.ndarray:

3 Source : func.py
with MIT License
from feihoo87

def Svv(f, T, Z=lambda f: 50 * np.ones_like(f)):
    """
    power spectral density of the series noise voltage
    
    f : list of frequency
    T : temperature
    Z : frequency-dependent complex electrical impedance
        (default 50 Ohm)
    """
    from scipy.constants import h, k
    eta = h * f / (k * T) / (np.exp(h * f / (k * T)) - 1)
    return 4 * k * T * np.real(Z(f)) * eta


def atts(f, atts=[], input=None):

3 Source : xeb.py
with MIT License
from feihoo87

def crossEntropy(P: np.array,
                 Q: np.array,
                 func: Callable = np.log,
                 eps: float = 1e-9) -> float:
    mask = (P > 0) * (Q > eps)
    if isinstance(P, (int, float, complex)):
        return -np.real(P) * np.sum(func(Q[mask]))
    else:
        return -np.sum(P[mask] * func(Q[mask]))


def Fxeb(Pm_lst: Iterable[np.array],

3 Source : states.py
with Apache License 2.0
from gecrooks

    def sample(self, trials: int) -> np.ndarray:
        """Measure the state in the computational basis the the given number
        of trials, and return the counts of each output configuration.
        """
        # TODO: Can we do this within backend?
        probs = np.real(self.probabilities())
        res = np.random.multinomial(trials, probs.ravel())
        res = res.reshape(probs.shape)
        return res

    def expectation(

See More Examples