Ejemplo n.º 1
0
def kimura_1957_54_denominator_analytic(c, d):
    """
    See the corresponding description for the numerator.
    This function computes the normalizing constant.
    """
    # Mathematica notation:
    # Integrate[Exp[-2*c*d*x*(1-x) - 2*c*x], {x, 0, 1}]
    #
    # precompute some intermediate quantities
    # FIXME: algopy has no csqrt but then again also does not support complex.
    #sqrt_c = cmath.sqrt(c)
    #sqrt_d = cmath.sqrt(d)
    sqrt_c = algopy.sqrt(c)
    sqrt_d = algopy.sqrt(d)
    sqrt_2 = math.sqrt(2)
    exp_2c = algopy.exp(2 * c)
    #
    # compute the numerator
    dawsn_num_a = algopy.special.dawsn((sqrt_c * (d - 1)) / (sqrt_2 * sqrt_d))
    dawsn_num_b = algopy.special.dawsn((sqrt_c * (d + 1)) / (sqrt_2 * sqrt_d))
    num = dawsn_num_a + exp_2c * dawsn_num_b
    #
    # compute the denominator
    den = sqrt_2 * sqrt_c * sqrt_d * exp_2c
    #
    return num / den
Ejemplo n.º 2
0
def kimura_1957_54_numerator_analytic(p, c, d):
    """
    From Kimura 1957, equation (5.4).
    This is the diffusion approximation of the fixation probability
    of an allele that has reached frequency p in the population,
    with scaled selection c = Ns
    and dominance/recessivity parameter d = 2h - 1.
    @param p: initial allele frequency in the population
    @param c: population-scaled selection coefficient
    @param d: transformed dominance/recessivity parameter
    @return: diffusion estimate of fixation probability
    """
    # Mathematica notation:
    # Integrate[Exp[-2*c*d*x*(1-x) - 2*c*x], {x, 0, p}]
    #
    # precompute some intermediate quantities
    sqrt_c = algopy.sqrt(c)
    sqrt_d = algopy.sqrt(d)
    sqrt_2 = math.sqrt(2)
    sqrt_pi = math.sqrt(math.pi)
    #
    # compute the numerator
    erfi_num_a = algopy.special.erfi((sqrt_c * (1 + d)) / (sqrt_2 * sqrt_d))
    erfi_num_b = algopy.special.erfi(
        (sqrt_c * (1 + d - 2 * d * p)) / (sqrt_2 * sqrt_d))
    num = (sqrt_pi / sqrt_2) * (erfi_num_a + erfi_num_b)
    #
    # compute the denominator
    exp_den_a = algopy.exp((c * ((1 + d)**2)) / (2 * d))
    den = 2 * algopy.sqrt(c) * algopy.sqrt(d) * exp_den_a
    #
    return num / den
Ejemplo n.º 3
0
def get_h_i_t(w_i, alpha_i, beta_i, b_i, c_i, mu_i, v_i, h_tm1_agg_i, delta_t_agg_i):
    if mu_i > 0:
        sqrthtpowmu = algopy.sqrt(h_tm1_agg_i) ** mu_i
        return (w_i + alpha_i * sqrthtpowmu * get_f_i(delta_t_agg_i, b_i, c_i) ** v_i + beta_i * sqrthtpowmu) ** (2./mu_i)
    else:
        sqrtht = algopy.sqrt(h_tm1_agg_i)
        return (algopy.exp(w_i + alpha_i * get_f_i(delta_t_agg_i, b_i, c_i)  ** v_i + beta_i * algopy.log(sqrtht)) ** (2.))
