コード例 #1
0
    def ComputeJacobianMatrix(self,
                              vec_x,
                              vec_xi=None,
                              rep_loc=None):  #need validation
        """
        Calcul l'inverse du Jacobien aux points de gauss dans le cas d'un élément isoparamétrique (c'est à dire que les mêmes fonctions de forme sont utilisées)
        vec_xi est un tableau dont les lignes donnent les coordonnées dans le repère de référence où on souhaite avoir le jacobien (en général pg)
        """
        if vec_xi is None: vec_xi = self.xi_pg
        self.ComputeDetJacobian(vec_x, vec_xi)

        if rep_loc != None:
            rep_pg = self.interpolateLocalFrame(
                rep_loc,
                vec_xi)  #interpolation du repère local aux points de gauss
            self.JacobianMatrix = sp.matmul(
                self.JacobianMatrix, sp.swapaxes(rep_pg, 2, 3)
            )  #to verify - sp.swapaxes(rep_pg,2,3) is equivalent to a transpose over the axis 2 and 3
#            for k,J in enumerate(self.JacobianMatrix): self.JacobianMatrix[k] = sp.dot(J, rep_pg[k].T)

        if self.JacobianMatrix.shape[-2] == self.JacobianMatrix.shape[-1]:
            self.inverseJacobian = linalg.inv(self.JacobianMatrix)
#            self.inverseJacobian = [linalg.inv(J) for J in self.JacobianMatrix]
        else:  #l'espace réel est dans une dimension plus grande que l'espace de l'élément de référence
            J = self.JacobianMatrix
            JT = sp.swapaxes(self.JacobianMatrix, 2, 3)
            self.inverseJacobian = sp.matmul(
                JT, linalg.inv(sp.matmul(J, JT))
            )  #inverseJacobian.shape = (Nel,len(vec_xi)=nb_pg, dim:vec_x.shape[-1], dim:vec_xi.shape[-1])
コード例 #2
0
def rho_dot(Hamiltonian, Gamma, rho, closed):
    """
    Calculate the time derivative of the density matrix

    This function uses the Lindblad form of the quantum master equation (Steck eq. 5.177 & 5.178 pg 181)

    .. math::
        \\dot{\\rho} = -\\frac{i}{\\hbar} [H, \\rho] + \\Gamma D[c] \\rho

    where

    .. math::
        D[c] \\rho = c\\rho c^{\\dagger} - \\frac{1}{2} \\{c^{\\dagger} c, \\rho\\}.

    :math:`\Gamma` is the decay rate and :math:`c` along with its Hermitian conjugate :math:`c^{\dagger}` are the transition matrices
    of the n level system.
    The documentation also has some extra information.
    For now only radiative decay is considered (no dephasing).
    
    :param Hamiltonian: Complex ndarray. Hamiltonian.
    :param Gamma: Ndarray. Decay matrix.
    :param rho: Complex ndarray. density matrix.
    :return: Complex ndarray. Time derivative of the density matrix.
    """
    return -1j / hbar * commutator(Hamiltonian, rho) \
           - 1 / 2 * anticommutator(Gamma, rho) \
           + sum(sp.matmul(closed[0], sp.matmul(rho, closed[1])))
コード例 #3
0
    def ComputeJacobianMatrix(self, vec_x, vec_xi=None, rep_loc=None):
        if vec_xi is None: vec_xi == self.xi_pg
        self.ComputeDetJacobian(vec_x, vec_xi)

        if self.JacobianMatrix.shape[-2] == self.JacobianMatrix.shape[-1]:
            if rep_loc != None:
                rep_pg = self.interpolateLocalFrame(
                    rep_loc, vec_xi
                )  #interpolation du repère local aux points de gauss  -> shape = (len(vec_x),len(vec_xi),dim,dim)
                self.JacobianMatrix = sp.matmul(
                    self.JacobianMatrix, sp.swapaxes(rep_pg, 2, 3)
                )  #to verify - sp.swapaxes(rep_pg,2,3) is equivalent to a transpose over the axis 2 and 3
#                rep_pg = self.interpolateLocalFrame(rep_loc, vec_xi) #interpolation du repère local aux points de gauss
#                for k,J in enumerate(self.JacobianMatrix): self.JacobianMatrix[k] = sp.dot(J, rep_pg[k].T)
        else:  #l'espace réel est dans une dimension plus grande que l'espace de l'élément de référence
            if rep_loc is None:
                J = self.JacobianMatrix
                JT = sp.swapaxes(self.JacobianMatrix, 2, 3)
                self.inverseJacobian = sp.matmul(
                    JT, linalg.inv(sp.matmul(J, JT))
                )  #inverseJacobian.shape = (Nel,len(vec_xi)=nb_pg, dim:vec_x.shape[-1], dim:vec_xi.shape[-1])
                #                self.inverseJacobian = [sp.dot(J.T , linalg.inv(sp.dot(J,J.T))) for J in self.JacobianMatrix]   #this line may have a high computational cost
                return
            else:
                rep_pg = self.repLocFromJac(rep_loc, vec_xi)[:, 0:2, :]
                for k, J in enumerate(self.JacobianMatrix):
                    self.JacobianMatrix[k] = sp.dot(J, rep_pg[k].T)
        self.inverseJacobian = linalg.inv(self.JacobianMatrix)
