def test_lognormal():
    mean = Symbol('mu', real=True, finite=True)
    std = Symbol('sigma', positive=True, real=True, finite=True)
    X = LogNormal('x', mean, std)
    # The sympy integrator can't do this too well
    #assert E(X) == exp(mean+std**2/2)
    #assert variance(X) == (exp(std**2)-1) * exp(2*mean + std**2)

    # Right now, only density function and sampling works
    # Test sampling: Only e^mean in sample std of 0
    for i in range(3):
        X = LogNormal('x', i, 0)
        assert S(sample(X)) == N(exp(i))
    # The sympy integrator can't do this too well
    #assert E(X) ==

    mu = Symbol("mu", real=True)
    sigma = Symbol("sigma", positive=True)

    X = LogNormal('x', mu, sigma)
    assert density(X)(x) == (sqrt(2)*exp(-(-mu + log(x))**2
                                    /(2*sigma**2))/(2*x*sqrt(pi)*sigma))

    X = LogNormal('x', 0, 1)  # Mean 0, standard deviation 1
    assert density(X)(x) == sqrt(2)*exp(-log(x)**2/2)/(2*x*sqrt(pi))
    def normal_dist1(self, mean, sd, x1):
        '''
        this function returns the probability using the normal distribution.
         parameters: 
            mean:the mean of the normal distribution
            sd :the standard deviation of the normal distribution
            x1: a value in the data set of the normal distribution

        returns the calculated probability'''
        z = round(((x1 - mean) / sd), 3)  # round to 3dp
        p = integrate(
            self.funx(),
            (self.x, -oo,
             z))  # integrates the function from negative infinity to z
        prob = {'p(Z<-z)': N(p), 'p(Z>-z)': 1 - N(p)}
        return prob
Пример #3
0
def calculate_value(free_symbols_dict, replaced, reduced, precision_factor=1):

    # We only care about the first argument of [reduced]
    reduced = reduced[0]

    # Set precision to [precision] multiplied by [precision_factor]
    mp.dps = precision_factor * precision

    # Replacing old expressions with new expressions and storing result in free_symbols_dict
    for new, old in replaced:
        keys = old.free_symbols
        for key in keys:
            old = old.subs(key, free_symbols_dict[key])
        free_symbols_dict[new] = old

    # Evaluating expression after cse optimization substitution
    keys = reduced.free_symbols
    for key in keys:
        reduced = reduced.subs(key, free_symbols_dict[key])

    # Adding our variable, value pair to our calculated_dict
    try:
        res = mpf(reduced)
    # If value is a complex number, store it as a mpc
    except TypeError:
        res = mpc(N(reduced))

    # Set the precision back
    mp.dps = precision

    return res
def Yl_red(l1, l2, l):
    """
    < l1 || Y_l || l2 >
    Note: all inputs are not not doubled
    """
    return (-1)**l1 * np.sqrt((2 * l1 + 1) * (2 * l2 + 1) * (2 * l + 1) /
                              (4 * np.pi)) * N(wigner_3j(l1, l, l2, 0, 0, 0))
Пример #5
0
def test_intrinsic_math1_codegen():
    # not included: log10
    from sympy import acos, asin, atan, ceiling, cos, cosh, floor, log, ln, \
        sin, sinh, sqrt, tan, tanh, N
    name_expr = [
        ("test_fabs", abs(x)),
        ("test_acos", acos(x)),
        ("test_asin", asin(x)),
        ("test_atan", atan(x)),
        ("test_cos", cos(x)),
        ("test_cosh", cosh(x)),
        ("test_log", log(x)),
        ("test_ln", ln(x)),
        ("test_sin", sin(x)),
        ("test_sinh", sinh(x)),
        ("test_sqrt", sqrt(x)),
        ("test_tan", tan(x)),
        ("test_tanh", tanh(x)),
    ]
    numerical_tests = []
    for name, expr in name_expr:
        for xval in 0.2, 0.5, 0.8:
            expected = N(expr.subs(x, xval))
            numerical_tests.append((name, (xval, ), expected, 1e-14))
    for lang, commands in valid_lang_commands:
        if lang.startswith("C"):
            name_expr_C = [("test_floor", floor(x)), ("test_ceil", ceiling(x))]
        else:
            name_expr_C = []
        run_test("intrinsic_math1", name_expr + name_expr_C, numerical_tests,
                 lang, commands)