Ejemplo n.º 4
0
def kimura_1957_54_numerator_analytic(p, c, d):
    """
    From Kimura 1957, equation (5.4).
    This is the diffusion approximation of the fixation probability
    of an allele that has reached frequency p in the population,
    with scaled selection c = Ns
    and dominance/recessivity parameter d = 2h - 1.
    @param p: initial allele frequency in the population
    @param c: population-scaled selection coefficient
    @param d: transformed dominance/recessivity parameter
    @return: diffusion estimate of fixation probability
    """
    # Mathematica notation:
    # Integrate[Exp[-2*c*d*x*(1-x) - 2*c*x], {x, 0, p}]
    #
    # precompute some intermediate quantities
    sqrt_c = algopy.sqrt(c)
    sqrt_d = algopy.sqrt(d)
    sqrt_2 = math.sqrt(2)
    sqrt_pi = math.sqrt(math.pi)
    #
    # compute the numerator
    erfi_num_a = algopy.special.erfi(
            (sqrt_c * (1 + d)) / (sqrt_2 * sqrt_d))
    erfi_num_b = algopy.special.erfi(
            (sqrt_c * (1 + d - 2*d*p)) / (sqrt_2 * sqrt_d))
    num = (sqrt_pi / sqrt_2) * (erfi_num_a + erfi_num_b)
    #
    # compute the denominator
    exp_den_a = algopy.exp((c*((1+d)**2)) / (2*d))
    den = 2*algopy.sqrt(c)*algopy.sqrt(d)*exp_den_a
    #
    return num / den
Ejemplo n.º 5
0
def eval_f_eigh(Y):
    """ some reformulations to make eval_f_orig
        compatible with algopy

        replaced scipy.linalg.expm by a symmetric eigenvalue decomposition

        this function **can** be differentiated with algopy

    """
    a, b, v = transform_params(Y)

    Q = algopy.zeros((4,4), dtype=Y)
    Q[0,0] = 0;    Q[0,1] = a;    Q[0,2] = b;    Q[0,3] = b;
    Q[1,0] = a;    Q[1,1] = 0;    Q[1,2] = b;    Q[1,3] = b;
    Q[2,0] = b;    Q[2,1] = b;    Q[2,2] = 0;    Q[2,3] = a;
    Q[3,0] = b;    Q[3,1] = b;    Q[3,2] = a;    Q[3,3] = 0;

    Q = algopy.dot(Q, algopy.diag(v))
    Q -= algopy.diag(algopy.sum(Q, axis=1))
    va = algopy.diag(algopy.sqrt(v))
    vb = algopy.diag(1./algopy.sqrt(v))
    W, U = algopy.eigh(algopy.dot(algopy.dot(va, Q), vb))
    M = algopy.dot(U, algopy.dot(algopy.diag(algopy.exp(W)), U.T))
    P = algopy.dot(vb, algopy.dot(M, va))
    S = algopy.log(algopy.dot(algopy.diag(v), P))
    return -algopy.sum(S * g_data)
Ejemplo n.º 6
0
def kimura_1957_54_denominator_analytic(c, d):
    """
    See the corresponding description for the numerator.
    This function computes the normalizing constant.
    """
    # Mathematica notation:
    # Integrate[Exp[-2*c*d*x*(1-x) - 2*c*x], {x, 0, 1}]
    #
    # precompute some intermediate quantities
    # FIXME: algopy has no csqrt but then again also does not support complex.
    #sqrt_c = cmath.sqrt(c)
    #sqrt_d = cmath.sqrt(d)
    sqrt_c = algopy.sqrt(c)
    sqrt_d = algopy.sqrt(d)
    sqrt_2 = math.sqrt(2)
    exp_2c = algopy.exp(2*c)
    #
    # compute the numerator
    dawsn_num_a = algopy.special.dawsn(
            (sqrt_c * (d-1)) / (sqrt_2 * sqrt_d))
    dawsn_num_b = algopy.special.dawsn(
            (sqrt_c * (d+1)) / (sqrt_2 * sqrt_d))
    num = dawsn_num_a + exp_2c * dawsn_num_b
    #
    # compute the denominator
    den = sqrt_2 * sqrt_c * sqrt_d * exp_2c
    #
    return num / den
Ejemplo n.º 7
0
def normalization(alpha, c, l, list_contr, dtype=np.float64(1.0)):
    contr = 0
    coef = algopy.zeros(len(alpha), dtype=dtype)

    for ib, ci in enumerate(list_contr):
        div = 1.0
        l_large = 0
        for m in l[ib]:
            if (m > 0):
                l_large += 1
                for k in range(1, 2 * m, 2):
                    div = div * k
        div = div / pow(2, l_large)
        div = div * pow(np.pi, 1.5)
        for i in range(ci):
            coef[contr + i] = normalization_primitive(alpha[contr + i], l[ib],
                                                      l_large) * c[contr + i]
        tmp = 0.0
        for i in range(ci):
            for j in range(ci):
                tmp = tmp + coef[contr + j] * coef[contr + i] / np.power(
                    alpha[contr + i] + alpha[contr + j], l_large + 1.5)
        tmp = algopy.sqrt(tmp * div)
        for i in range(contr, contr + ci):
            coef[i] = coef[i] / tmp
        contr = contr + ci
    return coef