コード例 #4
0
        def F1(params, flag=False):
            if m0:
                _m, _w = m0, params[0]
            elif w0:
                _m, _w = params[0], w0
            else:
                _m, _w = params

            tmp = np.power(np.abs(tc - t), _m)

            X = [
                np.ones(N), tmp, tmp * np.cos(_w * np.log(np.abs(tc - t))),
                tmp * np.sin(_w * np.log(np.abs(tc - t)))
            ]

            X = np.vstack(X).T
            try:
                beta = sp.matmul(sp.linalg.inv(sp.matmul(X.T, X)),
                                 sp.matmul(X.T, y))
            except:
                # print(_m, _w)
                raise ValueError("X is singular")

            SSE = np.sum(np.power(y - np.matmul(beta, X.T), 2))
            if flag:
                return SSE, beta
            return SSE
コード例 #5
0
ファイル: kalman.py プロジェクト: zxzion/software
 def predict(self):
     """
     The predict step in Kalman filtering.
     :return:
     """
     # Predict the state and covariance
     self.x = matmul(self.A, self.x) + matmul(self.B, self.u)
     self.P = matmul(matmul(self.A, self.P), self.A.T) + self.Q
コード例 #6
0
def least_squares_interpolant(x, y):
    xmat = sp.zeros((len(x), 2))
    for i in range(len(x)):
        for j in range(2):
            xmat[i][j] = x[i] ** j
    a = sp.matmul(sp.transpose(xmat), xmat)
    b = sp.matmul(sp.transpose(xmat), y)
    ans = numpy.linalg.solve(a, b)
    return ans, xmat
コード例 #7
0
 def update_reservoir(self, u, n, Y):
     # u is input at specific time
     #   u has shape (N_u (3 for L63))
     # See page 16 eqtn 18 of Lukosevicius PracticalESN for feedback info.
     x_n_tilde = cp.tanh(
         cp.matmul(self.W, self.x[n]) +
         cp.array(sp.matmul(self.W_in, sp.hstack((sp.array([1]), u)))) +
         cp.array(sp.matmul(self.W_fb, Y)))
     self.x[n+1] = cp.multiply((1-cp.array(self.alpha_matrix)), cp.array(self.x[n])) \
           + cp.multiply(cp.array(self.alpha_matrix), x_n_tilde)
コード例 #8
0
 def update_reservoir(self, u, n, Y):
     # u is input at specific time
     #   u has shape (N_u (3 for L63))
     # See page 16 eqtn 18 of Lukosevicius PracticalESN for feedback info.
     x_n_tilde = sp.tanh(
         sp.matmul(self.W, self.x[n]) +
         sp.matmul(self.W_in, sp.hstack((sp.array([1]), u))) +
         sp.matmul(self.W_fb, Y))  # TODO: Add derivative term?
     self.x[n+1] = sp.multiply((1-self.alpha_matrix), self.x[n]) \
           + sp.multiply(self.alpha_matrix, x_n_tilde)
コード例 #9
0
def chi_formal(Ham, psi_i, psi_0, t):
    extract = Matrix_diag(Ham(t))

    H_d = extract[0]
    M = extract[1]
    M_dag = extract[2]
    exponential = sp.zeros([len(H_d), len(H_d)], dtype=complex)
    for i in range(len(H_d)):
        exponential[i][i] = sp.exp(-1j * t * H_d[i][i])

    psi_i_bra = sp.matrix.conjugate(sp.transpose(psi_i))
    psi_t = sp.matmul(M, sp.matmul(exponential, sp.matmul(M_dag, psi_0)))

    chi_rooted = sp.matmul(psi_i_bra, psi_t)

    return abs(chi_rooted)**2
コード例 #10
0
 def cart2frac(self):
   """Convert Cartesian coordinates to fractional"""
   if self.cart:
     lat_inv = inv(self.lat)
     for i in range(self.nat):
       self.r[i,:] = sp.matmul(lat_inv, self.r[i,:])
     self.cart = False
