def _brownian_eigs(n_grid, lag_time, grad_potential, xmin, xmax, reflect_bc): """Analytic eigenvalues/eigenvectors for 1D Brownian dynamics """ import scipy.linalg ONE_OVER_SQRT_2PI = 1.0 / (np.sqrt(2 * np.pi)) normalpdf = lambda x: ONE_OVER_SQRT_2PI * np.exp(-0.5 * (x * x)) grid = np.linspace(xmin, xmax, n_grid) width = grid[1] - grid[0] transmat = np.zeros((n_grid, n_grid)) for i, x_i in enumerate(grid): if reflect_bc: for offset in range(-(n_grid - 1), n_grid): x_j = x_i + (offset * width) j = _reflect_boundary_conditions(i + offset, 0, n_grid - 1) # What is the probability of going from x_i to x_j in one step? diff = (x_j - x_i + DT * grad_potential(x_i)) / DT_SQRT_2D transmat[i, j] += normalpdf(diff) else: for j, x_j in enumerate(grid): # What is the probability of going from x_i to x_j in one step? diff = (x_j - x_i + DT * grad_potential(x_i)) / DT_SQRT_2D transmat[i, j] += normalpdf(diff) transmat[i, :] = transmat[i, :] / np.sum(transmat[i, :]) transmat = np.linalg.matrix_power(transmat, lag_time) u, v = scipy.linalg.eig(transmat) order = np.argsort(np.real(u))[::-1] return np.real_if_close(u[order]), np.real_if_close(v[:, order])
def compute_score(self): self.scores = [] # We now have a dictionary # start with a 'row' of all zeroes adjacency = [] adjacency = adjacency + [0]*(len(self.user_dict) - len(adjacency)) # Adjacency Matrix A = np.zeros( shape=(len(self.user_dict), len(self.user_dict)) ) # keep track of A's rows outer_count = 0 for mentioning_user in self.user_dict: inner_count = 0 for mentioned_user in self.user_dict: if( mentioned_user in self.user_dict[mentioning_user]['mentioned'] ): adjacency[inner_count] = 1 else: adjacency[inner_count] = 0 inner_count += 1 # print adjacency A[outer_count] = adjacency outer_count += 1 self.scores = [np.dot(A, np.transpose(A)), np.dot(np.transpose(A), A)] dictList = [] print "Hub:" w, v = LA.eig(np.dot(A, np.transpose(A))) i = np.real_if_close(w).argmax() principal = v[:,i] print self.user_dict.keys()[principal.argmax()] print "Authority:" w, v = LA.eig(np.dot(A, np.transpose(A))) i = np.real_if_close(w).argmax() principal = v[:,i] print self.user_dict.keys()[principal.argmax()]
def doublewell_eigs(n_grid, lag_time=1, grad_potential=DOUBLEWELL_GRAD_POTENTIAL): """Analytic eigenvalues/eigenvectors for the doublwell system. """ import scipy.linalg ONE_OVER_SQRT_2PI = 1.0 / (np.sqrt(2*np.pi)) normalpdf = lambda x : ONE_OVER_SQRT_2PI * np.exp(-0.5 * (x*x)) grid = np.linspace(-np.pi, np.pi, n_grid) width = grid[1]-grid[0] transmat = np.zeros((n_grid, n_grid)) for i, x_i in enumerate(grid): for offset in range(-(n_grid-1), n_grid): x_j = x_i + (offset * width) j = _reflect_boundary_conditions(i+offset, 0, n_grid-1) # What is the probability of going from x_i to x_j in one step? diff = (x_j - x_i + DT * grad_potential(x_i)) / DT_SQRT_2D transmat[i, j] += normalpdf(diff) transmat[i, :] = transmat[i, :] / np.sum(transmat[i, :]) transmat = np.linalg.matrix_power(transmat, lag_time) u, v = scipy.linalg.eig(transmat) order = np.argsort(np.real(u))[::-1] return np.real_if_close(u[order]), np.real_if_close(v[:, order])
def epsilon(a_one,a_two,gamma): # laplacian l_one = laplacian(a_one) l_two = laplacian(a_two) # eigenvalues e_one = np.real_if_close(np.linalg.eigvals(l_one)) e_two = np.real_if_close(np.linalg.eigvals(l_two)) # sorting e_one.sort() e_two.sort() # excluding smallest value (zero) ee_one = np.real_if_close(e_one[1:],tol=1e-10) ee_two = np.real_if_close(e_two[1:],tol=1e-10) print ee_one print ee_two # omega omega_one = np.sqrt([round(l,10) for l in ee_one]) omega_two= np.sqrt([round(l,10) for l in ee_two]) # K K_one = 1 / rho_unnormalized_int(omega_k=omega_one, gamma=gamma) K_two = 1 / rho_unnormalized_int(omega_k=omega_two, gamma=gamma) # epsilon return np.sqrt(density_diff_int(omega_one, omega_two, K_one, K_two, gamma))
def _check(self, res, ref): if hasattr(res, "get_x"): x = res.get_x() for k in list(res.keys()): if np.all(res[k] == x): continue elif np.any(np.iscomplex(res[k])) or np.any(np.iscomplex(ref[k])): # Interpolate Re and Im of the results to compare. x = x.reshape((-1,)) refx = ref[ref.x].reshape((-1,)) d1 = InterpolatedUnivariateSpline(x, np.real(res[k]).reshape((-1,))) d2 = InterpolatedUnivariateSpline(refx, np.real(ref[k]).reshape((-1,))) ok(d1(x), d2(x), rtol=self.er, atol=self.ea, msg=("Test %s FAILED (Re)" % self.test_id)) d1 = InterpolatedUnivariateSpline(x, np.imag(res[k]).reshape((-1,))) d2 = InterpolatedUnivariateSpline(refx, np.imag(ref[k]).reshape((-1,))) ok(d1(x), d2(x), rtol=self.er, atol=self.ea, msg=("Test %s FAILED (Im)" % self.test_id)) else: # Interpolate the results to compare. x = x.reshape((-1,)) refx = ref[ref.x].reshape((-1,)) d1 = InterpolatedUnivariateSpline(x, np.real_if_close(res[k]).reshape((-1,))) d2 = InterpolatedUnivariateSpline(refx, np.real_if_close(ref[k]).reshape((-1,))) ok(d1(x), d2(x), rtol=self.er, atol=self.ea, msg=("Test %s FAILED" % self.test_id)) elif isinstance(res, results.op_solution): for k in list(res.keys()): assert k in ref ok(res[k], ref[k], rtol=self.er, atol=self.ea, msg=("Test %s FAILED" % self.test_id)) elif isinstance(res, results.pz_solution): # recover the reference signularities from Re/Im data ref_sing_keys = list(ref.keys())[:] ref_sing_keys.sort() assert len(ref_sing_keys) % 2 == 0 ref_sing = [ ref[ref_sing_keys[int(len(ref_sing_keys) / 2) + k]] + ref[ref_sing_keys[k]] * 1j for k in range(int(len(ref_sing_keys) / 2)) ] ref_poles_num = len([k for k in ref.keys() if k[:4] == "Re(p"]) poles_ref, zeros_ref = ref_sing[:ref_poles_num], ref_sing[ref_poles_num:] assert len(poles_ref) == len(res.poles) pz._check_singularities(res.poles, poles_ref) assert len(zeros_ref) == len(res.zeros) pz._check_singularities(res.zeros, zeros_ref) else: if isinstance(res, list) or isinstance(res, tuple): for i, j in zip(res, ref): self._check(i, j) elif res is not None: for k in list(res.keys()): assert k in ref if isinstance(res[k], dict): # hence ref[k] will be a dict too self._check(res[k], ref[k]) elif isinstance(ref[k], sympy.Basic) and isinstance(res[k], sympy.Basic): # get rid of assumptions. Evaluate only expression rf = parse_expr(str(ref[k])) rs = parse_expr(str(res[k])) assert (rs == rf) or (sympy.simplify(rf / rs) == 1) else: assert res[k] == ref[k]
def _fit_asymetric(self, counts): rc = counts + self.prior_counts transmat = rc.astype(float) / rc.sum(axis=1)[:, None] u, lv = scipy.linalg.eig(transmat, left=True, right=False) order = np.argsort(-np.real(u)) u = np.real_if_close(u[order]) lv = np.real_if_close(lv[:, order]) populations = lv[:, 0] populations /= populations.sum(dtype=float) return transmat, populations
def _solve_msm_eigensystem(transmat, k): """Find the dominant eigenpairs of an MSM transition matrix Parameters ---------- transmat : np.ndarray, shape=(n_states, n_states) The transition matrix k : int The number of eigenpairs to find. Notes ----- Normalize the left (:math:`\phi`) and right (:math:``\psi``) eigenfunctions according to the following criteria. * The first left eigenvector, \phi_1, _is_ the stationary distribution, and thus should be normalized to sum to 1. * The left-right eigenpairs should be biorthonormal: <\phi_i, \psi_j> = \delta_{ij} * The left eigenvectors should satisfy <\phi_i, \phi_i>_{\mu^{-1}} = 1 * The right eigenvectors should satisfy <\psi_i, \psi_i>_{\mu} = 1 Returns ------- eigvals : np.ndarray, shape=(k,) The largest `k` eigenvalues lv : np.ndarray, shape=(n_states, k) The normalized left eigenvectors (:math:`\phi`) of ``transmat`` rv : np.ndarray, shape=(n_states, k) The normalized right eigenvectors (:math:`\psi`) of ``transmat`` """ u, lv, rv = scipy.linalg.eig(transmat, left=True, right=True) order = np.argsort(-np.real(u)) u = np.real_if_close(u[order[:k]]) lv = np.real_if_close(lv[:, order[:k]]) rv = np.real_if_close(rv[:, order[:k]]) # 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
def eigimages(self, n_eigs=None): ''' Create eigenimages up to the n_eigs. Parameters ---------- n_eigs : None or int The number of eigenimages to create. When n_eigs is negative, the last -n_eig eigenimages are created. If None is given, the number in `~PCA.n_eigs` will be returned. Returns ------- eigimgs : `~numpy.ndarray` 3D array, where the first dimension if the number of eigenvalues. ''' if n_eigs is None: n_eigs = self.n_eigs if n_eigs > 0: iterat = range(n_eigs) elif n_eigs < 0: # We're looking for the noisy components whenever n_eigs < 0 # Find where we have valid eigenvalues, and use the last # n_eigs of those. iterat = self._valid_eigenvectors()[n_eigs:] for ct, idx in enumerate(iterat): eigimg = np.zeros(self.data.shape[1:], dtype=float) for channel in range(self.data.shape[0]): if self._mean_sub: mean_value = np.nanmean(self.data[channel]) eigimg += np.nan_to_num((self.data[channel] - mean_value) * np.real_if_close( self.eigvecs[channel, idx])) else: eigimg += np.nan_to_num(self.data[channel] * np.real_if_close( self.eigvecs[channel, idx])) if ct == 0: eigimgs = eigimg else: eigimgs = np.dstack((eigimgs, eigimg)) if eigimgs.ndim == 3: return eigimgs.swapaxes(0, 2) else: return eigimgs
def _normalize_gain(self): """ Normalize the gain factor so that the maximum of |H(f)| stays 1 or a previously stored maximum value of |H(f)|. Do this every time a P or Z has been changed. Called by setModelData() and when cmbNorm is activated """ norm = qget_cmb_box(self.ui.cmbNorm, data=False) self.ui.ledGain.setEnabled(norm == 'None') if norm != self.norm_last: qstyle_widget(self.ui.butSave, 'changed') if not np.isfinite(self.zpk[2]): self.zpk[2] = 1. self.zpk[2] = np.real_if_close(self.zpk[2]).item() if np.iscomplex(self.zpk[2]): logger.warning("Casting complex to real for gain k!") self.zpk[2] = np.abs(self.zpk[2]) if norm != "None": b, a = zpk2tf(self.zpk[0], self.zpk[1], self.zpk[2]) [w, H] = freqz(b, a, whole=True) Hmax = max(abs(H)) if not np.isfinite(Hmax) or Hmax > 1e4 or Hmax < 1e-4: Hmax = 1. if norm == "1": self.zpk[2] = self.zpk[2] / Hmax # normalize to 1 elif norm == "Max": if norm != self.norm_last: # setting has been changed -> 'Max' self.Hmax_last = Hmax # use current design to set Hmax_last self.zpk[2] = self.zpk[2] / Hmax * self.Hmax_last self.norm_last = norm # store current setting of combobox self._restore_gain()
def test_spicefft(): """Test fourier.spicefft() and printing.print_spicefft()""" for w in (ahkab.options.RECT_WINDOW, ahkab.options.BART_WINDOW, ahkab.options.HANN_WINDOW, ahkab.options.HAMM_WINDOW, ahkab.options.BLACK_WINDOW, ahkab.options.HARRIS_WINDOW, ahkab.options.KAISER_WINDOW): fsp, Fsp, THDsp = ahkab.fourier.spicefft('vn1', r, window=w) fsp, Fsp, THDsp = ahkab.fourier.spicefft('vn1', r, window='GAUSS', alpha=3000) ahkab.printing.print_spicefft('vn1', fsp, Fsp, uformat='UNORM', window='GAUSS') assert np.allclose(fsp, np.linspace(0, 512*1000, 512, endpoint=False)) assert len(fsp) == 512 assert len(Fsp) == 512 fsp, Fsp, THDsp = ahkab.fourier.spicefft('vn1', r, window='GAUSS', alpha=3000, np=4096) assert len(fsp) == 2048 assert len(Fsp) == 2048 assert fsp[0] == 0 assert np.real(Fsp[0]) == np.real_if_close(Fsp[0]) f, F, THD = ahkab.fourier.spicefft('vn1', r, 10e3) ahkab.printing.print_spicefft('vn1', f, F, THD, outfile='stdout') f, F, THD = ahkab.fourier.spicefft('vn1', r, 10e3, fmin=20e3, fmax=50e3) assert np.allclose(f, np.array([0., 20000., 30000., 40000., 50000.])) ahkab.printing.print_spicefft('vn1', f, F, THD, outfile='stdout') f1, F1, THD1 = ahkab.fourier.spicefft('vn1', r, 10e3, window='HANN', **{'from':.1e-3, 'to':.4e-3}) f2, F2, THD1 = ahkab.fourier.spicefft('vn1', r, 10e3, window='HANN', **{'start':.1e-3, 'stop':.4e-3}) assert np.allclose(f1, f2) assert np.allclose(F1, F2)
def _add_relaxation(self, f_set, J0, J1, J2): H0_vecs = self.H0_vecs # cache locally J0ab = J0(self.w_diff) J1ab = J1(self.w_diff) J2ab = J2(self.w_diff) # pprint(J1ab) f2 = [] for A, Jq in zip(f_set, (J2ab, J1ab, J0ab, J1ab, J2ab)): A = dot(dot(H0_vecs.conj().T, A), H0_vecs) A *= A.conj() A *= Jq A = real_if_close(A) f2.append(A) f2 = array(f2) # pprint(f2) Rab = f2.sum(axis=0) diag_idx = diag_indices_from(Rab) Rab[diag_idx] = 0 assert allclose(Rab, Rab.T) Rab[diag_idx] = -Rab.sum(axis=1) self.info("Redfield matrix:") self.pprint(Rab) self.Rab_list.append(Rab)
def second_order_solver(FF,GG,HH, eigmax=1.0+1e-6): # from scipy.linalg import qz from dolo.numeric.extern.qz import qzordered from numpy import array,mat,c_,r_,eye,zeros,real_if_close,diag,allclose,where,diagflat from numpy.linalg import solve Psi_mat = array(FF) Gamma_mat = array(-GG) Theta_mat = array(-HH) m_states = FF.shape[0] Xi_mat = r_[c_[Gamma_mat, Theta_mat], c_[eye(m_states), zeros((m_states, m_states))]] Delta_mat = r_[c_[Psi_mat, zeros((m_states, m_states))], c_[zeros((m_states, m_states)), eye(m_states)]] [Delta_up,Xi_up,UUU,VVV,eigval] = qzordered(Delta_mat, Xi_mat,) VVVH = VVV.T VVV_2_1 = VVVH[m_states:2*m_states, :m_states] VVV_2_2 = VVVH[m_states:2*m_states, m_states:2*m_states] UUU_2_1 = UUU[m_states:2*m_states, :m_states] PP = - solve(VVV_2_1, VVV_2_2) # slightly different check than in the original toolkit: assert allclose(real_if_close(PP), PP.real) PP = PP.real return [eigval,PP]
def __init__( self, vectors= Matrix.eye, mean= numpy.zeros, ): mean = mean if callable(mean) else numpy.array(mean).flatten()[None, :] vectors = vectors if callable(vectors) else Matrix(vectors) stack=helpers.autoshape([ [vectors], [mean ], ],default= 1) #unpack the stack into the object's parameters self.vectors = Matrix(numpy.real_if_close(stack[0, 0])) self.mean = Matrix(numpy.real_if_close(stack[1, 0]))
def BorueErukhimovich_Powerlaw(q, C, r0, s, t, nu): """Borue-Erukhimovich model ending in a power-law. Inputs: ------- ``q``: independent variable ``C``: scaling factor ``r0``: typical el.stat. screening length ``s``: dimensionless charge concentration ``t``: dimensionless temperature ``nu``: excluded volume parameter Formula: -------- ``C*(x^2+s)/((x^2+s)(x^2+t)+1)`` where ``x=q*r0`` if ``q<qsep`` ``A*q^(-1/nu)``if ``q>qsep`` ``A`` and ``qsep`` are determined from conditions of smoothness at the cross-over. """ def get_xsep(alpha, s, t): A = alpha + 2 B = 2 * s * alpha + t * alpha + 4 * s C = s * t * alpha + alpha + alpha * s ** 2 + alpha * s * t - 2 + 2 * s ** 2 D = alpha * s ** 2 * t + alpha * s r = np.roots([A, B, C, D]) #print "get_xsep: ", alpha, s, t, r return r[r > 0][0] ** 0.5 get_B = lambda C, xsep, s, t, nu:C * (xsep ** 2 + s) / ((xsep ** 2 + s) * (xsep ** 2 + t) + 1) * xsep ** (1.0 / nu) x = q * r0 xsep = np.real_if_close(get_xsep(-1.0 / nu, s, t)) A = get_B(C, xsep, s, t, nu) return np.piecewise(q, (x < xsep, x >= xsep), (lambda a:BorueErukhimovich(a, C, r0, s, t), lambda a:A * (a * r0) ** (-1.0 / nu)))
def test_it(self): actuation_type = 'robin' bound_cond_type = 'robin' param = [2., 1.5, -3., -1., -.5] adjoint_param = ef.get_adjoint_rad_evp_param(param) a2, a1, a0, alpha, beta = param l = 1. spatial_disc = 10 dz = sim.Domain(bounds=(0, l), num=spatial_disc) T = 1. temporal_disc = 1e2 dt = sim.Domain(bounds=(0, T), num=temporal_disc) n = 10 eig_freq, eig_val = ef.compute_rad_robin_eigenfrequencies(param, l, n) init_eig_funcs = np.array([ef.SecondOrderRobinEigenfunction(om, param, dz.bounds) for om in eig_freq]) init_adjoint_eig_funcs = np.array([ef.SecondOrderRobinEigenfunction(om, adjoint_param, dz.bounds) for om in eig_freq]) # normalize eigenfunctions and adjoint eigenfunctions adjoint_and_eig_funcs = [cr.normalize_function(init_eig_funcs[i], init_adjoint_eig_funcs[i]) for i in range(n)] eig_funcs = np.array([f_tuple[0] for f_tuple in adjoint_and_eig_funcs]) adjoint_eig_funcs = np.array([f_tuple[1] for f_tuple in adjoint_and_eig_funcs]) # register eigenfunctions register_base("eig_funcs", eig_funcs, overwrite=True) register_base("adjoint_eig_funcs", adjoint_eig_funcs, overwrite=True) # derive initial field variable x(z,0) and weights start_state = cr.Function(lambda z: 0., domain=(0, l)) initial_weights = cr.project_on_base(start_state, adjoint_eig_funcs) # init trajectory u = tr.RadTrajectory(l, T, param, bound_cond_type, actuation_type) # determine (A,B) with weak-formulation (pyinduct) rad_pde = ut.get_parabolic_robin_weak_form("eig_funcs", "adjoint_eig_funcs", u, param, dz.bounds) cf = sim.parse_weak_formulation(rad_pde) ss_weak = cf.convert_to_state_space() # determine (A,B) with modal-transfomation A = np.diag(np.real_if_close(eig_val)) B = a2*np.array([adjoint_eig_funcs[i](l) for i in xrange(len(eig_freq))]) ss_modal = sim.StateSpace("eig_funcs", A, B) # check if ss_modal.(A,B) is close to ss_weak.(A,B) self.assertTrue(np.allclose(np.sort(np.linalg.eigvals(ss_weak.A)), np.sort(np.linalg.eigvals(ss_modal.A)), rtol=1e-05, atol=0.)) self.assertTrue(np.allclose(np.array([i[0] for i in ss_weak.B]), ss_modal.B)) # display results if show_plots: t, q = sim.simulate_state_space(ss_modal, u, initial_weights, dt) eval_d = ut.evaluate_approximation("eig_funcs", q, t, dz, spat_order=1) win1 = vis.PgAnimatedPlot([eval_d], title="Test") win2 = vis.PgSurfacePlot(eval_d[0]) app.exec_()
def make_lcp(A,F=0.25): """ Copyright 2012, Michael Andersen, DIKU, michael (at) diku (dot) dk """ # [x, b] = MAKE_LCP(A): Make LCP # # INPUT: # # A -- The coefficient matrix in the LCP # F -- The fraction of zero-values in the x-solution. # # OUTPUT: # # x -- A solution for the LCP problem. # b -- The right hand side vector # # Port of Kenny Erleben, DIKU 2011 Matlab code to Python ##### Get of number of variable ########## N = np.size(A,0) # Pick a dimension, it should be NxN ##### Generate a random LCP solution ########## x = np.random.uniform(0,1,(N,1)) x[x < F] = 0 # x = np.real_if_close(x) ##### Generate a right-hand-side vector that is ########## ##### consistent with a random solution ########## b = np.zeros((N,1)) s = np.real_if_close(np.dot(A,x)) b[x>0] = -s[x>0] return (x, b)
def dot_product_l2(first, second): """ vectorized version of dot_product :param first: numpy.ndarray of function :param second: numpy.ndarray of function :return: numpy.nadarray of inner product """ # TODO seems like for now vectorize is the better alternative here # frst = sanitize_input(first, Function) # scnd = sanitize_input(second, Function) # # res = np.zeros_like(frst) # # first_iter = frst.flat # second_iter = scnd.flat # res_iter = res.flat # # while True: # try: # f = first_iter.next() # s = second_iter.next() # r = res_iter.next() # r[...] = _dot_product_l2(f, s) # except StopIteration: # break # # return res if "handle" not in dot_product_l2.__dict__: dot_product_l2.handle = np.vectorize(_dot_product_l2, otypes=[np.complex]) return np.real_if_close(dot_product_l2.handle(first, second))
def b_conv(v1, v2): w1 = dual.fft(v1[rand_perm[0]]) w2 = dual.fft(v2[rand_perm[1]]) return np.real_if_close(dual.ifft(w1 * w2))
def extract_theta(gateset): """ For a given gateset, obtain the angle between the "X axis of rotation" and the "true" X axis (perpendicular to Z). (Angle of misalignment between "Gx" axis of rotation and X axis as defined by "Gz".) WARNING: This is a gauge-covariant parameter! (I think!) Gauge must be fixed prior to estimating. Parameters ---------- gateset : GateSet The gateset whose X axis misaligment is to be calculated. Returns ------- thetaVal : float The value of theta for the input gateset. """ decomp = _gt.decompose_gate_matrix( gateset.gates['Gx'] ) thetaVal = _np.real_if_close( [ _np.arccos( _np.dot(decomp['axis of rotation'], [0,1,0,0]))])[0] if thetaVal > _np.pi/2: thetaVal = _np.pi - thetaVal elif thetaVal < -_np.pi/2: thetaVal = _np.pi + thetaVal return thetaVal
def values(self): """Get all of the results set's variables values.""" data = self.asmatrix() values = [np.real_if_close(data[0, :])] for i in range(1, data.shape[0]): values.append(data[i, :]) return values
def __call__(self, weights, weight_label): """ evaluation function for approximated control law :param weights: 1d ndarray of approximation weights :param weight_label: string, label of functions the weights correspond to. :return: control output u """ res = {} output = 0+0j # add dynamic part for lbl, law in self._cfs.get_dynamic_terms().items(): dst_weights = [0] if "E" in law is not None: # build eval vector if lbl not in self._eval_vectors.keys(): self._eval_vectors[lbl] = self._build_eval_vector(law) # collect information info = TransformationInfo() info.src_lbl = weight_label info.dst_lbl = lbl info.src_base = get_base(weight_label, 0) info.dst_base = get_base(lbl, 0) info.src_order = int(weights.size / info.src_base.size) - 1 info.dst_order = int(next(iter(self._eval_vectors[lbl].values())).size / info.dst_base.size) - 1 # look up transformation if info not in self._transformations.keys(): # fetch handle handle = get_weight_transformation(info) self._transformations[info] = handle # transform weights dst_weights = self._transformations[info](weights) # evaluate vectors = self._eval_vectors[lbl] for p, vec in vectors.items(): output = output + np.dot(vec, np.power(dst_weights, p)) res[lbl] = dst_weights # add constant term static_terms = self._cfs.get_static_terms() if "f" in static_terms: output = output + static_terms["f"] # TODO: replace with the one from utils if abs(np.imag(output)) > np.finfo(np.complex128).eps * 100: print("Warning: Imaginary part of output is nonzero! out = {0}".format(output)) out = np.real_if_close(output, tol=10000000) if np.imag(out) != 0: raise ValueError("calculated complex control output u={0}," " check for errors in control law!".format(out)) res["output"] = out return res
def convolve(self, X): """ Convolve X with a kernel in frequency space. Args: X: array to be convolved Returns: correlation of X with the kernel """ Fkernel_shape = np.array(self.Fkernel.shape)[self.axes] FX = np.fft.fftn(X, axes=self.axes, s=Fkernel_shape) Fy = self._sum(FX * self.Fkernel) correlation = np.real_if_close( np.fft.ifftn(Fy, axes=self.axes)) return np.real_if_close(np.fft.fftshift(correlation, axes=self.axes), tol=1e7)
def min_y(self): r = self._min_y if r is None: t_lst = [0, 1] for t in numpy.real_if_close(self._solve_quadratic(0, *self.points_y), tol=1e5): if 0<t and t<1: t_lst.append(t) r = self._min_y = min([self[t] for t in t_lst]) return r
def _mround(z): """Base function to generate the ufunc round""" z = np.real_if_close(z) if np.iscomplex(z): return _mround(np.real(z)) + 1j*_mround(np.imag(z)) s = 1 if z >= 0 else -1 res = z - s*(abs(z) % 1) if abs(z) % 1 < .5 \ else z + s*(1 - (abs(z)%1)) return res
def spatialCoeff(fcoeff): coeff = np.zeros(fcoeff.shape,dtype = 'float') dim_len = coeff.shape[0] for ii in range(coeff.shape[3]): coeff[:,:,:,ii] = np.real_if_close(np.fft.ifftn(fcoeff[:,:,:,ii])) coeff[:,:,:,ii] = np.roll(coeff[:,:,:,ii], dim_len/2, axis = 0) coeff[:,:,:,ii] = np.roll(coeff[:,:,:,ii], dim_len/2, axis = 1) coeff[:,:,:,ii] = np.roll(coeff[:,:,:,ii], dim_len/2, axis = 2) return coeff
def CF_gz_AC(parms, tau, wixi=wixi): u""" Axial (1D) diffusion in a TIR-FCS setup. From Two species (bound/unbound) this is the cross correlation part. This function is called by other functions within this module. *parms* - a list of parameters. Parameters (parms[i]): [0] D_3D 3D Diffusion coefficient (species A) [1] D_2D 2D Diffusion coefficient of bound species C [2] sigma lateral size of the point spread function sigma = simga_0 * lambda / NA [3] a side size of the square pinhole [4] d_eva evanescent decay length (decay to 1/e) [5] Conc_3D 3-dimensional concentration of species A [6] Conc_2D 2-dimensional concentration of species C [7] eta_3D molecular brightness of species A [8] eta_2D molecular brightness of species C [9] k_a Surface association rate constant [10] k_d Surface dissociation rate constant *tau* - lag time """ D = parms[0] #D_2D = parms[1] #sigma = parms[2] # a = parms[3] d_eva = parms[4] Conc_3D = parms[5] # ligand concentration in solution Conc_2D = parms[6] eta_3D = parms[7] eta_2D = parms[8] k_a = parms[9] k_d = parms[10] # Define some other constants: K = k_a/k_d # equilibrium constant Beta = 1/(1 + K*Conc_3D) Re = D / d_eva**2 Rt = D * (Conc_3D / (Beta * Conc_2D))**2 Rr = k_a * Conc_3D + k_d # Define even more constants: sqrtR1 = -Rr/(2*nps.sqrt(Rt)) + nps.sqrt( Rr**2/(4*Rt) - Rr ) sqrtR2 = -Rr/(2*nps.sqrt(Rt)) - nps.sqrt( Rr**2/(4*Rt) - Rr ) R1 = sqrtR1 **2 R2 = sqrtR2 **2 # And even more more: sqrtR3 = sqrtR1 + nps.sqrt(Re) sqrtR4 = sqrtR2 + nps.sqrt(Re) #R3 = sqrtR3 **2 #R4 = sqrtR4 **2 # Calculate return function A1 = eta_2D * Conc_2D * k_d / (eta_3D * Conc_3D) A2 = sqrtR4*wixi(-nps.sqrt(tau*R1)) - sqrtR3*wixi(-nps.sqrt(tau*R2)) A3 = ( sqrtR1 - sqrtR2 ) * wixi( nps.sqrt(tau*Re) ) A4 = ( sqrtR1 - sqrtR2 ) * sqrtR3 * sqrtR4 Solution = A1 * ( A2 + A3 ) / A4 # There are some below numerical errors-imaginary numbers. # We do not want them. return np.real_if_close(Solution)
def eval_handle(z): # TODO call uniform complex converter instead res = np.real_if_close(sum([weights[i] * base[i](z) for i in range(weights.shape[0])]), tol=1e6) if not all(np.imag(res) == 0): print(("warning: complex values encountered! {0}".format(np.max(np.imag(res))))) # return np.real(res) return np.zeros_like(z) return res
def ExpandCoeff(coeff, new_side_len): coeff[:,:,:,0] = np.real_if_close(np.fft.ifftn(coeff[:,:,:,0])) coeff[:,:,:,0] = np.fft.fftshift(coeff[:,:,:,0]) new_coeff = np.ndarray(shape = (new_side_len,new_side_len,new_side_len,coeff.shape[3]),dtype = 'complex128') new_coeff[new_side_len/2-10:new_side_len/2+11,new_side_len/2-10:new_side_len/2+11,\ new_side_len/2-10:new_side_len/2+11,0]=coeff[:,:,:,0] new_coeff[:,:,:,0] = np.fft.ifftshift(new_coeff[:,:,:,0]) new_coeff[:,:,:,0] = np.fft.fftn(new_coeff[:,:,:,0]) new_coeff[0,0,0,1] = new_coeff[0,0,0,0] return new_coeff
def plotfunc(fun): global ff f = fun(xv) ff = np.fft.fftshift(np.fft.fft(f)) plotx = np.linspace(-Lx,Lx,200) py.plot(plotx,np.real_if_close(map(interp, plotx)),'c-',linewidth=2) py.plot(plotx,fun(plotx),'k--',linewidth=2) py.plot(xv,f,'ro',linewidth=2,markeredgecolor='r',markersize=6.0) py.ylim(-1.5,1.5) py.xlim(-Lx,Lx)
def get_stationary_distribution(self): """Compute the stationary distribution of states. """ # The stationary distribution is proportional to the left-eigenvector # associated with the largest eigenvalue (i.e., 1) of the transition # matrix. check_is_fitted(self, "transmat_") eigvals, eigvecs = np.linalg.eig(self.transmat_.T) eigvec = np.real_if_close(eigvecs[:, np.argmax(eigvals)]) return eigvec / eigvec.sum()
def PCAcombinedweights( fileloc, numPCs ): #PCA on combined weights for all dimensions (x,y,z,alpha,beta,gamma) all_PCs_list = [] x_raw_all = [] x_all = [] x_raw_all = [] dict_x_all = [] #Import data df = pd.read_csv( fileloc, delimiter=' ', names=['bf1', 'bf2', 'bf3', 'bf4', 'bf5', 'bf6', 'target']) df.head() features = ['bf1', 'bf2', 'bf3', 'bf4', 'bf5', 'bf6'] x = df.loc[:, features].values x_raw = x x_raw_all.append(x_raw) #Scale the weights x = StandardScaler().fit_transform(x) x_all.append(x) x_raw = np.array((x_raw)) x_all = np.squeeze(np.array((x_all))) #Calculate Z,V,mu,sigma cov_mat = np.cov(x_all.T) #Compute covariance matrix eig_vals, eig_vecs = np.linalg.eig( cov_mat) #Eigendecomposition on covariance matrix eig_vecs = eig_vecs.real eig_vals = np.real_if_close(eig_vals, tol=10) idx = eig_vals.argsort()[::-1] eig_vals = eig_vals[idx] eig_vecs = eig_vecs[:, idx] #Choose the 1st k eigenvectors corresponding to the highest eigenvalues V = eig_vecs[:, 0:numPCs] V_t = np.transpose(V) Z = np.matmul(x_all, V) #Define mu and sigma vectors mu = np.mean(x_raw, axis=0) sigma = np.std(x_raw, axis=0) return Z, V_t, mu, sigma
def r_par(m, theta_i): """ Calculates the reflected amplitude for parallel polarized light Args: m : complex index of refraction [-] theta_i : angle from normal to surface [radians] Returns: reflected fraction of parallel field [-] """ c = m * m * np.cos(theta_i) s = np.sin(theta_i) d = np.sqrt(m * m - s * s, dtype=np.complex) # m*cos(theta_t) if m.imag == 0: d = np.conjugate(d) rp = (c - d) / (c + d) return np.real_if_close(rp)
def K_tensor(self): """numpy.ndarray : The anisotropic energy coefficient tensor""" # ii is imaginary unit ii = np.array([1.j]) # updn is alternating +- updn = np.array([1, -1, 1, -1, 1, -1]) # Compute K_tensor K = ii * np.einsum('s,s,si,sj->ij', updn, self.k, self.L, self.L) # Round away near-zero terms K = np.real_if_close(K, tol=self.__tol) K[np.isclose(K / K.max(), 0.0, atol=self.__tol)] = 0.0 return K
def _generate_signal(self, tlist, w): signal = np.zeros_like(tlist, dtype=np.complex) evals = self.evals # this does e_i - e_j for all eigenvalues ediffs = np.subtract.outer(evals, evals) ediffs *= self.one_over_plank2pi for idx in range(len(evals)): self.logger.info('Adding signal {}...'.format(idx)) for jdx in range(len(evals)): signal += np.exp( 1.j * ediffs[idx, jdx] * tlist) * w[idx, jdx] # 6.582117e-7 =planck2pi [neV*s] return (np.real_if_close(signal / self.Hdim))
def back_substitution(matrix): """Perform back substitution and return solution of system Arguments: matrix -- two-dimensional matrix Attention: given argument must be a upper triangular matrix with ones on main diagonal and have n rows and n + 1 columns (last column is vector b) """ n = matrix.shape[0] x = np.zeros(n, complex) for i in range(n - 1, -1, -1): x[i] = matrix[i, n] - sum(matrix[i, :n] * x) return np.real_if_close(x)
def eig_stats(self, Data): jac = self.Jac(Data) eigs = np.real_if_close(np.linalg.eigvals(jac)) eigs_r = np.real(eigs) eigs_i = np.imag(eigs) eig_min = min(eigs_r) eig_max = max(eigs_r) N_real = sum(np.abs(eigs_i) == 0.) N_imag = len(eigs) - N_real N_neg = sum(eigs_r < 0.) N_zer = sum(eigs_r == 0.) N_pos = len(eigs) - N_neg - N_zer div_trace = sum(eigs_r) return np.array( [eig_min, eig_max, N_real, N_imag, N_neg, N_zer, N_pos, div_trace])
def vector2latex(vector, precision=5, pretext="", display_output=True): out_latex = "\n$$ " + pretext out_latex += "\\begin{bmatrix}\n" for amplitude in vector: amplitude = np.real_if_close(amplitude) amp_mod = np.mod(np.real(amplitude), 1) if (np.isclose(amp_mod, 0) or np.isclose(amp_mod, 1)) and type(amplitude) == np.ndarray: out_latex += str(int(np.round(amplitude))) + " \\\\\n" else: out_latex += '{:.{}f}'.format(amplitude, precision) + " \\\\\n" out_latex = out_latex[:-4] # remove trailing ampersands out_latex += "\end{bmatrix} $$" if display_output: display(Markdown(out_latex)) else: return out_latex
def general_unitary_gate(theta: float, phi: float, gamma: float) -> np.ndarray: """ Returns the matrix corresponding to the most general single qubit unitary: |cos(θ/2) -exp(-iγ) * sin(θ/2)| |exp(iφ) * sin(θ/2) exp(iγ + iφ) * cos(θ/2)|. Args: {theta, phi, gamma} (float): Euler angles for the Bloch sphere. Returns: A np.ndarray encoding the matrix given above. """ a = np.cos(theta / 2) b = -np.exp(-1.0j * gamma) * np.sin(theta / 2) c = np.exp(1.0j * phi) * np.sin(theta / 2) d = np.exp(1.0j * gamma + 1.0j * phi) * np.cos(theta / 2) return np.real_if_close(np.array([[a, b], [c, d]], dtype=np.csingle))
def t_per(m, theta_i): """ Calculates the transmitted amplitude for perpendicular polarized light Args: m : complex index of refraction [-] theta_i : incidence angle from normal [radians] Returns: transmitted fraction of perpendicular field [-] """ c = np.cos(theta_i) s = np.sin(theta_i) d = np.sqrt(m * m - s * s, dtype=np.complex) # m*cos(theta_t) if m.imag == 0: d = np.conjugate(d) ts = 2 * c / (c + d) return np.real_if_close(ts)
def _recast_dressed_eigendata( self, dressed_eigendata: List[Tuple[ndarray, QutipEigenstates]]) -> SpectrumData: evals_count = self.evals_count energy_table = np.empty(shape=(self.param_count, evals_count), dtype=np.float_) state_table = [] # for dressed states, entries are Qobj for j in range(self.param_count): energy_table[j] = np.real_if_close(dressed_eigendata[j][0]) state_table.append(dressed_eigendata[j][1]) specdata = storage.SpectrumData(energy_table, system_params={}, param_name=self.param_name, param_vals=self.param_vals, state_table=state_table) return specdata
def add_op(self, name, op, need_JW=False): """Add one on-site operators. Parameters ---------- name : str A valid python variable name, used to label the operator. The name under which `op` is added as attribute to self. op : np.ndarray | :class:`~tenpy.linalg.np_conserved.Array` A matrix acting on the local hilbert space representing the local operator. Dense numpy arrays are automatically converted to :class:`~tenpy.linalg.np_conserved.Array`. LegCharges have to be ``[leg, leg.conj()]``. We set labels ``'p', 'p*'``. need_JW : bool Whether the operator needs a Jordan-Wigner string. If ``True``, the function adds `name` to :attr:`need_JW_string`. """ name = str(name) if not name.isidentifier(): raise ValueError("Invalid operator name: " + name) if name in self.opnames: raise ValueError("Operator with that name already existent: " + name) if hasattr(self, name): raise ValueError("Site already has that attribute name: " + name) if not isinstance(op, npc.Array): op = np.asarray(op) if op.shape != (self.dim, self.dim): raise ValueError("wrong shape of on-site operator") # try to convert op into npc.Array op = npc.Array.from_ndarray(op, [self.leg, self.leg.conj()]) if op.rank != 2: raise ValueError("only rank-2 on-site operators allowed") op.legs[0].test_equal(self.leg) op.legs[1].test_contractible(self.leg) op.test_sanity() op.iset_leg_labels(['p', 'p*']) setattr(self, name, op) self.opnames.add(name) if need_JW: self.need_JW_string.add(name) if name == 'JW': self.JW_exponent = np.angle( np.real_if_close(np.diag(op.to_ndarray()))) / np.pi
def cov_inv(drmat, dimat, tol=10**(-10)): ''' Computes covariance matrix of invariant measure of linear SDE. ''' from numpy import array, sqrt, newaxis, inf, exp, nditer from numpy import real, imag, complex64, float64, real_if_close from numpy.linalg import eig, inv from scipy.integrate import quad eigv, simat = eig(drmat) inv_simat = inv(simat) bmat = (inv_simat @ dimat @ dimat.T @ inv_simat.T).astype(complex64) vmat = eigv[:, newaxis] + eigv with nditer(bmat, op_flags=['readwrite']) as bit: for b, v in zip(bit, vmat.ravel()): b_re, *rest = quad(lambda t: real(b * exp(t * v)), 0, inf) b_im, *rest = quad(lambda t: imag(b * exp(t * v)), 0, inf) b[...] = b_re + b_im * 1.j return real_if_close(simat @ bmat @ simat.T)
def test_tomo_analysis_cardinal_state(self): #The dataset corresponds to the 00 cardinal state. tomo_object = tomography_execute.TomographyExecute( timestamp='20161124_162604', tomography_type="MLE") # Get the dm for 00 cardinal state # returned rho is a quantum object rho_tomo = (tomo_object.get_density_matrix()).full() # get a rho target corresponding to the 00 state rho_target = (qt.ket2dm(qt.basis(4, 0))).full() #get it's fidelity to a 00 state #This is not the correct fidelity, it's only to benchmark whether #this run of code reproduced this fidelity or not, if it does not, #the code is broken. #The correct method shhould be pauli labels benchmark_fidelity = np.real_if_close( np.dot(rho_tomo.flatten(), rho_target.flatten())) self.assertAlmostEqual(benchmark_fidelity, 0.9679030, places=6)
def Stationary(prob): N = prob.shape[0] from scipy import linalg as LA import numpy as np v, w = LA.eig(prob.T) ind = np.nonzero(np.abs(v - 1.0) < 1e-8)[0] if len(ind) > 0: i = np.min(ind) #== statement is not good sdist = w[:, i] / np.sum(w[:, i]) sdist = np.real_if_close( sdist) #discards the imaginary part if it is negligible return sdist else: print('error: no eigenvalue which is equal to one.')
def zeros(self, use_mp=False): """Return the zeros of the rational function. If ``use_mp`` is ``True``, uses the ``mpmath`` package to compute the result using 100-digit precision arithmetic. If an integer is passed, uses that number of digits to compute the result. """ if use_mp: return _compute_roots(self.weights * self.values, self.nodes, use_mp=use_mp) else: zj, fj, wj = self.nodes, self.values, self.weights B = np.eye(len(wj) + 1) B[0, 0] = 0 E = np.block([[0, wj], [fj[:, None], np.diag(zj)]]) evals = scipy.linalg.eigvals(E, B) return np.real_if_close(evals[np.isfinite(evals)])
def displacement(self, pos): """ Compute the position-dependent anisotropic displacement. The argument pos can either be a single 3D position, or a list/array of 3D positions. """ ii = np.array([1.j]) updn = np.array([1, -1, 1, -1, 1, -1]) eta = self.eta(pos) disp = 1 / (2 * np.pi * ii) * \ np.einsum('a,a,ai,a,na->ni', updn, self.k, self.A, self.L.dot(self.__burgers), np.log(eta)) disp = np.real_if_close(disp, tol=self.__tol) if np.asarray(pos).ndim == 1: return disp[0] else: return disp
def spectral_radius(self): """Compute the spectral radius of the matrix of l1 norm of Hawkes kernels. Notes ----- If the spectral radius is greater that 1, the hawkes process is not stable """ get_norm = np.vectorize(lambda kernel: kernel.get_norm()) norms = get_norm(self.kernels) # It might happens that eig returns a complex number but with a # negligible complex part, in this case we keep only the real part spectral_radius = max(eig(norms)[0]) spectral_radius = np.real_if_close(spectral_radius) return spectral_radius
def sample_bitstrings(self, n_samples): """ Sample bitstrings from the distribution defined by the wavefunction. Qubit 0 is at ``out[:, 0]``. :param n_samples: The number of bitstrings to sample :return: An array of shape (n_samples, n_qubits) """ if self.rs is None: raise ValueError("You have tried to perform a stochastic operation without setting the " "random state of the simulator. Might I suggest using a PyQVM object?") probabilities = np.real_if_close(np.diagonal(self.density)) possible_bitstrings = all_bitstrings(self.n_qubits) inds = self.rs.choice(2 ** self.n_qubits, n_samples, p=probabilities) bitstrings = possible_bitstrings[inds, :] bitstrings = np.flip(bitstrings, axis=1) # qubit ordering: 0 on the left. return bitstrings
def multiplicities(self, groups, p): g = groups[p] multi = np.zeros((g.nclasses, ), dtype=complex) for i in range(g.order): chars = np.asarray([np.trace(ir.mx[i]).conj() for ir in g.irreps]) look = g.lelements[i] tr1 = tr2 = 0. for i1, i2 in self.indices: if i1 != i2: continue tr1 += self.gamma1[look, i1, i1] tr2 += self.gamma2[look, i2, i2] chars *= tr1 * tr2 #chars *= np.trace(self.gamma1[look]) #chars *= np.trace(self.gamma2[look]) multi += chars multi = np.real_if_close(multi / g.order) return multi
def _penalty_matrix(self): S = np.zeros(((self.num_percentiles + 1) * self.n_features + 1, (self.num_percentiles + 1) * self.n_features + 1)) flat_knots = np.asarray([self._knots.get(feat) for feat in self.feature_names]).flatten() penalty_matrix = np.real_if_close(sp.linalg.sqrtm(R.outer(flat_knots, flat_knots).astype(np.float64)), tol=10 ** 8) penalty_matrix = np.insert(penalty_matrix, np.arange(0, self.num_percentiles * self.n_features, self.num_percentiles), 0, axis=1) penalty_matrix = np.insert(penalty_matrix, np.arange(0, self.num_percentiles * self.n_features, self.num_percentiles), 0, axis=0) S[1:, 1:] = penalty_matrix return S
def hamiltonian_to_lindbladian(hamiltonian, sparse=False): """ Construct the Lindbladian corresponding to a given Hamiltonian. Mathematically, for a d-dimensional Hamiltonian matrix H, this routine constructs the d^2-dimension Lindbladian matrix L whose action is given by L(rho) = -1j*2/sqrt(d)*[ H, rho ], where square brackets denote the commutator and rho is a density matrix. L is returned as a superoperator matrix that acts on a vectorized density matrices. Parameters ---------- hamiltonian : ndarray The hamiltonian matrix used to construct the Lindbladian. sparse : bool, optional Whether to construct a sparse or dense (the default) matrix. Returns ------- ndarray or Scipy CSR matrix """ #TODO: there's probably a fast & slick way to so this computation # using vectorization identities assert (len(hamiltonian.shape) == 2) assert (hamiltonian.shape[0] == hamiltonian.shape[1]) d = hamiltonian.shape[0] if sparse: lindbladian = _sps.lil_matrix((d**2, d**2), dtype=hamiltonian.dtype) else: lindbladian = _np.empty((d**2, d**2), dtype=hamiltonian.dtype) for i, rho0 in enumerate(basis_matrices('std', d**2)): # rho0 == input density mx rho1 = _np.sqrt(d) / 2 * ( -1j * (_mt.safedot(hamiltonian, rho0) - _mt.safedot(rho0, hamiltonian))) lindbladian[:, i] = _np.real_if_close( rho1.flatten()[:, None] if sparse else rho1.flatten()) # vectorize rho1 & set as linbladian column if sparse: lindbladian = lindbladian.tocsr() return lindbladian
def right_normalize(self, test=False): """ returns a right_normalized version of the random_MPS() object new version using QR """ #Pseudo Code #get M[L] #reshape M[L] to Psi #SVD of PSI #reshape V^h to B[L], save S[L], multiply M[L-1] U S = Mt[L-1] #repeat procedure Ms = self.Ms L, d, chi = self.L, self.d, self.chi Bs = [] for i in range(L - 1, -1, -1): chi1, d, chi2 = Ms[i].shape # a_i-1, sigma_i, s_i m = Ms[i].reshape(chi1, d * chi2) Q, R = qr( m.conjugate().transpose(), mode='reduced' ) #in numpy.linalg.qr 'reduced' is standard whilst not in scipy version B = Q.conjugate().transpose().reshape(min( m.shape), d, chi2) # s_i-1, sigma_i , s_i Bs.append(B) # problem gefunden, ich speicher ja nirgends B ab # update next M matrix to M-tilde = M U S # in order not to overwrite the first matrix again when hitting i=0 use if i > 0: Ms[i - 1] = np.tensordot( Ms[i - 1], R.conjugate().transpose(), 1) # a_L-2 sigma_L-1 [a_L-1] , [a_L-1] s_L-1 if test: # check if right-normalization is fulfilled, should give identity matrices print( np.real_if_close( np.tensordot(B, B.conjugate(), axes=([2, 1], [ 2, 1 ])))) # s_i-1 [sigma] [a_i], s_i-1 [sigma] [a_i] #return Ms # or update self.Ms = Bs[::-1] self.normstat = 'right-norm'
def time_evolve_qutip(self, dt, steps): """Clear and simple translation into python of textbook description. Never actually used. Parameters ---------- dt : float time step steps : int total number of steps Returns ------- numpy.array Muon polarization function. """ atoms = self.atoms partial_densities = [] for atom in atoms: if atom['Label'] == 'mu': Ox, Oy, Oz = atom['Observables'] rho_mu = 0.5 * (qeye(2) + qdot( [0, 0, 1], [sigmax(), sigmay(), sigmaz()])) partial_densities.append(rho_mu) else: rho_atom = qeye( 2 * atoms[i]['Spin'] + 1 ) # This is exp(-beta H) / Tr ( exp(-beta H ) ) when beta H << 1 partial_densities.append(rho_atom) rhoz = tensor(partial_densities) rhoz = rhoz.unit() dU = (-1j * self.H * one_over_plank2pi_neVs * dt).expm() r = np.zeros(steps, dtype=np.complex) U = qeye(dU.dims) # this is t=0 for i in range(steps): r[i] += (rhoz * U.dag() * Oz * U).tr() U *= dU return np.real_if_close(r)
def entanglement_fidelity(pauli_lio0: np.ndarray, pauli_lio1: np.ndarray, tol: float = 1000) -> float: r""" Returns the entanglement fidelity (F_e) between two channels, E and F, represented as Pauli Liouville matrix. The expression is .. math:: F_e(E,F) = Tr[E^\dagger F] / (dim^2), where dim is the dimension of the Hilbert space associated with E and F. See the following references for more information: [GRAPTN]_ referenced in the superoperator_tools module. In particular section V subsection G. .. [H**3] General teleportation channel, singlet fraction and quasi-distillation. Horodecki et al. PRA 60, 1888 (1999). https://doi.org/10.1103/PhysRevA.60.1888 https://arxiv.org/abs/quant-ph/9807091 .. [GFID] A simple formula for the average gate fidelity of a quantum dynamical operation. M. Nielsen. Physics Letters A 303, 249 (2002). https://doi.org/10.1016/S0375-9601(02)01272-0 https://arxiv.org/abs/quant-ph/0205035 :param pauli_lio0: A dim**2 by dim**2 Pauli-Liouville matrix :param pauli_lio1: A dim**2 by dim**2 Pauli-Liouville matrix :param tol: Tolerance in machine epsilons for np.real_if_close. :return: Returns the entanglement fidelity between pauli_lio0 and pauli_lio1 which is a scalar. """ assert pauli_lio0.shape == pauli_lio1.shape assert pauli_lio0.shape[0] == pauli_lio1.shape[1] dim_squared = pauli_lio0.shape[0] dim = int(np.sqrt(dim_squared)) Fe = np.trace(np.matmul(np.transpose(np.conj(pauli_lio0)), pauli_lio1)) / (dim**2) return np.ndarray.item(np.real_if_close(Fe, tol))
def polres(self): """Return the poles and residues of the rational function.""" zj, fj, wj = self.nodes, self.values, self.weights m = len(wj) # compute poles B = np.eye(m + 1) B[0, 0] = 0 E = np.block([[0, wj], [np.ones((m, 1)), np.diag(zj)]]) evals = scipy.linalg.eigvals(E, B) pol = np.real_if_close(evals[np.isfinite(evals)]) # compute residues via formula for simple poles of quotients of analytic functions C_pol = 1.0 / (pol[:, None] - zj[None, :]) N_pol = C_pol.dot(fj * wj) Ddiff_pol = (-C_pol**2).dot(wj) res = N_pol / Ddiff_pol return pol, res
def updateinternals(self, e, epos, mask=None): """Update any internals given that electron e moved to epos. mask is a Boolean array which allows us to update only certain walkers""" # MAY want to vectorize later if it really hangs here, shouldn't! s = int(e >= self._nelec[0]) if mask is None: mask = [True] * epos.configs.shape[0] eeff = e - s * self._nelec[0] ao = np.real_if_close(self._mol.eval_gto(self.pbc_str + "GTOval_sph", epos.configs), tol=1e4) mo = ao.dot(self.parameters[self._coefflookup[s]]) mo_vals = mo[:, self._det_occup[s]] det_ratio, self._inverse[s][mask, :, :, :] = sherman_morrison_ms( eeff, self._inverse[s][mask, :, :, :], mo_vals[mask, :]) self._updateval(det_ratio, s, mask)
def lowpass_scipy_fft(signal,sample_freq,time_period,keep_mean): lowpass_signal=np.zeros(signal.shape) if any(np.isnan(signal)): raise ValueError('There is NaN in the signal') else: hf = 1./time_period temp_fft = sc.fftpack.fft(signal) fftfreq = np.fft.fftfreq(len(signal),sample_freq) ### daily data it is 1./365 ## monthly data 1./12 ## yearly data=1 i1 = np.abs(fftfreq) >= hf temp_fft[i1] = 0 if not(keep_mean): temp_fft[0]=0 lowpass_signal= np.real_if_close(sc.fftpack.ifft(temp_fft)) return lowpass_signal
def multiplicity_of_SU2(self, j, useinv=True): """Multiplicites of irreps for SU(2) with multiplicity [j] = 2*j+1. Parameter --------- j : int The multiplicity of the angular momentum. useinv : bool Use the inversion flag of the representations. Returns ------- multi : ndarray The multiplicities of the irreps for the SU(2) representation. """ _char = self.characters_of_SU2(j, useinv=useinv) multi = self.tchar.dot(_char * self.cdim) multi = np.real_if_close(np.rint(multi / float(self.order))) return multi
def psf2otf(psf, shape): if np.all(psf == 0): return np.zeros_like(psf) inshape = psf.shape # Pad the PSF to outsize psf = zero_pad(psf, shape, position='corner') for axis, axis_size in enumerate(inshape): psf = np.roll(psf, -int(axis_size / 2), axis=axis) # Compute the OTF otf = np.fft.fft2(psf) n_ops = np.sum(psf.size * np.log2(psf.shape)) otf = np.real_if_close(otf, tol=n_ops) return otf
def impurity(rho: np.ndarray, dim_renorm=False, tol: float = 1000) -> float: """ Calculates the impurity (or linear entropy) :math:`L = 1 - tr[ρ^2]` of a quantum state ρ. As stated above the lower value of the impurity depends on the dimension of ρ's Hilbert space. For some applications this can be undesirable. For this reason we introduce an optional dimensional renormalization flag with the following behavior If the dimensional renormalization flag is FALSE (default) then 0 ≤ L ≤ 1/dim. If the dimensional renormalization flag is TRUE then 0 ≤ L ≤ 1. where dim is the dimension of ρ's Hilbert space. :param rho: Is a dim by dim positive matrix with unit trace. :param dim_renorm: Boolean, default False. :param tol: Tolerance in machine epsilons for np.real_if_close. :return: L the impurity of the state. """ imp = 1 - np.trace(rho @ rho) if dim_renorm: dim = rho.shape[0] imp = (dim / (dim - 1.0)) * imp return np.ndarray.item(np.real_if_close(imp, tol))