Ejemplo n.º 8
0
def overlap(xin, params):
    xup, xdown, yup, ydown = xin
    r, alpha = params
    overlap_fraction = np.zeros(np.size(x))

    #define dx as the upstream x coordinate - the downstream x coordinate then rotate according to wind direction
    dx = xdown - xup
    #define dy as the upstream y coordinate - the downstream y coordinate then rotate according to wind direction
    dy = ydown - yup
    R = r + dx * alpha  #The radius of the wake depending how far it is from the turbine
    A = r**2 * np.pi  #The area of the turbine

    if dx > 0:
        if np.abs(dy) <= R - r:
            overlap_fraction = 1  #if the turbine is completely in the wake, overlap is 1, or 100%
        elif np.abs(dy) >= R + r:
            overlap_fraction = 0  #if none of it touches the wake, the overlap is 0
        else:
            #if part is in and part is out of the wake, the overlap fraction is defied by the overlap area/rotor area
            overlap_area = r**2. * arccos(
                (dy**2. + r**2. - R**2.) / (2.0 * dy * r)) + R**2. * arccos(
                    (dy**2. + R**2. - r**2.) / (2.0 * dy * R)) - 0.5 * sqrt(
                        (-dy + r + R) * (dy + r - R) * (dy - r + R) *
                        (dy + r + R))
            overlap_fraction = overlap_area / A
    else:
        overlap_fraction = 0  #turbines cannot be affected by any wakes that start downstream from them

    # print overlap_fraction
    return overlap_fraction  #retrun the n x n matrix of how each turbine is affected by all of the others
Ejemplo n.º 9
0
def demo_small_tree():
    nvertices = 3
    nleaves = 2
    nedges = 2
    v = np.exp(np.random.randn(2))
    v1, v2 = v.tolist()

    # define the shape of the tree
    B = np.array([
        [1, 0, -1],
        [0, 1, -1],
        ], dtype=float)

    # construct the centered covariance matrix using matrix algebra
    L = centered_tree_covariance(B, nleaves, v)

    # construct the centered covariance matrix using direct methods
    C = np.array([
        [v1, 0],
        [0, v2],
        ], dtype=float)
    C = doubly_centered(C)
    assert_allclose(L, C)

    # sample centered data
    vsqrt = np.sqrt(v)
    xs = []
    nsamples = 1000
    for i in range(nsamples):
        x = np.zeros(nleaves)
        x[0] = np.random.normal(0, vsqrt[0])
        x[1] = np.random.normal(0, vsqrt[1])
        x -= x.mean()
        xs.append(x)

    # check the log likelihood using matrix algebra
    print('average log likelihoods using matrix algebra')
    ll_average_matrix = log_likelihoods(L, xs).mean()
    print(ll_average_matrix)
    print()

    # check the log likelihood using felsenstein pruning
    print('average log likelihoods using felsenstein pruning')
    lls = []
    for x in xs:
        ll = scipy.stats.norm.logpdf(x[1] - x[0], loc=0, scale=sqrt(v1 + v2))
        pruning_adjustment = 0.5 * log(nleaves)
        lls.append(pruning_adjustment + ll)
    ll_average_pruning = np.mean(lls)
    print(ll_average_pruning)
    print()

    d = ll_average_pruning - ll_average_matrix
    print('difference of log likelihoods:')
    print(d)
    print()
    print('exp of difference of log likelihoods:')
    print(exp(d))
    print()
Ejemplo n.º 10
0
def ackley(x):
    a, b, c = 20.0, -0.2, 2.0 * numpy.pi
    len_recip = 1.0 / len(x)
    sum_sqrs, sum_cos = 0.0, 0.0
    for i in x:
        sum_cos += algopy.cos(c * i)
        sum_sqrs += i * i
    return -a * algopy.exp(b * algopy.sqrt(len_recip * sum_sqrs)) - algopy.exp(len_recip * sum_cos) + a + numpy.e