コード例 #11
0
 def output_Y(self, u, n):
     one_by_one = sp.array([1])
     # Eqtn 4
     concatinated_matrix = sp.hstack((sp.hstack(
         (one_by_one, u)), cp.asnumpy(self.x[n])))
     output_Y_return = sp.matmul(self.W_out, concatinated_matrix)
     return output_Y_return
コード例 #12
0
def WikiCG(A, b, *, e=1e-8, iter_max=100):
    x = sp.zeros(b.shape, dtype=float)
    r = b - sp.matmul(A, x)
    p = sp.copy(r)
    rr = sp.dot(r, r)
    for _ in range(iter_max):
        Ap = sp.matmul(A, p)
        alpha = rr / sp.matmul(p, Ap)
        x += alpha * p
        r -= alpha * Ap
        if linalg.norm(r) < e:
            break
        beta = rr
        rr = sp.dot(r, r)
        beta = rr / beta
        p = r + beta * p
    return x
コード例 #13
0
def fun(t, z):
    i = 1
    Fr = sp.zeros(40)
    while i < 20:
        Fr[i +
           20] = -(CAP[i]) * invM[i, i] * sp.tanh((z[20 + i]) - z[20 + i - 1])
        i += 1

    return sp.matmul(A, z) + Fr
コード例 #14
0
 def calculate_W_out(self, Y_target, N_x, beta, train_start_timestep,
                     train_end_timestep):
     # see Lukosevicius Practical ESN eqtn 11
     # Using ridge regression
     N_u = sp.shape(Y_target)[0]
     X = sp.vstack(
         (sp.ones((1, train_end_timestep - train_start_timestep)),
          Y_target[:, train_start_timestep:train_end_timestep],
          self.x[train_start_timestep:train_end_timestep].transpose()))
     # Ridge Regression
     W_out = sp.matmul(
         sp.array(Y_target[:, train_start_timestep + 1:train_end_timestep +
                           1]),
         sp.matmul(
             X.transpose(),
             sp.linalg.inv(
                 sp.matmul(X, X.transpose()) +
                 beta * sp.identity(1 + N_x + N_u))))
     self.W_out = W_out
コード例 #15
0
ファイル: kalman.py プロジェクト: zxzion/software
    def update(self, z):
        """
        The update step in Kalman filtering.
        :param z: The measurements.
        :return:
        """
        # Calculate the Kalman gain
        S = matmul(matmul(self.H, self.P), self.H.T) + self.R
        K = matmul(matmul(self.P, self.H.T), inv(S))

        # Correction based on the measurement
        residual = z - matmul(self.H, self.x)
        self.x = self.x + matmul(K, residual)
        self.P = self.P - matmul(matmul(K, self.H), self.P)

        self.state.append(self.x)
        self.residual.append(norm(residual))
        self.epsilon.append(matmul(residual.T, matmul(inv(S), residual)))
        self.sigma.append(sqrt(S[0, 0]**2 + S[1, 1]**2 + S[2, 2]**2))
        self.process_noise.append(self.Q[0, 0])
コード例 #16
0
def fun(t,z):
    # --- Reporte de paso de tiempo
    if t > fun.tnextreport:
        print "  {} at t = {}".format(fun.solver, fun.tnextreport)
        fun.tnextreport += 1
    # --- Cálculo
    Famort = sp.zeros((40))   # vector de fuerza friccional de amortiguamiento
    Famort[0] = -(Cap[0] * (1./M[0,0]) * sp.tanh((z[20]/vr)))    
    Ft=sp.zeros(40)
    if t<226.81:
        Ft[20:]=f0(t)*9.8
    return sp.matmul(A,z) + Famort + Ft
コード例 #17
0
def BookCG(A, b, e=1e-8, k_max=100):
    k = 0
    d_old = 0
    x = sp.zeros((A.shape[0]))
    r = b - sp.matmul(A, x)
    d = sp.dot(r, r)
    while sp.sqrt(d) > e * sp.sqrt(sp.dot(b, b)) and k < k_max:
        k = k + 1
        if k == 1:
            p = r
        else:
            beta = d / d_old
            p = r + beta * p
        w = sp.matmul(A, p)
        a = d / sp.dot(p, w)
        x = x + a * p
        r = r - a * w
        d_old = d
        d = sp.dot(r, r)

    return x