Пример #6
0
def calcDistance():
    while True:
        try:
            x1In = input("X1 = ")
            y1In = input("Y1 = ")
            x2In = input("X2 = ")
            y2In = input("Y2 = ")
            expr = sqrt((X2 - X1)**2 + (Y2 - Y1)**2) - d
            expr2 = ((X2 - X1)**2 + (Y2 - Y1)**2)**(1 / 2) - d
            expr = expr.subs(X1, x1In)
            expr = expr.subs(X2, x2In)
            expr = expr.subs(Y1, y1In)
            expr = expr.subs(Y2, y2In)
            expr2 = expr2.subs(X1, x1In)
            expr2 = expr2.subs(X2, x2In)
            expr2 = expr2.subs(Y1, y1In)
            expr2 = expr2.subs(Y2, y2In)
            print("\nResults:")
            sol = N(expr2)
            sol = solve(sol, d)
            expr = solve(expr, d)
            print("Sqrt:\t\t", expr)
            print("Decimal:\t", str(sol))
            closer = str(
                input("\nEnter 1 to exit.\n"
                      "Press any key to continue.\n"))
            if (closer == '1'):
                return
        except:
            print("Invalid Character")
Пример #7
0
def test_ansi_math1_codegen():
    # not included: log10
    from sympy import acos, asin, atan, ceiling, cos, cosh, floor, log, ln, \
        sin, sinh, sqrt, tan, tanh, N
    x = symbols('x')
    name_expr = [
        ("test_fabs", abs(x)),
        ("test_acos", acos(x)),
        ("test_asin", asin(x)),
        ("test_atan", atan(x)),
        ("test_ceil", ceiling(x)),
        ("test_cos", cos(x)),
        ("test_cosh", cosh(x)),
        ("test_floor", floor(x)),
        ("test_log", log(x)),
        ("test_ln", ln(x)),
        ("test_sin", sin(x)),
        ("test_sinh", sinh(x)),
        ("test_sqrt", sqrt(x)),
        ("test_tan", tan(x)),
        ("test_tanh", tanh(x)),
    ]
    numerical_tests = []
    for name, expr in name_expr:
        for xval in 0.2, 0.5, 0.8:
            expected = N(expr.subs(x, xval))
            numerical_tests.append((name, (xval,), expected, 1e-14))
    run_cc_test("ansi_math1", name_expr, numerical_tests)
Пример #8
0
def regulate(theta):
    """
    Return the regulated symbolic representation of `theta`::
        * if it has a representation close enough to `pi` transformations,
            return that representation (for example, `3.14` -> `sympy.pi`).
        * otherwise, return a sympified representation of theta (for example,
            `1.23` ->  `sympy.Float(1.23)`).

    See also `UGateGeneric`.

    Args:
        theta (float or sympy.Basic): the float value (e.g., 3.14) or the
            symbolic value (e.g., pi)

    Returns:
        sympy.Basic: the sympy-regulated representation of `theta`
    """
    error_margin = 0.01
    targets = [pi, pi / 2, pi * 2, pi / 4]

    for t in targets:
        if abs(N(theta - t)) < error_margin:
            return t

    return sympify(theta)