Ejemplo n.º 11
0
def ackley(x):
    a, b, c = 20.0, -0.2, 2.0 * numpy.pi
    len_recip = 1.0 / len(x)
    sum_sqrs, sum_cos = 0.0, 0.0
    for i in x:
        sum_cos += algopy.cos(c * i)
        sum_sqrs += i * i
    return (-a * algopy.exp(b * algopy.sqrt(len_recip * sum_sqrs)) -
            algopy.exp(len_recip * sum_cos) + a + numpy.e)
Ejemplo n.º 12
0
def eval_f_eigh(Y):
    """ some reformulations to make eval_f_orig
        compatible with algopy

        replaced scipy.linalg.expm by a symmetric eigenvalue decomposition

        this function **can** be differentiated with algopy

    """
    a, b, v = transform_params(Y)

    Q = algopy.zeros((4, 4), dtype=Y)
    Q[0, 0] = 0
    Q[0, 1] = a
    Q[0, 2] = b
    Q[0, 3] = b
    Q[1, 0] = a
    Q[1, 1] = 0
    Q[1, 2] = b
    Q[1, 3] = b
    Q[2, 0] = b
    Q[2, 1] = b
    Q[2, 2] = 0
    Q[2, 3] = a
    Q[3, 0] = b
    Q[3, 1] = b
    Q[3, 2] = a
    Q[3, 3] = 0

    Q = algopy.dot(Q, algopy.diag(v))
    Q -= algopy.diag(algopy.sum(Q, axis=1))
    va = algopy.diag(algopy.sqrt(v))
    vb = algopy.diag(1. / algopy.sqrt(v))
    W, U = algopy.eigh(algopy.dot(algopy.dot(va, Q), vb))
    M = algopy.dot(U, algopy.dot(algopy.diag(algopy.exp(W)), U.T))
    P = algopy.dot(vb, algopy.dot(M, va))
    S = algopy.log(algopy.dot(algopy.diag(v), P))
    return -algopy.sum(S * g_data)
Ejemplo n.º 13
0
def loss(r_0, a, alpha, x_focus, x, overlap):
    loss = np.zeros(np.size(x))
    loss_squared = np.zeros(np.size(x))
    dx = np.zeros(np.size(x))
    for i in range(0, np.size(x)):
        dx[i] = x_focus-x[i]
        if dx[i] > 0:
            loss[i] = overlap[i]*2.*a*(r_0/(r_0+alpha*(dx[i])))**2
            loss_squared[i] = loss[i]**2
        else:
            loss[i] = 0
            loss_squared[i] = 0
    total_loss = sqrt(np.sum(loss_squared))
    return total_loss
Ejemplo n.º 14
0
def loss(r_0, a, alpha, x_focus, x, overlap):
    loss = np.zeros(np.size(x))
    loss_squared = np.zeros(np.size(x))
    dx = np.zeros(np.size(x))
    for i in range(0, np.size(x)):
        dx[i] = x_focus - x[i]
        if dx[i] > 0:
            loss[i] = overlap[i] * 2. * a * (r_0 / (r_0 + alpha * (dx[i])))**2
            loss_squared[i] = loss[i]**2
        else:
            loss[i] = 0
            loss_squared[i] = 0
    total_loss = sqrt(np.sum(loss_squared))
    return total_loss
Ejemplo n.º 15
0
def prune_cherry(v1, v2, x1, x2):
    """
    @param v1: terminal branch length of the first leaf
    @param v2: terminal branch length of the second leaf
    @param x1: observed data at the first leaf
    @param x2: observed data at the second leaf
    @return: ll, delta, x12
    """
    v12 = v1 + v2
    sigma = sqrt(v12)
    delta = v1*v2 / v12
    x12 = (v2*x1 + v1*x2) / v12
    ll = scipy.stats.norm.logpdf(x2 - x1, loc=0, scale=sigma)
    return ll, delta, x12