コード例 #18
0
def rho_dot(Hamiltonian, Gamma, rho, closed):
    """
    Calculate the time derivative of the density matrix using the quantum master equation (Steck eq. 5.177 & 5.178 pg 181)
        rho_dot = -i / hbar * [H, rho] + Gamma * D[c] * rho
    where
        D[c] * rho = 1 / 2 * {c_dagger * c, rho}.
    Gamma is the decay rate and c are the transition matrices of the n level system. In practice c will be a sum of 
    multiple transition matrices.
    
    NOTE: 1.) For now only radiative decay is considered (no dephasing) and all levels have the same decay rate.
          2.) The Lindblad operator does not include the term that adds population back in.  Therefore this function 
              simulates open quantum systems
    
    :param Hamiltonian: Hamiltonian.
    :param Gamma: Decay matrix.
    :param rho: density matrix.
    :return: Time derivative of the density matrix as a 2-D ndarray (dtype=complex).
    """
    return -1j / hbar * commutator(Hamiltonian, rho) \
           - 1 / 2 * anticommutator(Gamma, rho) \
           + sum(sp.matmul(closed[0], sp.matmul(rho, closed[1])))
コード例 #19
0
def main(n = 3):
    A = [[20*random() for j in range(n)] for i in range(n)]
    b = [20*random() for i in range(n)]

    L, U = descompLU(A, b)

    printMatrix(A, 'A')
    print()
    printMatrix(L, 'L')
    print()
    printMatrix(U, 'U')
    print()
    printMatrix(matmul(L, U), 'LU')
コード例 #20
0
ファイル: make_survey.py プロジェクト: adematti/pymakesurvey
def rotation_matrix_from_vectors(a, b):

    a = scipy.asarray(a)
    b = scipy.asarray(b)
    a /= scipy.linalg.norm(a)
    b /= scipy.linalg.norm(b)
    v = scipy.cross(a, b)
    c = scipy.dot(a, b)
    s = scipy.linalg.norm(v)
    I = scipy.identity(3, dtype='f8')
    k = scipy.array([[0., -v[2], v[1]], [v[2], 0., -v[0]], [-v[1], v[0], 0.]])
    if s == 0.: return I
    return I + k + scipy.matmul(k, k) * ((1. - c) / (s**2))
コード例 #21
0
def reflect_by_householder(v, u, c):
    print("Reflect by Householder:")
    print("chord:", v)
    print("Unit normal vector:", u)
    center_ = center(len(v))
    tensor_ = scipy.outer(u, u)
    print("tensor_:\n", tensor_)
    product_ = scipy.multiply(tensor_, 2)
    print("product_:", product_)
    identity_ = scipy.eye(len(v))
    print("identity_:\n", identity_)
    householder = scipy.subtract(identity_, product_)
    print("householder:\n", householder)
    reflected_voices = scipy.matmul(householder, v)
    print("reflected_voices:", reflected_voices)
    translated_voices = scipy.subtract(v, center_)
    print("moved to origin:", translated_voices)
    reflected_translated_voices = scipy.matmul(householder, translated_voices)
    print("reflected_translated_voices:", reflected_translated_voices)
    reflection = scipy.add(reflected_translated_voices, center_)
    print("moved from origin:", reflection)
    print("reflection by householder:", reflection)
    return reflection
コード例 #22
0
def oht_alg(d2d_to_d2d_gains_diag, uav_to_d2d_gains, d2d_to_d2d_gains_diff, eta, power_UAV, power_cir_UAV):
    theta_ini = Parameter(value=1 / 0.5)
    iter = 0
    epsilon = 1
    theta_sol = 0
    iter_phi = []
    while epsilon >= 1e-2 and iter <= 20:
        iter += 1
        if iter == 1:
            theta_ref = theta_ini.value
        else:
            theta_ref = theta_sol

        term_x = sp.divide(1,
                           sp.multiply(sp.subtract(theta_ref, 1), sp.matmul(d2d_to_d2d_gains_diag, uav_to_d2d_gains)))
        term_y = sp.add(
            sp.multiply(sp.subtract(theta_ref, 1), sp.matmul(sp.transpose(d2d_to_d2d_gains_diff), uav_to_d2d_gains)),
            sp.divide(1, eta * power_UAV))

        a_1 = sp.add(sp.divide(sp.multiply(2, sp.log(sp.add(1, sp.divide(1, sp.multiply(term_x, term_y))))), theta_ref),
                     sp.divide(2, sp.multiply(theta_ref, sp.add(sp.multiply(term_x, term_y), 1))))
        b_1 = sp.divide(1, sp.multiply(theta_ref, sp.multiply(term_x, sp.add(sp.multiply(term_x, term_y), 1))))
        c_1 = sp.divide(1, sp.multiply(theta_ref, sp.multiply(term_y, sp.add(sp.multiply(term_x, term_y), 1))))
        d_1 = sp.divide(sp.log(sp.add(1, sp.divide(1, sp.multiply(term_x, term_y)))), sp.square(theta_ref))

        theta = NonNegative(1)
        t_max = NonNegative(1)
        obj_opt = Maximize(t_max)

        constraints = [theta >= 1]
        constraints.append(
            t_max <= a_1 - sp.divide(b_1, sp.matmul(d2d_to_d2d_gains_diag, uav_to_d2d_gains)) * inv_pos(theta - 1)
            - mul_elemwise(c_1,
                           sp.matmul(sp.transpose(d2d_to_d2d_gains_diff), uav_to_d2d_gains) * (theta - 1)
                           + sp.divide(1, eta * power_UAV))
            - d_1 * theta)

        t1 = time.time()

        prob = Problem(obj_opt, constraints)
        prob.solve(solver=ECOS_BB)
        theta_sol = theta.value
        phi_n_sol = sp.multiply((theta_sol - 1) * eta * power_UAV, uav_to_d2d_gains)
        x_rate = sp.matmul(d2d_to_d2d_gains_diag, phi_n_sol)
        term_rate = sp.matmul(sp.transpose(d2d_to_d2d_gains_diff), phi_n_sol) + 1
        rate_sol_ue = sp.divide(sp.log(sp.add(1, sp.divide(x_rate, term_rate))), theta_sol)
        iter_maximin_rate = min(rate_sol_ue)
        term_pow_iter = sp.subtract(1, sp.divide(1, theta_sol)) * eta * power_UAV * sp.add(1, sp.sum(
            uav_to_d2d_gains)) + power_cir_UAV
        iter_phi.append(t_max.value)
        if iter >= 2:
            epsilon = sp.divide(sp.absolute(sp.subtract(iter_phi[iter - 1], iter_phi[iter - 2])),
                                sp.absolute(iter_phi[iter - 2]))
        iter_EE = sp.divide(sp.multiply(1e3, sp.divide(sp.sum(rate_sol_ue), term_pow_iter)), sp.log(2))

    return iter_EE, theta_sol, iter_maximin_rate