Пример #9
0
def dipole_hf_to_fs(
        electric_field: complex,
        q_ar: SphericalVector,
        d_rme: complex,
        j: moment,
        f: moment,
        mf: moment,
        jp: moment,
        mp: moment,
        i: moment
) -> complex:
    """
    Computes rabi frequency for a dipole transition between two zeeman states, the lower
    (un-primed) state being defined in the hyperfine basis and the upper (primed) state being
    defined in the fine structure basis.

    This computation is particularly useful in the case of exciting to Rydberg states, where the
    strength hyperfine interactions become much smaller than the linewidths of the fine structure
    levels.

    The states in this function are described as |a, f, mf> -> |ap, jp, mp> where p represents
    primed states, and a/ap abstract away all unaccounted-for quantum numbers.
    Args:
        electric_field : electric field strength of the oscillating field coupling the two states
        q_ar : SphericalVector object describing the field polarization
        d_rme : reduced dipole matrix element between the two FINE-STRUCTURE levels
        j : fine structure angular momentum quantum number for the initial state. Should be
            integer or half-integer
        f : hyperfine structure angular momentum quantum number for the initial state. Should be
            integer or half-integer
        mf : zeeman state quantum number (in the hyperfine basis) for the initial state. Should be
            integer or half-integer
        jp : fine structure angular momentum quantum number for the final state. Should be
            integer of half-integer
        mp : zeeman state quantum number (in the fine structure basis) for the final state.
            Should be integer or half-integer
        i : nuclear spin quantum number. Should be integer or half-integer

    Returns:
        rabi frequency coupling |a,I,j,f,mf> to |ap,j,mj;I>
    """

    s = 0
    for q in [-1, 0, 1]:
        #print(q, q_ar[q])
        for fp in np.arange(abs(i-jp), i+jp+1):
            mfp = q+mf
            if abs(mfp) > fp:
                # print(f"q = {q} mf = {mf}, fp = {fp} mfp = {mfp}")
                s += 0
                continue
            c1 = clebsch_gordan(jp, i, fp, mp, mfp-mp, mfp)
            c2 = clebsch_gordan(1, f, fp, q, mf, mfp)
            six = wigner_6j(j, i, f, fp, 1, jp)
            cont = c1 * c2 * six * q_ar[q] * (-1) ** (1 + i + jp + fp)
            # if(q_ar[q] != 0):
                # print(f"fr = {fp} mfr = {mfp} c1 = {c1} c2 = {c2}")
            s += cont
    return complex(N(electric_field * s * np.sqrt(2 * f + 1) * d_rme / hb))
Пример #10
0
def thj(j1, j2, j3, m1, m2, m3):
    """
    3-j symbol
    ( j1 j2 j3 )
    ( m1 m2 m3 )
    """
    #return wigner3j(j1,j2,j3,m1,m2,m3)
    return N(wigner_3j(j1, j2, j3, m1, m2, m3))