Ejemplo n.º 16
0
def custom_pruning(v, x):
    """
    Do Felsenstein REML pruning using a hardcoded tree.
    Branch lengths are variances.
    Return the log likelihood.
    @param v: branch lengths
    @param x: data vector
    @return: ll
    """
    nleaves = x.shape[0]
    ll01, delta01, x01 = prune_cherry(v[0], v[1], x[0], x[1])
    ll23, delta23, x23 = prune_cherry(v[2], v[3], x[2], x[3])
    v45 = v[4] + delta01 + delta23
    sigma45 = sqrt(v45)
    ll45 = scipy.stats.norm.logpdf(x23 - x01, loc=0, scale=sigma45)
    pruning_adjustment = 0.5 * log(nleaves)
    return pruning_adjustment + ll01 + ll23 + ll45
Ejemplo n.º 17
0
def house(x):
    """ computes the Householder vector v and twice its norm beta
    
    (v,beta) = house(x)
    
    Parameters
    ----------
    x: array_like
        len(x) = N
    
    Returns
    -------
    v: array_like
        len(v) = N
    
    beta: Float
        two times the 2-norm of v
        
    Description
    -----------
    computes beta and v to be used in the Householder reflector
    H(v) = 1 - beta dot(v,v.T)
    where v[0] = 1
    such that H(v)x = alpha * e_1
    i.e., H(v)x is a multiple of the first Cartesian basis vector
    """
    
    sigma = algopy.sqrt(algopy.dot(x.T,x))[0,0]
    
    v = x.copy()
    if x[0] <= 0:
        v[0] -= sigma

    else:
        v[0] += sigma
    
    v = v/v[0]
    beta = 2./algopy.dot(v.T,v)[0,0]
    
    return v, beta
Ejemplo n.º 18
0
def house(x):
    """ computes the Householder vector v and twice its norm beta
    
    (v,beta) = house(x)
    
    Parameters
    ----------
    x: array_like
        len(x) = N
    
    Returns
    -------
    v: array_like
        len(v) = N
    
    beta: Float
        two times the 2-norm of v
        
    Description
    -----------
    computes beta and v to be used in the Householder reflector
    H(v) = 1 - beta dot(v,v.T)
    where v[0] = 1
    such that H(v)x = alpha * e_1
    i.e., H(v)x is a multiple of the first Cartesian basis vector
    """
    
    sigma = algopy.sqrt(algopy.dot(x.T,x))[0,0]
    
    v = x.copy()
    if x[0] <= 0:
        v[0] -= sigma

    else:
        v[0] += sigma
    
    v = v/v[0]
    beta = 2./algopy.dot(v.T,v)[0,0]
    
    return v, beta