コード例 #23
0
def RK4(t_tot, N, Ham, psi):
    dt = t_tot / N  #N is number of steps
    t = sp.linspace(0, t_tot, N + 1)
    y = [psi]
    for i in range(len(t) - 1):
        k1 = dt * TDSE_T(Ham, t[i], y[len(y) - 1])
        k2 = dt * TDSE_T(Ham, t[i] + 0.5 * dt, y[len(y) - 1] + k1 / 2)
        k3 = dt * TDSE_T(Ham, t[i] + 0.5 * dt, y[len(y) - 1] + k2 / 2)
        k4 = dt * TDSE_T(Ham, t[i] + dt, y[len(y) - 1] + k3)
        ynew = y[len(y) - 1] + (k1 + 2 * k2 + 2 * k3 + k4) / 6
        y.append(ynew)
    chi = []
    for i in range(len(y)):
        inneri = sp.matmul(sp.conjugate(psi), y[i])
        inner = abs(inneri)**2
        chi.append(inner)
    return t, chi
コード例 #24
0
    def _operator(self, op):
        """
        This is the function that acts an operator on the full hierarchy.

        PARAMETERS
        ----------
        1. op : an operator

        RETURNS
        -------
        None
        """
        phi_mat = np.transpose(
            np.reshape(self.phi,
                       [int(len(self.phi) / self.n_state), self.n_state],
                       order="C"))
        self.storage.phi = np.reshape(np.transpose(sp.matmul(op, phi_mat)),
                                      len(self.phi))
コード例 #25
0
def fun(t, z):
    #---- Esto sirve solo para reportar en que tiempo vamos
    if t > fun.tnextreport:
        print "  {} at t = {}".format(fun.solver, fun.tnextreport)
        fun.tnextreport += 1

    if fun.solver != "Euler":
        z = np.squeeze(z)
    Famort = sp.zeros(40)  #vector de fuerza friccional de amortiguamiento
    Famort[0] = -(CAP[0] * (1. / M[0, 0]) * sp.tanh((z[20] / vr)))

    for i in range(1, 20):
        Famort[i] = -(1. / M[i, i]) * CAP[i] * sp.tanh(
            (z[i + 20] - z[i - 1 + 20]) / vr)

    Ft = sp.zeros(40)
    if t < 226.81:
        Ft[20:] = inte(t) * 9.8

    return sp.matmul(A, z) + Famort + Ft