Пример #11
0
    def get_probability_density_func(self):
        """
        Ensures that the probabilities sum to be 1.
        """
        tol = 1e-12
        target = 1 - tol
        integ = 0
        inc = 5
        beg = 20

        dist_sum = N(
            Sum(self.distribution,
                (self.x, self.interval_low, self.interval_high)).doit())
        self.distribution = self.distribution / dist_sum
        f = np.vectorize(
            lambdify(self.x, self.distribution, ('numpy', 'sympy')))

        if self.interval_low != '-oo' and self.interval_high != 'oo':
            low_approx = self.interval_low
            high_approx = self.interval_high
            self.x_values = np.arange(self.interval_low,
                                      self.interval_high + 1)

        else:
            low_approx = -beg if self.interval_low == '-oo' else self.interval_low
            high_approx = beg if self.interval_high == 'oo' else self.interval_high

            while integ < target:
                xs = np.arange(low_approx, high_approx + 1)
                func = f(xs)

                integ = np.sum(func)
                low_approx = low_approx - inc if self.interval_low == '-oo' else low_approx
                high_approx = high_approx + inc if self.interval_high == 'oo' else high_approx

            self.x_values = xs

        prob_acc = N(
            Sum(self.distribution, (self.x, low_approx, high_approx)).doit())

        if prob_acc < target:
            print(f'Variable {self.name} is not correct.')
            _warn(f'Variable {self.name} is not correct.')
            exit()

        self.probabilities = f(self.x_values)
 def is_equal(self, eq1, eq2):
     """Compare answers"""
     #answer=eq1, solution=eq2
     equation_types = [
         Equality, Unequality, StrictLessThan, LessThan, StrictGreaterThan,
         GreaterThan
     ]
     #Symbolic equality/Perfect match
     if self._comparison_type == "perfect_match":
         return eq1 == eq2
     eq1 = factor(
         simplify(eq1)
     )  #simplify is mandatory to counter expand_trig and expand_log weaknesses
     eq2 = factor(simplify(eq2))
     #Trigonometric simplifications
     if self._use_trigo:
         eq1 = expand_trig(eq1)
         eq2 = expand_trig(eq2)
     #Logarithmic simplifications
     if self._use_log:
         if self._use_complex:
             eq1 = expand_log(eq1)
             eq2 = expand_log(eq2)
         else:
             eq1 = expand_log(eq1, force=True)
             eq2 = expand_log(eq2, force=True)
     if self._tolerance:
         eq1 = eq1.subs([(E, math.e), (pi, math.pi)])
         eq2 = eq2.subs([(E, math.e), (pi, math.pi)])
     #Numbers
     if (isinstance(eq1, Number)
             and isinstance(eq2, Number)) or self._tolerance:
         return round(float(abs(N(eq1 - eq2))), 10) <= round(
             float(self._tolerance), 10) if self._tolerance else abs(
                 N(eq1 - eq2)) == 0
     #Numerical Evaluation
     if not type(eq1) == type(eq2):
         return N(eq1) == N(eq2)
     #Equality and inequalities
     if type(eq1) in equation_types:
         return eq1 == eq2 or simplify(eq1) == simplify(eq2)
     #Direct match
     if eq1 == eq2 or simplify(eq1) == simplify(eq2):
         return True
     #Uncaught
     return abs(N(eq1 - eq2)) == 0
Пример #13
0
    def rotated(self, nx: float, ny: float, nz: float, theta: float):
        """
        Returns a rotated version of this object

        :param nx: x-component of the rotation axis
        :param ny: y-component of the rotation axis
        :param nz: z-component of the rotation axis
        :param theta: rotation angle
        :return: a rotated version of this object
        """
        nrm = N(sqrt(nx**2 + ny**2 + nz**2))
        sn2 = N(sin(theta / 2))
        cs2 = N(cos(theta / 2))
        q = Quaternion(cs2, sn2 * nx / nrm, sn2 * ny / nrm, sn2 * nz / nrm)
        q_inv = q.conjugate()
        r = q_inv * Quaternion(0, x, y, z) * q
        return Geometry3D(self.subs_3d(self.f, r.b, r.c, r.d))
Пример #14
0
def sjs(j1, j2, j3, j4, j5, j6):
    """
    6-j symbol
    { j1 j2 j3 }
    { j4 j5 j6 }
    """
    #return wigner6j(j1,j2,j3,j4,j5,j6)
    return N(wigner_6j(0.5*j1,0.5*j2,0.5*j3,0.5*j4,0.5*j5,0.5*j6))