Ejemplo n.º 19
0
def rhfenergy(alpha_old, coef2, xyz, l, charges, xyz_atom, natoms, nbasis,
              contr_list, ne, max_scf, max_d, log, eigen, printguess,
              readguess, name, write, dtype):
    '''
    This function returns the rhf function

    Parameters:
     alpha_old : array
                Gaussian exponents
     coef2     : array
                Contraction coeffients
     xyz       : array 3N
                Gaussian centers
     l         : array 3N
                Angular momentum each entry is a vector
                eg. s orbital (0,0,0) or pz (1,0,0)
     charges   : array
                Atom charges
     nbasis    : int
                Number of basis
     contr_list: list of integers
                Specify the number of orbitals in each atom
     ne        : int
                Number of electrons
     max_scf   : int
                maximum number of scf cycles
     log       : bool
                The exponents are given in log
     printguess: str or None
                File to print coeff matrix initial guess
     readguess : str or None
                File that contains coeff matrix initial guess
     name      : str
                Output file name
     write     : bool
                True if printing
     dtype     : type of output
                This is the directive to know if algopy will be used or not
                np.float64(1.0) if it is a single point calculation
                otherwise, it specify the size of the UTMP, autodifferentiation
    Returns:
       energy    : float
                RHF energy
    '''
    tool_D = 1e-8
    tool = 1e-8

    if log:
        alpha = algopy.exp(alpha_old)
    else:
        alpha = alpha_old

    if type(xyz_atom) != np.ndarray:  ## Cover the case of diff xyz atom
        coef = normalization(alpha,
                             coef2,
                             l,
                             contr_list,
                             dtype=np.float64(1.0))
        V = nuclearmatrix(alpha,
                          coef,
                          xyz,
                          l,
                          nbasis,
                          charges,
                          xyz_atom,
                          natoms,
                          contr_list,
                          dtype=dtype)
        S = overlapmatrix(alpha,
                          coef,
                          xyz,
                          l,
                          nbasis,
                          contr_list,
                          dtype=np.float64(1.0))
        T = kineticmatrix(alpha,
                          coef,
                          xyz,
                          l,
                          nbasis,
                          contr_list,
                          dtype=np.float64(1.0))
        Eri = erivector(alpha,
                        coef,
                        xyz,
                        l,
                        nbasis,
                        contr_list,
                        dtype=np.float(1.0))
    else:
        coef = normalization(alpha, coef2, l, contr_list, dtype=dtype)
        S = overlapmatrix(alpha, coef, xyz, l, nbasis, contr_list, dtype=dtype)
        V = nuclearmatrix(alpha,
                          coef,
                          xyz,
                          l,
                          nbasis,
                          charges,
                          xyz_atom,
                          natoms,
                          contr_list,
                          dtype=dtype)
        T = kineticmatrix(alpha, coef, xyz, l, nbasis, contr_list, dtype=dtype)
        Eri = erivector(alpha, coef, xyz, l, nbasis, contr_list, dtype=dtype)
    Hcore = T + V
    if eigen:
        eigsys = eigensolver(S)
        SqrtLambda = algopy.diag(1. / algopy.sqrt(eigsys[0]))
        L = eigsys[1]
        LT = algopy.transpose(L)
        SqrtS = algopy.dot(algopy.dot(L, SqrtLambda), LT)
        SqrtST = algopy.transpose(SqrtS)
    else:
        Sinv = np.linalg.inv(S)

    if readguess != None:
        C = np.load(readguess)
        D = np.zeros((nbasis, nbasis))
        for i in range(nbasis):
            for j in range(nbasis):
                tmp = 0.0
                for k in range(ne):
                    tmp = tmp + C[i, k] * C[j, k]
                D[i, j] = tmp
        F = fockmatrix(Hcore, Eri, D, nbasis, alpha, dtype)
    else:
        F = Hcore
    OldE = 1e8

    status = False
    E_step = []
    for scf_iter in range(max_scf):
        if eigen:
            Fprime = algopy.dot(algopy.dot(SqrtST, F), SqrtS)
            eigsysFockOp = eigensolver(Fprime)
            Cprime = eigsysFockOp[1]
            C = algopy.dot(SqrtS, Cprime)
            Fprime = algopy.dot(algopy.dot(SqrtST, F), SqrtS)
            eigsysFockOp = eigensolver(Fprime)
            Cprime = eigsysFockOp[1]
            C = algopy.dot(SqrtS, Cprime)
            D = algopy.zeros((nbasis, nbasis), dtype=dtype)
            for i in range(nbasis):
                for j in range(nbasis):
                    tmp = 0.0
                    for k in range(ne):
                        tmp = tmp + C[i, k] * C[j, k]
                    D[i, j] = tmp
        else:
            D = newdensity(F, Sinv, nbasis, ne)
            for i in range(max_d):
                D = cannonicalputication(D, S)
                err = np.linalg.norm(D - np.dot(np.dot(D, S), D))
                if err < tool_D:
                    break
        F = fockmatrix(Hcore, Eri, D, nbasis, alpha, dtype)
        E_elec = algopy.sum(np.multiply(D, Hcore + F))
        E_step.append(E_elec)
        E_nuc = nuclearrepulsion(xyz_atom, charges, natoms)
        if np.absolute(E_elec - OldE) < tool:
            status = True
            break
        OldE = E_elec
    E_nuc = nuclearrepulsion(xyz_atom, charges, natoms)
    if printguess != None:
        np.save(printguess, C)

    def update_system():
        mol.energy = E_elec + E_nuc
        mol.erepulsion = Eri
        mol.hcore = Hcore
        mol.mo_coeff = C
        return

    def write_molden():
        import Data
        from Data import select_atom
        ## Details of calculation
        tape.write('[Energy] \n')
        tape.write('E_elec: ' + str(E_elec) + '\n')
        tape.write('E_nuc: ' + str(E_nuc) + '\n')
        tape.write('E_tot: ' + str(E_nuc + E_elec) + '\n')
        tape.write('SCF Details\n')
        line = 'Eigen: '
        if eigen:
            tape.write(line + 'True')
        else:
            tape.write(line + 'False')
        tape.write('\n')
        for i, step in enumerate(E_step):
            line = 'Step: ' + str(i) + ' ' + str(step)
            tape.write(line + '\n')

        ### C Matrix
        tape.write('[CM] \n')
        tape.write('C AO times MO\n')
        printmatrix(C, tape)

        ### D Matrix
        tape.write('[DM] \n')
        tape.write('D \n')
        printmatrix(D, tape)

        ### D Matrix
        tape.write('[NMO] \n')
        tape.write('NMO \n')
        printmatrix(mo_naturalorbital(D), tape)

        ### MO energies
        tape.write('[MOE] \n')
        tape.write('MOE \n')
        for i, energ in enumerate(eigsysFockOp[0]):
            tape.write(str(i) + ' ' + str(energ) + '\n')

        ### MO energies
        tape.write('[INPUT] \n')
        line = 'mol = ['
        for i, coord in enumerate(xyz_atom):
            line += '(' + str(charges[i]) + ','
            line += '(' + str(coord[0]) + ',' + str(coord[1]) + ',' + str(
                coord[2]) + ')),\n'
        tape.write(line)
        cont = 0
        line = 'basis = ['
        for i, ci in enumerate(contr_list):
            line += '['
            line += '(' + str(l[i][0]) + ',' + str(l[i][1]) + ',' + str(
                l[i][2]) + '),'
            for ii in range(ci):
                line += str(alpha[cont]) + ',' + str(coef[i])
                line += ',(' + str(xyz[i, 0]) + ',' + str(
                    xyz[i, 1]) + ',' + str(xyz[i, 2]) + ')],\n'
                cont += 1
            line += ']\n'
        tape.write(line)

        ### Atom coordinates
        tape.write('[Atoms]\n')
        for i, coord in enumerate(xyz_atom):
            line = select_atom.get(charges[i])
            line += ' ' + str(i + 1) + ' ' + str(charges[i])
            line += ' ' + str(coord[0]) + ' ' + str(coord[1]) + ' ' + str(
                coord[2]) + '\n'
            tape.write(line)
        ### Basis coordinates
        for i, coord in enumerate(xyz):
            line = 'XX'
            line += ' ' + str(i + natoms + 1) + ' ' + str(0)
            line += ' ' + str(coord[0]) + ' ' + str(coord[1]) + ' ' + str(
                coord[2]) + '\n'
            tape.write(line)

        ### Basis set
        cont = 0
        tape.write('[GTO]\n')
        for i, ci in enumerate(contr_list):
            tape.write('  ' + str(i + 1 + natoms) + '  0\n')
            if np.sum(l[i]) == 0:
                tape.write(' s   ' + str(ci) + ' 1.0 ' + str(l[i][0]) + ' ' +
                           str(l[i][1]) + ' ' + str(l[i][2]) + '\n')
            else:
                tape.write(' p   ' + str(ci) + ' 1.0 ' + str(l[i][0]) + ' ' +
                           str(l[i][1]) + ' ' + str(l[i][2]) + '\n')
                #tape.write(' p   '+str(1)+' 1.0 '+ str(l[i])+'\n')
            for ii in range(ci):
                line = '  ' + str(alpha[cont]) + ' ' + str(coef[cont]) + '\n'
                tape.write(line)
                cont += 1
            line = '  \n'
            tape.write(line)
        ### MOs
        tape.write('[MO]\n')
        for j in range(nbasis):
            tape.write('  Sym=  None\n')
            tape.write('  Ene=      ' + str(eigsysFockOp[0][j]) + '\n')
            tape.write('  Spin= Alpha\n')
            if j > ne:
                tape.write('  Occup=    0.0\n')
            else:
                tape.write('  Occup=    2.0\n')
            for i in range(nbasis):
                tape.write(str(i + 1 + natoms) + ' ' + str(C[i, j]) + '\n')

    if status:
        if write:
            tape = open(name + '.molden', "w")
            write_molden()
            tape.close()
            return E_elec + E_nuc
    else:
        print('E_elec: ' + str(E_elec) + '\n')
        print('E_nuc: ' + str(E_nuc) + '\n')
        print('E_tot: ' + str(E_nuc + E_elec) + '\n')
        print('SCF DID NOT CONVERGED')
        return 99999

    return E_elec + E_nuc