コード例 #26
0
    def write_spectrum(self,
                       row,
                       col,
                       states,
                       meas,
                       geom,
                       flush_immediately=False):
        """Write data from a single inversion to all output buffers."""

        self.writes = self.writes + 1

        if len(states) == 0:

            # Write a bad data flag
            atm_bad = s.zeros(len(self.fm.statevec)) * -9999.0
            state_bad = s.zeros(len(self.fm.statevec)) * -9999.0
            data_bad = s.zeros(self.fm.instrument.n_chan) * -9999.0
            to_write = {
                'estimated_state_file': state_bad,
                'estimated_reflectance_file': data_bad,
                'estimated_emission_file': data_bad,
                'modeled_radiance_file': data_bad,
                'apparent_reflectance_file': data_bad,
                'path_radiance_file': data_bad,
                'simulated_measurement_file': data_bad,
                'algebraic_inverse_file': data_bad,
                'atmospheric_coefficients_file': atm_bad,
                'radiometry_correction_file': data_bad,
                'spectral_calibration_file': data_bad,
                'posterior_uncertainty_file': state_bad
            }

        else:

            # The inversion returns a list of states, which are
            # intepreted either as samples from the posterior (MCMC case)
            # or as a gradient descent trajectory (standard case). For
            # gradient descent the last spectrum is the converged solution.
            if self.iv.method == 'MCMC':
                state_est = states.mean(axis=0)
            else:
                state_est = states[-1, :]

            # Spectral calibration
            wl, fwhm = self.fm.calibration(state_est)
            cal = s.column_stack(
                [s.arange(0, len(wl)), wl / 1000.0, fwhm / 1000.0])

            # If there is no actual measurement, we use the simulated version
            # in subsequent calculations.  Naturally in these cases we're
            # mostly just interested in the simulation result.
            if meas is None:
                meas = self.fm.calc_rdn(state_est, geom)

            # Rodgers diagnostics
            lamb_est, meas_est, path_est, S_hat, K, G = \
                self.iv.forward_uncertainty(state_est, meas, geom)

            # Simulation with noise
            meas_sim = self.fm.instrument.simulate_measurement(meas_est, geom)

            # Algebraic inverse and atmospheric optical coefficients
            x_surface, x_RT, x_instrument = self.fm.unpack(state_est)
            rfl_alg_opt, Ls, coeffs = invert_algebraic(
                self.fm.surface, self.fm.RT, self.fm.instrument, x_surface,
                x_RT, x_instrument, meas, geom)
            rhoatm, sphalb, transm, solar_irr, coszen, transup = coeffs

            L_atm = self.fm.RT.get_L_atm(x_RT, geom)
            L_down_transmitted = self.fm.RT.get_L_down_transmitted(x_RT, geom)
            L_up = self.fm.RT.get_L_up(x_RT, geom)

            atm = s.column_stack(
                list(coeffs[:4]) + [s.ones((len(wl), 1)) * coszen])

            # Upward emission & glint and apparent reflectance
            Ls_est = self.fm.calc_Ls(state_est, geom)
            apparent_rfl_est = lamb_est + Ls_est

            # Radiometric calibration
            factors = s.ones(len(wl))
            if 'radiometry_correction_file' in self.outfiles:
                if 'reference_reflectance_file' in self.infiles:
                    reference_file = self.infiles['reference_reflectance_file']
                    self.rfl_ref = reference_file.read_spectrum(row, col)
                    self.wl_ref = reference_file.wl
                    w, fw = self.fm.instrument.calibration(x_instrument)
                    resamp = resample_spectrum(self.rfl_ref,
                                               self.wl_ref,
                                               w,
                                               fw,
                                               fill=True)
                    meas_est = self.fm.calc_meas(state_est, geom, rfl=resamp)
                    factors = meas_est / meas
                else:
                    logging.warning('No reflectance reference')

            # Assemble all output products
            to_write = {
                'estimated_state_file':
                state_est,
                'estimated_reflectance_file':
                s.column_stack((self.fm.surface.wl, lamb_est)),
                'estimated_emission_file':
                s.column_stack((self.fm.surface.wl, Ls_est)),
                'estimated_reflectance_file':
                s.column_stack((self.fm.surface.wl, lamb_est)),
                'modeled_radiance_file':
                s.column_stack((wl, meas_est)),
                'apparent_reflectance_file':
                s.column_stack((self.fm.surface.wl, apparent_rfl_est)),
                'path_radiance_file':
                s.column_stack((wl, path_est)),
                'simulated_measurement_file':
                s.column_stack((wl, meas_sim)),
                'algebraic_inverse_file':
                s.column_stack((self.fm.surface.wl, rfl_alg_opt)),
                'atmospheric_coefficients_file':
                atm,
                'radiometry_correction_file':
                factors,
                'spectral_calibration_file':
                cal,
                'posterior_uncertainty_file':
                s.sqrt(s.diag(S_hat))
            }

        for product in self.outfiles:
            logging.debug('IO: Writing ' + product)
            self.outfiles[product].write_spectrum(row, col, to_write[product])
            if (self.writes % flush_rate) == 0 or flush_immediately:
                self.outfiles[product].flush_buffers()

        # Special case! samples file is matlab format.
        if 'mcmc_samples_file' in self.output:
            logging.debug('IO: Writing mcmc_samples_file')
            mdict = {'samples': states}
            s.io.savemat(self.output['mcmc_samples_file'], mdict)

        # Special case! Data dump file is matlab format.
        if 'data_dump_file' in self.output:

            logging.debug('IO: Writing data_dump_file')
            x = state_est
            xall = states
            Seps_inv, Seps_inv_sqrt = self.iv.calc_Seps(x, meas, geom)
            meas_est_window = meas_est[self.iv.winidx]
            meas_window = meas[self.iv.winidx]
            xa, Sa, Sa_inv, Sa_inv_sqrt = self.iv.calc_prior(x, geom)
            prior_resid = (x - xa).dot(Sa_inv_sqrt)
            rdn_est = self.fm.calc_rdn(x, geom)
            rdn_est_all = s.array(
                [self.fm.calc_rdn(xtemp, geom) for xtemp in states])

            x_surface, x_RT, x_instrument = self.fm.unpack(x)
            Kb = self.fm.Kb(x, geom)
            xinit = invert_simple(self.fm, meas, geom)
            Sy = self.fm.instrument.Sy(meas, geom)
            cost_jac_prior = s.diagflat(x - xa).dot(Sa_inv_sqrt)
            cost_jac_meas = Seps_inv_sqrt.dot(K[self.iv.winidx, :])
            meas_Cov = self.fm.Seps(x, meas, geom)
            lamb_est, meas_est, path_est, S_hat, K, G = \
                self.iv.forward_uncertainty(state_est, meas, geom)
            A = s.matmul(K, G)

            # Form the MATLAB dictionary object and write to file
            mdict = {
                'K': K,
                'G': G,
                'S_hat': S_hat,
                'prior_mu': xa,
                'Ls': Ls,
                'prior_Cov': Sa,
                'meas': meas,
                'rdn_est': rdn_est,
                'rdn_est_all': rdn_est_all,
                'x': x,
                'xall': xall,
                'x_surface': x_surface,
                'x_RT': x_RT,
                'x_instrument': x_instrument,
                'meas_Cov': meas_Cov,
                'wl': wl,
                'fwhm': fwhm,
                'lamb_est': lamb_est,
                'coszen': coszen,
                'cost_jac_prior': cost_jac_prior,
                'Kb': Kb,
                'A': A,
                'cost_jac_meas': cost_jac_meas,
                'winidx': self.iv.winidx,
                'windows': self.iv.windows,
                'prior_resid': prior_resid,
                'noise_Cov': Sy,
                'xinit': xinit,
                'rhoatm': rhoatm,
                'sphalb': sphalb,
                'transm': transm,
                'transup': transup,
                'solar_irr': solar_irr,
                'L_atm': L_atm,
                'L_down_transmitted': L_down_transmitted,
                'L_up': L_up
            }
            s.io.savemat(self.output['data_dump_file'], mdict)

        # Write plots, if needed
        if len(states) > 0 and 'plot_directory' in self.output:

            if 'reference_reflectance_file' in self.infiles:
                reference_file = self.infiles['reference_reflectance_file']
                self.rfl_ref = reference_file.read_spectrum(row, col)
                self.wl_ref = reference_file.wl

            for i, x in enumerate(states):

                # Calculate intermediate solutions
                lamb_est, meas_est, path_est, S_hat, K, G = \
                    self.iv.forward_uncertainty(state_est, meas, geom)

                plt.cla()
                red = [0.7, 0.2, 0.2]
                wl, fwhm = self.fm.calibration(x)
                xmin, xmax = min(wl), max(wl)
                fig = plt.subplots(1, 2, figsize=(10, 5))
                plt.subplot(1, 2, 1)
                meas_est = self.fm.calc_meas(x, geom)
                for lo, hi in self.iv.windows:
                    idx = s.where(s.logical_and(wl > lo, wl < hi))[0]
                    p1 = plt.plot(wl[idx], meas[idx], color=red, linewidth=2)
                    p2 = plt.plot(wl, meas_est, color='k', linewidth=1)
                plt.title("Radiance")
                plt.title("Measurement (Scaled DN)")
                ymax = max(meas) * 1.25
                ymax = max(meas) + 0.01
                ymin = min(meas) - 0.01
                plt.text(500, ymax * 0.92, "Measured", color=red)
                plt.text(500, ymax * 0.86, "Model", color='k')
                plt.ylabel(r"$\mu$W nm$^{-1}$ sr$^{-1}$ cm$^{-2}$")
                plt.ylabel("Intensity")
                plt.xlabel("Wavelength (nm)")
                plt.ylim([-0.001, ymax])
                plt.ylim([ymin, ymax])
                plt.xlim([xmin, xmax])

                plt.subplot(1, 2, 2)
                lamb_est = self.fm.calc_lamb(x, geom)
                ymax = min(max(lamb_est) * 1.25, 0.10)
                for lo, hi in self.iv.windows:

                    # black line
                    idx = s.where(s.logical_and(wl > lo, wl < hi))[0]
                    p2 = plt.plot(wl[idx], lamb_est[idx], 'k', linewidth=2)
                    ymax = max(max(lamb_est[idx] * 1.2), ymax)

                    # red line
                    if 'reference_reflectance_file' in self.infiles:
                        idx = s.where(
                            s.logical_and(self.wl_ref > lo,
                                          self.wl_ref < hi))[0]
                        p1 = plt.plot(self.wl_ref[idx],
                                      self.rfl_ref[idx],
                                      color=red,
                                      linewidth=2)
                        ymax = max(max(self.rfl_ref[idx] * 1.2), ymax)

                    # green and blue lines - surface components
                    if hasattr(self.fm.surface, 'components') and \
                            self.output['plot_surface_components']:
                        idx = s.where(
                            s.logical_and(self.fm.surface.wl > lo,
                                          self.fm.surface.wl < hi))[0]
                        p3 = plt.plot(self.fm.surface.wl[idx],
                                      self.fm.xa(x, geom)[idx],
                                      'b',
                                      linewidth=2)
                        for j in range(len(self.fm.surface.components)):
                            z = self.fm.surface.norm(
                                lamb_est[self.fm.surface.idx_ref])
                            mu = self.fm.surface.components[j][0] * z
                            plt.plot(self.fm.surface.wl[idx],
                                     mu[idx],
                                     'g:',
                                     linewidth=1)
                plt.text(500, ymax * 0.86, "Remote estimate", color='k')
                if 'reference_reflectance_file' in self.infiles:
                    plt.text(500, ymax * 0.92, "In situ reference", color=red)
                if hasattr(self.fm.surface, 'components') and \
                        self.output['plot_surface_components']:
                    plt.text(500, ymax * 0.80, "Prior mean state ", color='b')
                    plt.text(500,
                             ymax * 0.74,
                             "Surface components ",
                             color='g')
                plt.ylim([-0.0010, ymax])
                plt.xlim([xmin, xmax])
                plt.title("Reflectance")
                plt.title("Source Model")
                plt.xlabel("Wavelength (nm)")
                fn = self.output['plot_directory'] + ('/frame_%i.png' % i)
                plt.savefig(fn)
                plt.close()