Пример #15
0
    def test_generate_orthopoly(self):
        """
        Testing the ExponentialVariable generate_orthopoly and ensuring that the
        orthogonal polynomials are correct.
        """
        tol = 1e-6
        x0 = symbols('x0')

        true_var_orthopoly_vect = Matrix([
            [1], [x0 - 0.142857142857143],
            [x0 ** 2 - 0.571428571428572 * x0 + 0.0408163265306123],
            [x0 ** 3 - 1.28571428571428 * x0 ** 2 + 0.367346938775509 * x0
             -0.0174927113702623],
            [x0 ** 4 - 2.28571428571422 * x0 ** 3 + 1.46938775510196 * x0 ** 2
             -0.279883381924174 * x0 + 0.00999583506872018],
            [x0 ** 5 - 3.57142857142935 * x0 ** 4 + 4.08163265306289 * x0 ** 3
             -1.74927113702723 * x0 ** 2 + 0.249895876718207 * x0
             -0.00713988219194941],
#             [x0 ** 6 - 5.14285714283134 * x0 ** 5 + 9.18367346929817 * x0 ** 4
#              -6.99708454800531 * x0 ** 3 + 2.24906289042068 * x0 ** 2
#              -0.257035758904169 * x0 + 0.00611989902150362]
        ])

        basis_size = len(true_var_orthopoly_vect)

        equal = [
            str(
                Eq(
                    N(sympify(expand(true_var_orthopoly_vect[i])), tol),
                    N(sympify(expand(self.exp_var.var_orthopoly_vect[i])), tol)
                )
            ) for i in range(basis_size)
        ]

        eval_loc = locals().copy()
        eval_glob = globals().copy()

        evaled = np.array([
            eval(equal[i], eval_loc, eval_glob) for i in range(len(equal))]
        )

        self.assertTrue(
            evaled.all(),
            msg='ExponentialVariable generate_orthopoly is not correct'
        )
Пример #16
0
    def test_generate_orthopoly(self):
        """
        Testing the BetaVariable generate_orthopoly and ensuring that the
        orthogonal polynomials are correct.
        """
        tol = 1e-6
        x0 = symbols('x0')

        true_var_orthopoly_vect = Matrix([
            [1], [x0 - 0.4375],
            [x0 ** 2 - 0.888888888888889 * x0 + 0.183006535947712],
            [x0 ** 3 - 1.35 * x0 ** 2 + 0.568421052631579 * x0
             -0.0736842105263152],
            [x0 ** 4 - 1.81818181818182 * x0 ** 3 + 1.16883116883117 * x0 ** 2
             -0.311688311688312 * x0 + 0.0287081339712913],
            [x0 ** 5 - 2.29166666666667 * x0 ** 4 + 1.99275362318841 * x0 ** 3
             -0.815217391304351 * x0 ** 2 + 0.155279503105591 * x0
             -0.0108695652173908],
#             [x0 ** 6 - 2.76923076923077 * x0 ** 5 + 3.04615384615386 * x0 ** 4
#              -1.6923076923077 * x0 ** 3 + 0.496655518394654 * x0 ** 2
#              -0.072240802675587 * x0 + 0.00401337792642093]
        ])

        basis_size = len(true_var_orthopoly_vect)

        equal = [
            str(
                Eq(
                    N(sympify(expand(true_var_orthopoly_vect[i])), tol),
                    N(sympify(expand(self.beta_var.var_orthopoly_vect[i])), tol)
                )
            ) for i in range(basis_size)
        ]

        eval_loc = locals().copy()
        eval_glob = globals().copy()

        evaled = np.array([
            eval(equal[i], eval_loc, eval_glob) for i in range(len(equal))
        ])

        self.assertTrue(
            evaled.all(),
            msg='BetaVariable generate_orthopoly is not correct'
        )
Пример #17
0
    def get_mean(self):
        """
        Returns the mean of a DiscreteVariable.
        """
        decimals = 30
        if not hasattr(self, 'mean'):
            self.mean = np.sum(self.x_values * self.probabilities)

        return N(self.mean, decimals)
Пример #18
0
 def __str__(self):
     rounded_df = N(diff(self.cumulative_density_function(self.t), self.t),
                    8)
     s = '({:.3f}, {:.3f}): dF/dt = {}'.format(self.support_start,
                                               self.support_end, rounded_df)
     if self.point_mass > 0:
         s += '; Point mass of {:G} at {:.3f}'.format(
             self.point_mass, self.support_end)
     return s