Ejemplo n.º 20
0
def get_f(r_t, h_i_tm1, lambda_i, gamma_i):
    return 1/algopy.sqrt(2*numpy.pi * h_i_tm1) * algopy.exp(-((r_t - (lambda_i + gamma_i * algopy.sqrt(h_i_tm1))) ** 2.) / (2 * h_i_tm1))
Ejemplo n.º 21
0
def get_f_i(delta_i_t, b_i, c_i):
    return algopy.sqrt(algopy.square((delta_i_t - b_i))) - c_i * (delta_i_t - b_i)
Ejemplo n.º 22
0
def get_h_tm1_agg_i(p_1_tm1_agg_i, h_1_tm1, h_2_tm1, lambda1, gamma1, lambda2, gamma2):
    return (p_1_tm1_agg_i * h_1_tm1 + (1-p_1_tm1_agg_i) * h_2_tm1 +
        p_1_tm1_agg_i * (1-p_1_tm1_agg_i) * (lambda1 + algopy*numpy.sqrt(h_1_tm1) - (lambda2 + gamma1*algopy.sqrt(h_2_tm1))) **2)
Ejemplo n.º 23
0
def get_delta_t_agg_i(p_1_tm1_agg_i, r_t, lambda_1, gamma_1, lambda_2, gamma_2, h_1_tm1, h_2_tm1):
    p1 =       p_1_tm1_agg_i * ((r_t- (lambda_1 + gamma_1 * algopy.sqrt(h_1_tm1)))/algopy.sqrt(h_1_tm1))
    p2 = (1 - p_1_tm1_agg_i) * ((r_t- (lambda_2 + gamma_2 * algopy.sqrt(h_2_tm1)))/algopy.sqrt(h_2_tm1))
    return p1 + p2