コード例 #27
0
def Matrix_diag(H):
    w1, v1 = sp.linalg.eig(H)
    M_dag = sp.matrix.conjugate(sp.transpose(v1))
    M = v1  ## conjugate(transpose(M))
    H_diag = sp.matmul(sp.matmul(M_dag, H), M)
    return H_diag, M, M_dag, w1
コード例 #28
0
            d2d_to_d2d_gains = max_d2d_to_d2d_gains[:num_d2d_pairs, :
                                                    num_d2d_pairs, Mon]
            d2d_to_d2d_gains_diff = max_d2d_to_d2d_gains_diff[:num_d2d_pairs, :
                                                              num_d2d_pairs]
            d2d_to_d2d_gains_diag = sp.subtract(d2d_to_d2d_gains,
                                                d2d_to_d2d_gains_diff)

            # ############################################################
            # This code is used to find the initial point for EEmax algorithm
            # ############################################################

            theta_ini = Parameter(value=1 / (1 - 0.5))
            phi_n_ini = sp.multiply((theta_ini.value - 1) * eta *
                                    sp.divide(power_UAV, num_d2d_pairs),
                                    uav_to_d2d_gains)
            x_rate = sp.matmul(d2d_to_d2d_gains_diag, phi_n_ini)
            term_rate = sp.matmul(sp.transpose(d2d_to_d2d_gains_diff),
                                  phi_n_ini) + 1
            rate_sol_ue = sp.divide(
                sp.log(sp.add(1, sp.divide(x_rate, term_rate))),
                theta_ini.value)
            # print rate_sol_ue
            rmin_ref = min(rate_sol_ue)
            if rmin_ref <= 0.2 * sp.log(2):
                rmin = rmin_ref
            else:
                rmin = 0.2 * sp.log(2)

            pow_ = NonNegative(num_d2d_pairs)
            objective = Minimize(sum_entries(pow_) / theta_ini)
コード例 #29
0
def cavity(k, n_f, w_c):
    return w_c * sp.kron(sp.identity(k),
                         (sp.matmul(alphadag(n_f), alpha(n_f))))
コード例 #30
0
def TDSE_T(Hami, t, psi):
    diff = -1j * sp.matmul(Hami(t), psi)
    return diff