Пример #19
0
def sourdough_pct_adjust_fnc(levain_water, levain_hyd, dough_weight):
    from sympy import Eq, solve, symbols, N
    x = symbols('x')
    water_calc = N(
        Eq((x + levain_water) - ((x + levain_water) / (1 + levain_hyd)),
           levain_water), 1)
    flour = solve(water_calc, x)
    levain_weight = levain_water + int(flour[0])
    return (levain_weight / dough_weight)
Пример #20
0
    def test_recursive_var_basis(self):
        """
        Testing the general Variable recursive_var_basis for several
        distributions and ensuring that the orthogonal polynomials are correct.
        
        Verified by hand.
        """
        tol = 1e-6
        x0 = symbols('x0')

        # region: scipy.stats.invgauss, mu=3
        true_var_orthopoly_vect = Matrix([
            [1], [x0 - 3], [x0 ** 2 - 33 * x0 + 63],
            [x0 ** 3 - 98.1 * x0 ** 2 + 1671.3 * x0 - 2481.3],
#             [x0 ** 4 - 198.8157 * x0 ** 3 + 9859.4203 * x0 ** 2
#              -114968.4815 * x0 + 143304.1996]
        ])

        basis_size = len(true_var_orthopoly_vect)

        equal = [
            str(
                Eq(
                    N(sympify(expand(true_var_orthopoly_vect[i])), tol),
                    N(
                        sympify(expand(self.invgauss_var.var_orthopoly_vect[i])),
                        tol
                    )
                )
            ) for i in range(basis_size)
        ]

        eval_loc = locals().copy()
        eval_glob = globals().copy()

        evaled = np.array([
            eval(equal[i], eval_loc, eval_glob) for i in range(len(equal))
        ])

        self.assertTrue(
            evaled.all(),
            msg='Variable recursive_var_basis is not correct'
        )
Пример #21
0
 def stone(A,F,C,L,rho):
         """ computation of stoneley velocity """
         
         x = symbols('x')
         seq  = x + (((x-L)/(x-A))**.5)*((C*(x-A)+F**2)/(C*L)**.5)
         sol = nsolve(seq,0)
         csol = N(sol,n=12, chop=True)
         check = seq.subs(x,csol)
         velocity = (csol/rho)**.5
         return(csol,check,velocity)   
Пример #22
0
def c6():
    x = symbols("x")
    lst = np.arange(5, 50, 5)
    err = np.empty(10)
    for i, n in enumerate(lst):
        integral = N(integrate(x**n * exp(x - 1), (x, 0, 1)))
        subfact = (-1)**n * subfactorial(n) + (-1)**(n + 1) * factorial(n) / e
        err[i] = np.abs(integral - subfact)
    plt.plot(np.log(err))
    plt.show()
Пример #23
0
 def equalcall_old(self, ins, out=None):
     try:
         expr = N(
             parse_expr(self.out.text,
                        transformations=transformations,
                        evaluate=True))
         tex = str(expr)
         self.out.text = tex
     except:
         pass
Пример #24
0
def calculate_microwave_ME(state1,
                           state2,
                           reduced=False,
                           pol_vec=np.array((0, 0, 1))):
    """
    Function that evaluates the microwave matrix element between two states, state1 and state2, for a given polarization
    of the microwaves
    
    inputs:
    state1 = an UncoupledBasisState object
    state2 = an UncoupledBasisState object
    reduced = boolean that determines if the function returns reduced or full matrix element
    pol_vec = np.array describing the orientation of the microwave polarization in cartesian coordinates
    
    returns:
    Microwave matrix element between state 1 and state2
    """

    #Find quantum numbers for ground state
    J = float(state1.J)
    mJ = float(state1.mJ)
    I1 = float(state1.I1)
    m1 = float(state1.m1)
    I2 = float(state1.I2)
    m2 = float(state1.m2)

    #Find quantum numbers of excited state
    Jprime = float(state2.J)
    mJprime = float(state2.mJ)
    I1prime = float(state2.I1)
    m1prime = float(state2.m1)
    I2prime = float(state2.I2)
    m2prime = float(state2.m2)

    #Calculate reduced matrix element
    M_r = (N(wigner_3j(J, 1, Jprime, 0, 0, 0)) * np.sqrt(
        (2 * J + 1) * (2 * Jprime + 1)) *
           float(I1 == I1prime and m1 == m1prime and I2 == I2prime
                 and m2 == m2prime))

    #If desired, return just the reduced matrix element
    if reduced:
        return float(M_r)
    else:
        p_vec = {}
        p_vec[-1] = -1 / np.sqrt(2) * (pol_vec[0] + 1j * pol_vec[1])
        p_vec[0] = pol_vec[2]
        p_vec[1] = +1 / np.sqrt(2) * (pol_vec[0] - 1j * pol_vec[1])

        prefactor = 0
        for p in range(-1, 2):
            prefactor += (-1)**(p - mJ) * p_vec[p] * float(
                wigner_3j(J, 1, Jprime, -mJ, -p, mJprime))

        return prefactor * float(M_r)