Ejemplo n.º 24
0
def get_p_1_tm1_agg_2(d_1, e_1, lambda_1, gamma_1, h_1_tm1, p_1_tm1, d_2, e_2, lambda_2, gamma_2, h_2_tm1, p_2_tm1):
    p1term = (1 - cdf(d_1+e_1*(lambda_1 + gamma_1 * algopy.sqrt(h_1_tm1))))*p_1_tm1
    p2term =      cdf(d_2+e_2*(lambda_2 + gamma_2 * algopy.sqrt(h_2_tm1)))*p_2_tm1
    return p1term/(p1term + p2term)
Ejemplo n.º 25
0
def overlap(x, xdown, y, ydown, r, alpha):
    overlap_fraction = np.zeros(np.size(x))
    for i in range(0, np.size(x)):
        #define dx as the upstream x coordinate - the downstream x coordinate then rotate according to wind direction
        dx = xdown - x[i]
        #define dy as the upstream y coordinate - the downstream y coordinate then rotate according to wind direction
        dy = ydown - y[i]
        R = r+dx*alpha #The radius of the wake depending how far it is from the turbine
        A = r**2*np.pi #The area of the turbine

        if dx > 0:
            if np.abs(dy) <= R-r:
                overlap_fraction[i] = 1 #if the turbine is completely in the wake, overlap is 1, or 100%
            elif np.abs(dy) >= R+r:
                overlap_fraction[i] = 0 #if none of it touches the wake, the overlap is 0
            else:
                #if part is in and part is out of the wake, the overlap fraction is defied by the overlap area/rotor area
                overlap_area = r**2.*arccos((dy**2.+r**2.-R**2.)/(2.0*dy*r))+R**2.*arccos((dy**2.+R**2.-r**2.)/(2.0*dy*R))-0.5*sqrt((-dy+r+R)*(dy+r-R)*(dy-r+R)*(dy+r+R))
                overlap_fraction[i] = overlap_area/A
        else:
            overlap_fraction[i] = 0 #turbines cannot be affected by any wakes that start downstream from them

    # print overlap_fraction
    return overlap_fraction #retrun the n x n matrix of how each turbine is affected by all of the others
Ejemplo n.º 26
0
 def eval_f1(x):
     return algopy.sqrt(algopy.sum(x*x))