Пример #25
0
    def position_to_space_group(self, filepath, tolerance, file_type, x, y, z):
        '''Given a set of atomic positions, this function will look through each space group and see if it fits given a tolerance'''
        df = np.loadtxt(filepath, delimiter='/n', dtype=str)
        data = []
        #Only looks at real space unit cell in units of angstroms
        for i in df:
            if 'RECIP-PRIMVEC' in i:
                break
            elif 'CONVCOORD' in i or len(data):
                data.append(list(filter(None, i.split(' '))))

        #Identifies how many of each atom there are and goes from angstoms to crystals vectors
        atomic_numbers = {}
        transformed_data = []

        for i in data[2:]:
            #print(i)
            j = [float(item) for item in i]
            j[1] = N(j[1] / x, 4)
            j[2] = N(j[2] / y, 4)
            j[3] = N(j[3] / z, 4)
            transformed_data.append(j)

            if i[0] not in atomic_numbers.keys():
                atomic_numbers[i[0]] = 1
            else:
                atomic_numbers[i[0]] += 1

        #Finds all space group position files stored and iterates over them
        space_group_files = [
            f for f in os.listdir('../cryspos_storage/')
            if os.path.isfile(os.path.join('../cryspos_storage/', f))
        ]

        for i in space_group_files:
            space_group = i[:i.find('.')]
            wyckoff_list = self.give_wyckoff_numbers(space_group)
            for j in wyckoff_list:
                for k in atomic_numbers.keys():
                    if int(j[:-1]) == int(k) or int(
                            j[:-1]) == int(k) * 2 or int(j[:-1]) == int(k) * 3:
                        print('it happened {} {}'.format(space_group, j))
Пример #26
0
    def test_build(self):
        """
        Testing MatrixSystem form_norm_sq for a system with 5 common
        variable types.

        This example is from a well-tested test case.
        """
        x0 = symbols('x0')
        x1 = symbols('x1')
        x2 = symbols('x2')
        x3 = symbols('x3')
        x4 = symbols('x4')

        # region: symbolic basis
        true_var_basis_vect_symb = Matrix([[
            1, x0, x1, x2 - (1 / 3), x3 - 0.2, x4 - 1.0, x0**2 - 1.0, x0 * x1,
            x0 * (x2 - (1 / 3)), x0 * (x3 - 0.2), x0 * (x4 - 1),
            1.5 * x1**2 - 0.5, x1 * (x2 - (1 / 3)),
            x1 * (x3 - 0.2), x1 * (x4 - 1), x2**2 - (4 / 3) * x2 + (2 / 9),
            (1 * x2 - (1 / 3)) * (x3 - 0.2),
            (1 * x2 - (1 / 3)) * (x4 - 1), x3**2 - (2 / 3) * x3 + (1 / 21),
            (1 * x3 - 0.2) * (x4 - 1), x4**2 - 4 * x4 + 2
        ]])

        # endregion: symbolic basis

        basis_size = len(true_var_basis_vect_symb)

        equal = [
            str(
                Eq(N(sympify(expand(true_var_basis_vect_symb[i])), self.tol),
                   N(sympify(expand(self.var_basis_vect_symb[i])), self.tol)))
            for i in range(basis_size)
        ]

        eval_loc = locals().copy()
        eval_glob = globals().copy()

        evaled = np.array(
            [eval(equal[i], eval_loc, eval_glob) for i in range(len(equal))])

        self.assertTrue(evaled.all(), msg='MatrixSystem build is not correct')
Пример #27
0
def dipole_trans_oper(l1, l2):
    from sympy import N

    n1, n2 = 2 * l1 + 1, 2 * l2 + 1
    op = np.zeros((3, n1, n2), dtype=np.complex128)
    for i1, m1 in enumerate(range(-l1, l1 + 1)):
        for i2, m2 in enumerate(range(-l2, l2 + 1)):
            tmp1 = clebsch_gordan(l2, 1, l1, m2, -1, m1)
            tmp2 = clebsch_gordan(l2, 1, l1, m2, 1, m1)
            tmp3 = clebsch_gordan(l2, 1, l1, m2, 0, m1)
            tmp1, tmp2, tmp3 = N(tmp1), N(tmp2), N(tmp3)
            op[0, i1, i2] = (tmp1 - tmp2) * np.sqrt(2.0) / 2.0
            op[1, i1, i2] = (tmp1 + tmp2) * 1j * np.sqrt(2.0) / 2.0
            op[2, i1, i2] = tmp3
    op_spin = np.zeros((3, 2 * n1, 2 * n2), dtype=np.complex128)
    for i in range(3):
        op_spin[i, 0:2 * n1:2, 0:2 * n2:2] = op[i]
        op_spin[i, 1:2 * n1:2, 1:2 * n2:2] = op[i]

    return op_spin
Пример #28
0
def Ysigma(l1, j1, l2, j2, l, s, k):
    """
    < l1, j1 || [Y_l sigma_s]_k || l2, j2 >
    Note: all inputs are not not doubled
    """
    sfact = np.sqrt(2.0)
    if (s == 1): sfact = np.sqrt(6.0)
    return np.sqrt(float(
        (2 * j1 + 1) * (2 * j2 + 1) *
        (2 * k + 1))) * N(wigner_9j(l1, 0.5, j1, l2, 0.5, j2, l, s, k,
                                    prec=8)) * Yl_red(l1, l2, l) * sfact
Пример #29
0
def is_result_minimal_balanced(result):
    
    # collection is not minimal balanced, if result isn't conclusive / not an absolute value
    if result is None:
        return False
    
    for _, val in result.items():
        if type(N(val)) is not Float:
            return False
        if val.is_zero or val.is_negative:
            return False
    return True
Пример #30
0
 def print_state(self):
     for amp, basis_state in self.data:
         if amp > 0: print('+', end="")
         if basis_state.isCoupled:
             F = rat(basis_state.F)
             mF = rat(basis_state.mF)
             F1 = rat(basis_state.F1)
             J = rat(basis_state.J)
             I1 = rat(basis_state.I1)
             I2 = rat(basis_state.I2)
             print('{:.4f}'.format(N(amp))+' x '+"|F = %s, mF = %s, F1 = %s, J = %s, I1 = %s, I2 = %s>"\
                   %(F,mF,F1,J,I1,I2))
         elif basis_state.isUncoupled:
             J = rat(basis_state.J)
             mJ = rat(basis_state.mJ)
             I1 = rat(basis_state.I1)
             m1 = rat(basis_state.m1)
             I2 = rat(basis_state.I2)
             m2 = rat(basis_state.m2)
             print('{:.4f}'.format(N(amp))+' x '+"|J = %s, mJ = %s, I1 = %s, m1 = %s, I2 = %s, m2 = %s>"\
                   %(J,mJ,I1,m1,I2,m2))