示例#1
0
def slice_sample(symbol, distr, prev_x=None, domain=sm.S.Reals, __cache={}):
    """
    Return a randomly chosen value of x in domain from distr.
    """
    
    distr = distr.subs(symbol, SLICE_X)
    sm.pretty_print(distr)
    
    if prev_x == None:
        prev_x = random_from_set(max_univariate_value(distr, SLICE_X, domain))
    
    free_symbols = distr.free_symbols
    
    if len(free_symbols) > 1:
        others = []
        others.extend(free_symbols)
        others.remove(SLICE_X)
        distr = bay.without(distr, others) #get marginal distribution
    
    if not (distr, domain) in __cache:
        __cache[distr, domain] = sm.solveset(distr >= SLICE_Y, SLICE_X, domain=domain)
    at_least_set = __cache[distr, domain]
    
    max_y = distr.subs(SLICE_X, prev_x).evalf()
    y = nm.random.rand() * max_y
    x_slice = at_least_set.subs(SLICE_Y, y).reduce().intersection(domain)
    sm.pretty_print(x_slice)
    #x_slice = sm.solveset(distr >= y, symbol, domain=domain).intersection(domain)
    return random_from_set(x_slice)
示例#2
0
def _variable_force_(fx, lower_bound, upper_bound,
                     variable_of_integration) -> object:
    """Work Done by Variable Force:

    we need to recall the mass-density formula of a one-dimensional object,
    as well as how to calculate the work done on an object by a variable force.

    Linear density of the string is equal to the mass divided by the length
    of the string:

    - p = m/L, where m is mass and L is length of the object.

    As the string is wound up, the portion of the cable that is hanging down
    decreases. The mass of the cable alone can therefore be expressed as
    the linear density multiplied by x, the length of the hanging portion
    of the cable. Since we also know that F=ma and the acceleration is equal
    to g, the force from the cable alone is equal to:

    - F(x) = ρxg

    The force from the weight of the crate is equal to its mass multiplied
    by g. The total force is therefore:

    - F(x) = pxg + pL

    The mass m of a one-dimensional object oriented along the x-axis over the
    interval [a,b] is given by:

    - m = ∫ [a, b] ρ(x) dx,

    where ρ(x) is the linear density of the object at a point x in the interval.
    When linear density is constant, this simplifies to:

    - m = ∫ [a, b] ρ dx.

    If a variable force F(x) moves an object in a positive direction along the
    x-axis from point a to point b, then the work done on the object is:

    - W = ∫ [a, b] F(x) dx.

    :param fx:
    :param lower_bound:
    :param upper_bound:
    :param variable_of_integration:
    :return:
    """
    _l_ = lower_bound
    _u_ = upper_bound
    _var_ = variable_of_integration
    _work_ = Integral(fx, (_var_, _l_, _u_))
    _work_sol_ = _work_.doit()
    print("\nWork Integral: \n")
    pretty_print(_work_)
    print("\nWork = \n")
    pretty_print(_work_sol_)
    return _work_sol_
示例#3
0
def _circle_(radius) -> object:
    """Area = π * r^2
    :param radius: The radius of the circle
    """
    print("\n")
    print('Radius: \n')
    pretty_print(radius)
    area = pi * radius ** 2
    print('\nArea of circle: \n')
    pretty_print(area)
    return area
示例#4
0
def _mean_value_(fx, lower_bound, upper_bound,
                variable_of_integration, average_rate_change=None) -> object:
    """The Mean Value Theorem:

    Let f be a function such that:

    1. It is continuous on the closed interval [a, b].
    2. It is differentiable on the open interval (a, b).

    Then there is (at least) a number c in (a, b) such that

    -   f'(c) = [ f(b) - f(a) ] / [ b - a ]

    Comment: Notice that the left side is the instantaneous rate of
    change / slope of the tangent line at c, while the right side is
    the average rate of change / slope of the secant line from a to b.
    Thus the theorem guarantees that there is at least one place in (a, b)
    where the tangent line there is parallel to the secant line connecting
    the points (a, f (a)) and (b, f (b)) on the curve y = f (x).

    :param fx:
    :param lower_bound:
    :param upper_bound:
    :param variable_of_integration:
    :param average_rate_change:
    :return:
    """
    a = lower_bound
    b = upper_bound
    _var_ = variable_of_integration
    _area_ = Integral(fx, (_var_, a, b))
    avg_roc = average_rate_change
    if avg_roc is not None:
        _mean_avg_roc_ = Fraction(1 / (b - a)).limit_denominator() * avg_roc
    elif avg_roc is None:
        _mean_avg_roc_ = "None"
        _given_c = "None"
    _mean_value_theorem_of_integral_ = Fraction(1 / (b - a)).limit_denominator() * _area_.doit()
    if _mean_value_theorem_of_integral_ > 0:
        c = solve(fx - _mean_value_theorem_of_integral_)
    elif _mean_value_theorem_of_integral_ < 0:
        c = solve(fx + _mean_value_theorem_of_integral_)
    print("\nf({}) = \n".format(_var_))
    pretty_print(fx)
    print("\nIntegral: \n")
    pretty_print(_area_)
    print("\nMean value theorem for integral: \n")
    pretty_print(_mean_value_theorem_of_integral_)
    print("\nMean value given a rate of change: \n")
    pretty_print(_mean_avg_roc_)
    print("\nc from Mean value theorem for integral: \n")
    pretty_print(c)
示例#5
0
def sp_derive():

    import sympy as sp

    vars = 'G_s, s_n, s_p_n, w_n, dw_n, ds_n, G_s, G_w, c, phi'

    syms = sp.symbols(vars)

    for var, sym in zip(vars.split(','), syms):
        globals()[var.strip()] = sym

    s_n1 = s_n + ds_n
    w_n1 = w_n + dw_n

    tau_trial = G_s * (s_n1 - s_p_n)

    print('diff', sp.diff(tau_trial, ds_n))

    print(tau_trial)

    sig_n1 = G_w * w_n1

    print(sig_n1)

    tau_fr = (c + sig_n1 * sp.tan(phi)) * \
        sp.Heaviside(sig_n1 - c / sp.tan(phi))

    print(tau_fr)

    d_tau_fr = sp.diff(tau_fr, dw_n)

    print(d_tau_fr)

    f_trial = sp.abs(tau_trial) - tau_fr

    print(f_trial)

    d_gamma = f_trial / G_s

    print('d_gamma')
    sp.pretty_print(d_gamma)

    print('d_gamma_s')
    sp.pretty_print(sp.diff(d_gamma, ds_n))

    print('tau_n1')
    tau_n1 = sp.simplify(tau_trial - d_gamma * G_s * sp.sign(tau_trial))
    sp.pretty_print(tau_n1)

    print('dtau_n1_w')
    dtau_n1_w = sp.diff(tau_n1, dw_n)
    sp.pretty_print(dtau_n1_w)

    print('dtau_n1_s')
    dtau_n1_s = sp.diff(d_gamma * sp.sign(tau_trial), ds_n)
    print(dtau_n1_s)

    s_p_n1 = s_p_n + d_gamma * sp.sign(tau_trial)

    print(s_p_n1)
示例#6
0
    def print_out_expression(self, expression_data, message):
        """
        prints out the message and the pretty printed version of expression_data

        also logs the message and latex of the expression_data in full_output
        """
        print("")
        print("")
        sympy_str = self.data_to_sympy_expression(expression_data)
        print(message)
        pretty_print(sympy_str)

        latex_str = latex(sympify(sympy_str))
        self.full_output.append({"message": message, "latex": latex_str})
def sp_derive():

    import sympy as sp

    vars = 'G_s, s_n, s_p_n, w_n, dw_n, ds_n, G_s, G_w, c, phi'

    syms = sp.symbols(vars)

    for var, sym in zip(vars.split(','), syms):
        globals()[var.strip()] = sym

    s_n1 = s_n + ds_n
    w_n1 = w_n + dw_n

    tau_trial = G_s * (s_n1 - s_p_n)

    print 'diff', sp.diff(tau_trial, ds_n)

    print tau_trial

    sig_n1 = G_w * w_n1

    print sig_n1

    tau_fr = (c + sig_n1 * sp.tan(phi)) * sp.Heaviside(sig_n1 - c / sp.tan(phi))

    print tau_fr

    d_tau_fr = sp.diff(tau_fr, dw_n)

    print d_tau_fr

    f_trial = sp.abs(tau_trial) - tau_fr

    print f_trial

    d_gamma = f_trial / G_s

    print 'd_gamma'
    sp.pretty_print(d_gamma)

    print 'd_gamma_s'
    sp.pretty_print(sp.diff(d_gamma, ds_n))

    print 'tau_n1'
    tau_n1 = sp.simplify(tau_trial - d_gamma * G_s * sp.sign(tau_trial))
    sp.pretty_print(tau_n1)

    print 'dtau_n1_w'
    dtau_n1_w = sp.diff(tau_n1, dw_n)
    sp.pretty_print(dtau_n1_w)

    print 'dtau_n1_s'
    dtau_n1_s = sp.diff(d_gamma * sp.sign(tau_trial), ds_n)
    print dtau_n1_s

    s_p_n1 = s_p_n + d_gamma * sp.sign(tau_trial)

    print s_p_n1
示例#8
0
def main():
    # Print with the [1 t t^2 ...] M [P0 P1 P2 ...]^T notation
    print compute_uniform_bspline_matrix(3)
    print
    print compute_uniform_bspline_matrix(4)
    print
    sp.pretty_print(cubic_sym_span_matrix())
    print
    nb_ctrlpts = 4
    res = cubic_open_placement_matrix(nb_ctrlpts)
    for i in xrange(nb_ctrlpts + 3):
        print res[:, :, i]
    print
    res = cubic_closed_placement_matrix(nb_ctrlpts)
    for i in xrange(nb_ctrlpts + 3):
        print res[:, :, i]
示例#9
0
def main ():
  # Print with the [1 t t^2 ...] M [P0 P1 P2 ...]^T notation
  print compute_uniform_bspline_matrix(3)
  print
  print compute_uniform_bspline_matrix(4)
  print
  sp.pretty_print(cubic_sym_span_matrix())
  print
  nb_ctrlpts = 4
  res = cubic_open_placement_matrix(nb_ctrlpts)
  for i in xrange(nb_ctrlpts+3):
    print res[:,:,i]
  print
  res = cubic_closed_placement_matrix(nb_ctrlpts)
  for i in xrange(nb_ctrlpts+3):
    print res[:,:,i]
示例#10
0
def equality():
    g = sympy.Symbol('g(x)')
    f = sympy.Symbol('f(x)')
    lam_0 = sympy.Symbol('lambda_0')
    alpha = sympy.Symbol('alpha')

    half = sympy.Rational(1, 2)
    lam = lam_0 - ((1 / alpha) * g)
    lagrangian = f + -(lam * g) + -alpha * half * ((lam - lam_0)**2)

    print("L(x, lambda) = ...")
    sympy.pretty_print(sympy.simplify(lagrangian))

    print("\n\n\n\n")
    print("lambda(i + 1) = ...")
    sympy.pretty_print(lam)
示例#11
0
    def print_out_equation(self, message, expression_data=None, sympy_ob=None):
        """
       logs equation and prints out equation in console
       can be from expression_data or a sympy equation object
        """
        print("")
        print("")
        if expression_data:
            sympy_data = self.data_to_sympy_equation(expression_data)
        if sympy_ob != None:
            sympy_data = sympy_ob
        print(message)
        pretty_print(sympy_data)

        latex_str = latex(sympify(sympy_data))
        self.full_output.append({"message": message, "latex": latex_str})
示例#12
0
def runge_kutta(f, t, y, h, m=4):
    '''Runge-Kutta method

    Examples:
        >>> ...
    '''
    # parameters
    𝜆s = sympy.symbols(f'𝜆1:{m+1}')
    𝛼s = sympy.symbols(f'𝛼2:{m+1}')
    𝛽s = [sympy.symbols(f'𝛽{i+2}(1:{i+2})') for i in range(m - 1)]
    # Ks
    Ks = [None] * m
    Ks[0] = h * f(t, y)
    for i in range(m - 1):
        t_ = t + 𝛼s[i] * h
        y_ = y + sum(𝛽 * K for 𝛽, K in zip(𝛽s[i], Ks[:i + 1]))
        result, _ = taylor_in_two_variables(f,
                                            t_,
                                            y_,
                                            t,
                                            y,
                                            m - 1,
                                            error=False)
        Ks[i + 1] = h * result
    # y_{n+1} - y_{n}
    Y = f(t, y)
    T = h * Y
    I = sympy.integrate(f(t, y), t)
    for i in range(m - 1):
        Y = sympy.diff(Y.subs(y, I), t).subs(I, y)
        T += h**(i + 2) / sympy.factorial(i + 2) * Y
    T = T.subs(I, y)
    # combine parameters
    R = sum(𝜆 * K for 𝜆, K in zip(𝜆s, Ks))
    T = (T - R).simplify()
    x = sympy.symbols('x')
    i = 1
    for j in range(m - 1, -1, -1):
        for k in range(j + 1):
            T = T.subs(sympy.diff(f(t, y), (t, k), (y, j - k)), x**i)
    coeffs = sympy.polys.poly(T, x).all_coeffs()
    sympy.pretty_print(tuple(filter(bool, coeffs)))
    return R
示例#13
0
def train_run(epochs):
    epochs=int(epochs)
    for epoch in range(epochs):
        tmodel.train()
        for batch_ids,(features,targets) \
        in enumerate(dataloaders['train']):        
            features=features.to(dev)
            targets=targets.to(dev).long()
            logits=tmodel(features)
            cost=tnnf.cross_entropy(logits,targets)
            optimizer.zero_grad(); cost.backward()
            optimizer.step()
            str1='epoch: %03d/%03d | batch: %03d/%03d | cost: %.4f'
            if not batch_ids%10:
                sp.pretty_print(str1%(epoch+1,epochs,batch_ids,
                                      len(dataloaders['train']),cost))
        tmodel.eval()
        with torch.set_grad_enabled(False):
            sp.pretty_print('epoch: %03d/%03d'%(epoch+1,epochs))
            str2='train acc/loss: %.2f%%/%.2f valid acc/loss: %.2f%%/%.2f'
            sp.pretty_print(str2%\
                  (model_acc(tmodel,dataloaders['train']),
                   epoch_loss(tmodel,dataloaders['train']),
                   model_acc(tmodel,dataloaders['valid']),
                   epoch_loss(tmodel,dataloaders['valid'])))
示例#14
0
def main():
    '''
    This is a "derivation" of the simple rule
    '''
    a = sympy.Symbol('a')
    b = sympy.Symbol('b')
    c = sympy.Symbol('c')

    t = sympy.Symbol('(t - t_0)')

    u_list = []
    eqns = []
    for n in range(3):
        u = sympy.Symbol('u_{}'.format(n))
        tt = t - n
        eqns.append((a * (tt ** 2)) + (b * tt) + c - u)
        u_list.append(u)

    sympy.pretty_print(eqns)

    soln = sympy.solve(eqns, [a, b, c])
    f = (soln[a] * (t * t)) + (soln[b] * t) + c
    sympy.pretty_print(f)

    df_dt = sympy.diff(f, t)
    sympy.pretty_print(sympy.factor(df_dt))
示例#15
0
def _radial_density_(px, radius, variable_of_integration) -> object:
    """

    We need to recall how to calculate the mass of a circular object
    from its radial density function.

    Let ρ(x) be an integrable function representing the radial density
    of a disk of radius r. Then the mass of the disk is given by:

    - m = ∫ [0, r] 2π x ρ(x) dx.

    :param px:
    :param radius:
    :param variable_of_integration:
    :return:
    """
    x, b = symbols('x, b')
    _l_ = 0
    _u_ = radius
    _var_ = variable_of_integration
    _mass_ = Integral(2 * pi * x * px, (_var_, _l_, _u_))
    _demo_ = Integral(2 * pi * x * px, (_var_, _l_, b))
    _mass_sol_ = _mass_.doit()
    print("\nIntegral mass: \n")
    pretty_print(_mass_)
    print("\nMass of the object: \n")
    pretty_print(_demo_.doit())
    print("\nMass of the object: \n")
    pretty_print(_mass_sol_)
    return [_mass_, _mass_sol_]
示例#16
0
def _linear_density_(px, lower_bound, upper_bound,
                     variable_of_integration) -> object:
    """

    Let R denote a region bounded above by the graph of a continuous function
    f(x), below by the x-axis, and on the left and right by the lines x = a
    and x = b, respectively. Let ρ denote the density of the associated lamina.
    Then we can make the following statements:

    - i. The mass of the lamina is:
        - m = ρ ∫ [a, b] f(x)dx

    - ii. The moments M_x and M_y of the lamina with respect to the x-axis and y-axes,
            respectively, are
        - M_x = ρ ∫ [a, b] [f(x)]^2/2 dx
        and
        - M_y = ρ ∫ [a, b] x f(x) dx

    - iii. The coordinates of the center of mass ( X̅, y̅ ) are:
        - X̅ = M_y/m  and  y̅ = M_x/m



    :param px:
    :param lower_bound:
    :param upper_bound:
    :param variable_of_integration:
    :return:
    """
    _l_ = lower_bound
    _u_ = upper_bound
    _var_ = variable_of_integration
    _mass_ = Integral(px, (_var_, _l_, _u_))
    _mass_sol_ = _mass_.doit()
    print("\nIntegral mass: \n")
    pretty_print(_mass_)
    print("\nMass of the object: \n")
    pretty_print(_mass_sol_)
    return [_mass_, _mass_sol_]
示例#17
0
def _volume_disk_(fx, lower_bound, upper_bound,
                  variable_of_integration) -> object:
    """The Disk Method:
If a region in the plane is revolved about a line in the same
plane, the resulting object is known as a solid of revolution.
For example, a solid right circular cylinder can be generated by
revolving a rectangle. Similarly, a solid spherical ball can be
generated by revolving a semi-disk. The line about which we
rotate the shape is called the axis of revolution.
The disk method is used when we rotate a single curve y = f(x)
around the x or y axis. Suppose that y = f(x) is a continuous
non-negative function on the interval [a, b].
The volume of the solid formed by revolving the region bounded by
the curve  y - f(x) and the x-axis between x = a and x = b about
the x-axis is given by:

- V = π ∫ [a,b] [ f(x) ]^2 dx

The cross section perpendicular to the axis of revolution has
the form of a disk of radius R = f(x).
Similarly, we can find the volume of the solid when the region
is bounded by the curve x = f(y) and the y-axis between y = c
and y = d, and is rotated about the y-axis. The resulting formula is:

- V = π ∫ [c, d] [ f(y)]^2 dy

    :param fx: f(x) is the function on the interval
    :param lower_bound:
    :param upper_bound:
    :param variable_of_integration:
    :return:
    """
    r = fx
    a = lower_bound
    b = upper_bound
    _v_ = variable_of_integration
    c, d = symbols('c, d')
    _area_ = ar.circle_(r)
    _integral_ = Integral(_area_, (_v_, c, d))
    _integral_sol = Integral(_area_, (_v_, a, b))
    _solution_ = _integral_sol.doit()

    print("\nVolume of the region, Integral notation: \n")
    pretty_print(_integral_sol)
    print(
        '\nThe antiderivative of the function with respect to {} is:\n'.format(
            _v_))
    pretty_print(_integral_.doit())
    print('\nVolume of the region is : \n')
    pretty_print(_solution_)
示例#18
0
from sympy import Symbol
from sympy.matrices import Matrix, eye, zeros, ones, diag
from sympy import pretty_print

from SymbolicCollisions.core.cm_symbols import *
from SymbolicCollisions.core.MatrixGenerator import MatrixGenerator
from SymbolicCollisions.core.printers import *

matrixGenerator = MatrixGenerator(ex_D2Q9, ey_D2Q9, None, moments_dict[f'D2Q9'])
Mraw = matrixGenerator.get_raw_moments_matrix()

Nraw = matrixGenerator.get_shift_matrix()

Traw = matrixGenerator.get_raw_x_shift_moments_matrix()

Nraw_alternative = Traw * Mraw.inv()
Nraw_alternative_simplified = Matrix([round_and_simplify(Nraw_alternative[i, :]) for i in range(len(ex_D2Q9))])
# print_as_vector(f1, 'f1')

pretty_print(Mraw)
pretty_print(Nraw)
pretty_print(Nraw_alternative)

示例#19
0
from sympy import symbols, solve, Eq, pretty_print
from sympy.physics.units import Quantity, mass, acceleration, power, velocity
from sympy.physics.units import convert_to
from sympy.physics.units import kilo
from sympy.physics.units import km, hour, m, s, kg, W
from sympy.physics.units.systems import SI

a = symbols("a")
m_ = Quantity("m")
v = Quantity("v")
W_ = Quantity("W")

SI.set_quantity_dimension(a, acceleration)

SI.set_quantity_dimension(m_, mass)
SI.set_quantity_scale_factor(m_, 1000*kg)

SI.set_quantity_dimension(v, velocity)
SI.set_quantity_scale_factor(v, 60*km/hour)

SI.set_quantity_dimension(W_, power)
SI.set_quantity_scale_factor(W_, 120*kilo*W)

eq = Eq(W_, m_*a*v)
result = solve(eq, a)[0]
pretty_print(result)

pretty_print(convert_to(result, m / s ** 2).n())


示例#20
0
from sympy import symbols

init_printing()

# let ve - orbital speed of Earth
# v0 - initial spaceship speed
# v  -  spaceship speed on 'exit' from Solar system
# Ms, Me - mass of the Sun and Earth resp
# R, r   - Earth orbit radius and Earth radius
ve, v, v0 = symbols('v_e v v_0')
G, Ms, Me = symbols('G M_s M_e')
R, r = symbols('R, r')

# For the Earth itself
eq_E = Eq(ve**2 / 2 - G * Ms / R, -G * Ms / R / 2)
pretty_print(eq_E)

# For the ship near the Earth and on "exit"
eq_ship = Eq(v0**2 / 2 - G * Ms / R - G * Me / r, v**2 / 2)
pretty_print(eq_ship)

res = solve([eq_E, eq_ship], v**2, G * Ms / R)

pretty_print(res)

# but for 1st space speed of 11 km/s we have
v1 = symbols('v1')
eq_v1 = Eq(v1**2 / 2 - G * Me / r, -G * Me / r / 2)
pretty_print(eq_v1)

# but for 2dn space speed
from SymbolicCollisions.core.cm_symbols import *
from SymbolicCollisions.core.printers import print_as_vector, get_print_symbols_in_indx_notation
from sympy import pretty_print

print("\n\n=== from raw moments to ortho moments ===\n")
T_raw_to_ortho = M_ortho_GS * Mraw_D2Q9.inv()
# pretty_print(T_raw_to_ortho)

print("\n\n=== relax raw moments in ortho space ===\n")
S_relax2 = T_raw_to_ortho.inv() * S_relax_MRT_GS * T_raw_to_ortho
pretty_print(S_relax2)

print("\n\n deja-vu! \n")
pretty_print(S_relax_hydro_D2Q9)

print("\n\n=== PRETTY CODE: relax relax_MRT_relax_raw_mom_into_ortho ===\n\n")

DF_in_str = 'f_in'  # symbol defining DF
mom_DF_str = 'm'
mom_relaxed_DF_str = 'm_relaxed'

print("CudaDeviceFunction void relax_MRT_relax_raw_mom_into_ortho("
      "real_t %s[9], "
      "real_t tau, "
      "\n{" % DF_in_str)

print("\nreal_t %s = 1./tau;" % omega_v)
print("\nreal_t %s[9]; real_t %s[9]; \n" % (mom_DF_str, mom_relaxed_DF_str))

populations = get_print_symbols_in_indx_notation(print_symbol=DF_in_str)
m_DF = get_print_symbols_in_indx_notation(print_symbol=mom_DF_str)
示例#22
0
from sympy import pretty_print, Eq, solve, symbols
from sympy.interactive import init_printing

init_printing()

g = 9.8
P = 0.025 * g
k = 15.3
m = 0.050
h = 0.09

delta_x = symbols('delta_x')
eq = Eq(m**2 / (P + m * g) * g * h, -m * delta_x + k / (2 * g) * delta_x**2)
pretty_print(eq)
solution = solve(eq, delta_x)
pretty_print(solution)

delta_x = solution[1]
result = h + delta_x
print("result is {0:.1f} cm".format(result * 100))
from sympy import Symbol
from sympy.matrices import Matrix, eye, zeros, ones, diag
from sympy import pretty_print
from SymbolicCollisions.core.DiscreteCMTransforms import get_DF
from SymbolicCollisions.core.cm_symbols import Shift_ortho_Straka_d2q5

"""
  See 
  'New Cascaded Thermal Lattice Boltzmann Method for simulations for advection-diffusion and convective heat transfer'
  by K.V. Sharma, R. Straka, F.W. Tavares, 2017
"""

# Smat = get_shift_matrix(K_ortho_Straka_d2q5, ex_Straka_d2_q5, ey_Straka_d2_q5)
# pretty_print(Smat)

Smat = Shift_ortho_Straka_d2q5
k = get_DF(q=4, print_symbol='k')
Relax = diag(Symbol('w2'), Symbol('w3'), Symbol('w4'), Symbol('w5'))   #
cm_neq = get_DF(q=4, print_symbol='cm_neq')

k = Smat.inv()*Relax*cm_neq

pretty_print(k)
from SymbolicCollisions.core.cm_symbols import *
from SymbolicCollisions.core.DiscreteCMTransforms import get_DF
from SymbolicCollisions.core.printers import print_as_vector
from sympy import pretty_print


print("\n\n=== from raw moments to ortho moments ===\n")
T_raw_to_ortho = M_ortho_GS * Mraw_D2Q9.inv()
# pretty_print(T_raw_to_ortho)

print("\n\n=== relax raw moments in ortho space ===\n")
S_relax2 = T_raw_to_ortho.inv() * S_relax_MRT_GS*T_raw_to_ortho
pretty_print(S_relax2)

print("\n\n deja-vu! \n")
pretty_print(S_relax_hydro_D2Q9)


print("\n\n=== PRETTY CODE: relax relax_MRT_relax_raw_mom_into_ortho ===\n\n")

DF_in_str = 'f_in'  # symbol defining DF
mom_DF_str = 'm'
mom_relaxed_DF_str = 'm_relaxed'

print("CudaDeviceFunction void relax_MRT_relax_raw_mom_into_ortho("
      "real_t %s[9], "
      "real_t tau, "
      "\n{"
      % DF_in_str)
示例#25
0
from sympy.interactive import init_printing
from sympy.physics.units import Quantity
from sympy.physics.units import convert_to
from utils import *

init_printing()

E = Quantity("E")
c = Quantity("c")

set_quantity(E, un.energy, 2.15e12 * un.kilo * un.watts * un.hour)
set_quantity(c, un.speed, 3.00e8 * un.m / un.s)
E = convert_to(E, un.joule).n()

print('Heavy water:')
pretty_print(Eq(symbols('D2O'), 2 * symbols('D') + symbols('O')))

print('Let nucleosynthesis reaction be like below:')
pretty_print(Eq(symbols('D'), symbols('H_^2')))
pretty_print(Eq(symbols('H^2') + symbols('H^2'), symbols('He_^4')))

print('a).')
m = symbols('m')
pretty_print(Eq(m, symbols('E') / c**2))
m = E / c**2
m = convert_to(m, un.kg).n()

pretty_print("Energy to mass  : {}".format(m))

print('b).')
M_D = Quantity('M_D')
示例#26
0
import sympy as sp
import matplotlib.pyplot as plt
from matplotlib import rcParams, animation
rcParams['font.family'] = 'serif'
rcParams['font.size'] = 16
plt.ion()
from sympy import init_session
init_session()
from sympy.utilities.lambdify import lambdify


x, nu, t = sp.symbols('x nu t')
phi = sp.exp((-(x-4*t)**2)/(4*nu*(t+1))) + \
sp.exp(-((x-4*t-2*np.pi)**2)/(4*nu*(t+1)))
phi
sp.pretty_print (phi)

phiprime = phi.diff(x)
phiprime
sp.pretty_print (phiprime)

u = -2*nu*(phiprime/phi)+4
print(u)

ufunc = lambdify((t,x,nu),u)
print('The value of u at t=1, x=4, nu=3 is {}.'.format(ufunc(1,4,3)))

#Variable Declarations
nx = 101
nt = 100
dx = 2*np.pi/(nx-1)
示例#27
0
res_v = solve([
    Eq(s1,
       v * sqrt(2) * t),
    Eq(v * sqrt(2), 2 * g * t),
    Eq(delta_h, g * t**2 / 2),
    Eq((v * sqrt(2) / 2)**2, 2 * g * delta_h)
], v, t, delta_h)[1]

A = A.subs({"v": res_v[0]})

res_s2 = solve([
    Eq(s2,
       v * sqrt(2) / 2 * t),
    Eq(h,
       v * sqrt(2) / 2 * t + g * t**2 / 2),
    Eq(s, s1 + s2),
    Eq(v**2, res_v[0]**2)
], s2, s1, t, v)

s1 = res_s2[1][1]
A = A.subs({"s1": s1})
pretty_print(A)

n = 3
distances = [19.4, 60.0, 86.1]
masses = [7.26, 2.00, 0.81]

for i in range(n):
    print(A.subs({g: 9.81, m: masses[i], s: distances[i], h: 1.8}))
示例#28
0
f2 = Mraw_D2Q9.inv() * Nraw.inv() * cm
print_as_vector(f2, 'f2')


from numpy.testing import assert_almost_equal
for i in range(0):
    assert_almost_equal(f1[i], f2[i])


print("\n\n=== from raw moments to ortho moments ===\n")
T_raw_to_ortho = M_ortho_GS * Mraw_D2Q9.inv()

S_relax = S_relax_MRT_GS.subs({
            's_v': 0.0321,
            })

X1 = Nraw * T_raw_to_ortho * Mraw_D2Q9
X2 = T_raw_to_ortho * Nraw * Mraw_D2Q9

pretty_print(X1*cm)
pretty_print(X2*cm)

XX1 = Mraw_D2Q9.inv() * T_raw_to_ortho.inv() * Nraw.inv() * S_relax * Nraw * T_raw_to_ortho * Mraw_D2Q9
XX2 = Mraw_D2Q9.inv() * Nraw.inv() * T_raw_to_ortho.inv() * S_relax * T_raw_to_ortho * Nraw * Mraw_D2Q9


a1 = Nraw * Mraw_D2Q9 * cm
a2 = ShiftMat*M_ortho_GS.inv()*cm

示例#29
0
from SymbolicCollisions.core.DiscreteCMTransforms import get_DF
from SymbolicCollisions.core.cm_symbols import *
from sympy.matrices import Matrix
from sympy import pretty_print, exp
from SymbolicCollisions.core.cm_symbols import ex_D2Q9, ey_D2Q9
from SymbolicCollisions.core.printers import print_as_vector
import numpy as np
from sympy.utilities.iterables import flatten


DF = get_DF('g')
# pretty_print(M_ortho_GS*DF)


print("\n\n=== is orthogonal and orthonormal? ===\n")
pretty_print(M_ortho_GS*M_ortho_GS.transpose())  # TODO: why not M_ortho_GS.transpose()* M_ortho_GS ?!
pretty_print(K_ortho_Geier.transpose()*K_ortho_Geier)



print("\n\n=== from raw moments to ortho moments ===\n")
T_raw_to_ortho = M_ortho_GS * Mraw_D2Q9.inv()
pretty_print(T_raw_to_ortho)

print("\n\n=== relax raw moments in ortho space and go back to raw moments ===\n")
S_relax_ortho = T_raw_to_ortho.inv() * S_relax_MRT_GS * T_raw_to_ortho
pretty_print(S_relax_ortho)


# print("\n\n=== normalize matrix  ===\n")
# from sklearn.preprocessing import normalize
示例#30
0
    f2 = -x**7 + 2*x**3*y + y**3
    f3 = (y**2-x**2)*(x-1)*(2*x-3) - 4*(x**2+y**2-2*x)**2
    f4 = y**2 + x**3 - x**2
    f5 = (x**2 + y**2)**3 + 3*x**2*y - y**3
    f6 = y**4 - y**2*x + x**2
    f7 = y**3 - (x**3 + y)**2 + 1
    f8 = (x**6)*y**3 + 2*x**3*y - 1
    f9 = 2*x**7*y + 2*x**7 + y**3 + 3*y**2 + 3*y
    f10= (x**3)*y**4 + 4*x**2*y**2 + 2*x**3*y - 1

    f  = f2
    a  = 0
    N  = 10

    print "Curve:\n"
    sympy.pretty_print(f)
    
    PT = puiseux(f,x,y,a,degree_bound=N,parametric=T,version='rational')
    Px = puiseux(f,x,y,a,degree_bound=N,parametric=False,version='rational')

    sympy.pprint(PT)
    sympy.pprint(Px)

#     import cProfile, pstats
#     cProfile.run(
#     "P = puiseux(f,x,y,a,degree_bound=N,parametric=False,version='rational')"
#     ,'puiseux.profile')
#     p = pstats.Stats('puiseux.profile')
#     p.strip_dirs()
#     p.sort_stats('time').print_stats(15)
#     p.sort_stats('cumulative').print_stats(15)
示例#31
0
def to_sparse(matrix):
    entries = {}
    for row in range(matrix.rows):
        for col in range(matrix.cols):
            val = matrix[row, col]

            # Exactly uniquely zero! Not almost zero! No bullshit!
            if val != 0:
                entries[(row, col)] = val

    return sparse.SparseMatrix(matrix.shape, entries)


if __name__ == '__main__':
    a = vector('a', 5)
    b = vector('b', 5)
    sympy.pretty_print(a)

    A = matrix('A', (5, 5))
    sympy.pretty_print(A)

    sympy.pretty_print(norm(a - b))

    sA = to_sparse(A)
    sb = to_sparse(b)
    sparse.diagstack(sA, sA, sA, sA, sb).spy()

    # from matplotlib import pyplot as plt
    # plt.show()
示例#32
0
def print_taylor(my_function, x0=0, n=5, by=1, what_to_diff=sy.Symbol('x')):
    # Approximate up until n starting from 1 and using steps of by
    for j in range(1, n + 1, by):
        func = taylor(my_function, x0, j, what_to_diff)
        print('\n\nTaylor expansion at n=%s' % str(j))
        pretty_print(func)
示例#33
0
img_files=['00_05_001.png','00_06_001.png']
img_size=64; data_img_size=160
batch_size2=8; img_size2=64
max_img_size=224; steps=60

""" ## ✒️ &nbsp; Data Loading and Preprocessing"""

def get_file(file_path,file_name):
    input_file=urllib.request.urlopen(file_path+file_name)
    output_file=open(file_name,'wb')
    output_file.write(input_file.read())
    output_file.close(); input_file.close()
get_file(file_path,file_name)
with h5py.File(file_name,'r') as f:
    keys=list(f.keys())
    sp.pretty_print('file keys: '+', '.join(keys))
    images=np.array(f[keys[0]])
    images=tf.image.resize(
        images,[data_img_size,data_img_size]).numpy()
    labels=np.array(f[keys[1]],dtype='float32')
    names=[el.decode('utf-8') for el in f[keys[2]]]
    f.close()

N=labels.shape[0]; n=int(.1*N); num_classes=len(names)
shuffle_ids=np.arange(N)
np.random.RandomState(12).shuffle(shuffle_ids)
images=images[shuffle_ids]; labels=labels[shuffle_ids]
x_test,x_valid,x_train=images[:n],images[n:2*n],images[2*n:]
y_test,y_valid,y_train=labels[:n],labels[n:2*n],labels[2*n:]
df=pd.DataFrame(
    [[x_train.shape,x_valid.shape,x_test.shape],
示例#34
0
from sympy import symbols, log, sqrt, pretty_print

S, E, r, σ, T, t = symbols('S, E, r, σ, T, t')

numerator_l = log(S / E) + r * (T - t)
numerator_r = σ**2 * (T - t) / 2
denominator = σ * sqrt(T - t)

d1 = (numerator_l + numerator_r) / denominator
d2 = (numerator_l - numerator_r) / denominator

# Process:
__Δ = d1 - d2
#   = 2*numerator_r / denominator
#   = σ**2*(T-t) / σ*sqrt(T-t)
#   = σ * sqrt(T-t)
#   =     _______
#     σ⋅╲╱ T - t

if __name__ == "__main__":
    pretty_print(__Δ.simplify())
示例#35
0
m[1].append(n * 2 * (x * y + w * z))
m[1].append(1 - n * 2 * (x**2 + z**2))
m[1].append(n * 2 * (y * z - w * x))
m[1].append(0)

m.append([])
m[2].append(n * 2 * (x * z - w * y))
m[2].append(n * 2 * (y * z + w * x))
m[2].append(1 - n * 2 * (x**2 + y**2))
m[2].append(0)

m.append([])
m[3] = [0, 0, 0, 1]

A = sym.Matrix(m)
sym.pretty_print(A)
vec = sym.Matrix([0, 0, 1, 0])  # col vec

#sym.pretty_print(vec)

expr = A * vec

s = expr.subs([(w, 0.854), (x, -0.546), (y, 0.354), (z, 0.354)])
sp = expr.subs([(w, 0.854), (x, -0.55), (y, 0.354), (z, 0.354)])
dx = -0.55 - (-0.546)
ds = sp - s
sym.pretty_print(s)
sym.pretty_print(sp)
sym.pretty_print(ds)

point = sym.Matrix([a, b, c, 0])
from sympy import Symbol
from sympy.matrices import Matrix, eye, zeros, ones, diag
from sympy import pretty_print
from SymbolicCollisions.core.cm_symbols import Shift_ortho_Straka_d2q5
from SymbolicCollisions.core.printers import get_print_symbols_in_indx_notation

"""
  See 
  'New Cascaded Thermal Lattice Boltzmann Method for simulations for advection-diffusion and convective heat transfer'
  by K.V. Sharma, R. Straka, F.W. Tavares, 2017
"""

# Smat = get_shift_matrix(K_ortho_Straka_d2q5, ex_Straka_d2_q5, ey_Straka_d2_q5)
# pretty_print(Smat)

Smat = Shift_ortho_Straka_d2q5
k = get_print_symbols_in_indx_notation(q=4, print_symbol='k')
Relax = diag(Symbol('w2'), Symbol('w3'), Symbol('w4'), Symbol('w5'))   #
cm_neq = get_print_symbols_in_indx_notation(q=4, print_symbol='cm_neq')

k = Smat.inv()*Relax*cm_neq

pretty_print(k)
示例#37
0
Hx2 = 4*x*s.sqrt(omega)*x*s.sqrt(omega) - 2
Hx3 = 8*x*s.sqrt(omega)*x*s.sqrt(omega)*x*s.sqrt(omega) - 12*x*s.sqrt(omega)
Hy0 = 1
Hy1 = 2*y*s.sqrt(omega)
Hy2 = 4*y*s.sqrt(omega)*y*s.sqrt(omega) - 2
Hy3 = 8*y*s.sqrt(omega)*y*s.sqrt(omega)*y*s.sqrt(omega) - 12*y*s.sqrt(omega)

phi  = exp(-omega*(x*x+y*y)/2)
phi0 = phi*Hx0*Hy0
phi1 = phi*Hx1*Hy1
phi2 = phi*Hx2*Hy2
phi3 = phi*Hx3*Hy3


print("Grad H0")
s.pretty_print(((s.diff(phi0,x)/phi)).simplify().simplify())
print("\nGrad H1")
s.pretty_print(((s.diff(phi1,x)/phi)).simplify().simplify())
print("\nGrad H2")
s.pretty_print(((s.diff(phi2,x)/phi)).simplify().simplify())
print("\nGrad H2")
s.pretty_print(((s.diff(phi3,x)/phi)).simplify().simplify())
print("-----------------------------------------------------------------------")
print("Lap H0")
s.pretty_print(((s.diff(s.diff(phi0,x),x)/phi)+s.diff(s.diff(phi0,y),y)/phi).simplify().simplify())
print("\nLap H1")
s.pretty_print(((s.diff(s.diff(phi1,x),x)/phi)+s.diff(s.diff(phi1,y),y)/phi).simplify().simplify()) 
print("\nLap H2")
s.pretty_print(((s.diff(s.diff(phi2,x),x)/phi)+s.diff(s.diff(phi2,y),y)/phi).simplify().simplify())
print("\nLap H3")
s.pretty_print(((s.diff(s.diff(phi3,x),x)/phi)+s.diff(s.diff(phi3,y),y)/phi).simplify().simplify())
示例#38
0
文件: st_SPW.py 项目: kvdum/st_code
                r'- T_{i}_b(tau)) + {dTbi_TopDown} * {sumA_k}) + G_c * c_v * ({A_c} * '
                r'(T_2_c - T_{i}_b(tau)) + {Tbi_DownTop} * {sumA_c}) + 3.6 * '
                r'K_{i}_b * F_{i}_b * (T_n - T_{i}_b(tau))')
 T_tau_template = r'T_{i}_b(tau)'
 eqs = []
 #T_tau_list = []
 tau = smp.Symbol('tau')
 for i in range(1, n+1):
     eq_left = smp.S(eq_left_template.format(i=i, A_k=A_k(i), dTbi_TopDown=dTbi_TopDown(i), 
                                   sumA_k=sumA_k(i), A_c=A_c(i), 
                                   Tbi_DownTop=Tbi_DownTop(i), sumA_c=sumA_c(i)) )
     eq_right = smp.S(eq_right_template.format(i=i))
     eq = smp.Eq(eq_left, eq_right.diff(tau))
     ##T_tau = smp.Function(T_tau_template.format(i=i))
     #T_tau_list.append(T_tau)
     smp.pretty_print(eq)
     eqs.append(eq)
 
 if n == 99:
     rhs = []
     for req in smp.dsolve(eqs):
         print(req)
         rhs.append(smp.Eq(req.rhs.subs(tau, 0), 15))
     print(" Розв'язок задачі Коші: ".center(50, '-'))
     C1, C2, C3 = smp.symbol('C1 C2 C3')
     print(smp.solve(rhs), [C1, C2, C3])
     
     #smp.pretty_print()
     
     print("Розв'язок символьним (аналітичним) методом завершено!")
     raise SystemExit(0)
示例#39
0
import sympy as sp
import numpy as np

M = sp.Matrix(sp.var('m0 m1 m2 m3 m4 m5 m6 m7 m8')).reshape(3, 3)
r = sp.Matrix(sp.var('x y z'))
t = sp.Matrix(sp.var('t0 t1 t2'))

eq = M * r - t
sp.pretty_print(eq)

solution = [sp.solve(surface, z) for surface in eq]

vm = np.array(((1.0, 0.1, -0.1), (0.1, 1.0, -0.1), (-0.1, -0.1, 1.0))).reshape(9)
vt = (np.random.random(3) - 0.5) * 0.1

p = sp.Plot()
p[1] = solution[0][0].subs(zip(M[:], vm)).subs(zip(t[:], vt))
p[2] = solution[1][0].subs(zip(M[:], vm)).subs(zip(t[:], vt))
p[3] = solution[2][0].subs(zip(M[:], vm)).subs(zip(t[:], vt))
示例#40
0
from sympy import Eq, Function
from sympy import init_printing, pretty_print
from sympy import solve, simplify
from sympy import symbols

init_printing()

x, rho, pi, r, R, G = symbols('x rho pi r R G')

M = Function('M')(r)
a_0 = Function('a_0')(x)
a_1 = Function('a_1')(x)
a_2 = Function('a_2')(x)

eq_M = Eq(M, 4 * rho * pi * r**3 / 3)
pretty_print(eq_M)

M0 = eq_M.args[1].subs(r, R)
M2 = eq_M.args[1].subs(r, R / 4)

M1 = M0 - M2

eq_a_0 = Eq(a_0, a_1 + a_2)
pretty_print(eq_a_0)

eq_a_0 = eq_a_0.subs({
    a_0: G * M0 / (x + R)**2,
    a_2: G * M2 / (x + R + R / 4)**2
})
pretty_print(eq_a_0)
示例#41
0
from sympy.functions import exp
import sympy as s

alpha,beta,a,x1,x2,y1,y2,r12,r1,r2 = s.symbols('alpha beta a x1 x2 y1 y2 r12 r1 r2')

#r12 = s.sqrt((x1-x2)**2)
#r1  = x1**2
#r2  = x2**2
r12 = s.sqrt((x1-x2)**2 + (y1-y2)**2)
r1  = x1**2 + y1**2
r2  = x2**2 + y2**2
sep = x1 -x2
obr12 = 1+beta*r12
Exp1 = exp(-alpha*(r1+r2)/2)
Exp2 = exp(a*r12/(1+r12*beta))

s.pretty_print(s.diff(Exp1,x1))
print("\n\n\n")
s.pretty_print(s.diff(Exp2,x1))
#s.pretty_print(1/r12)
#print("\n")
#s.pretty_print(sep/obr12**2*s.diff(1/r12,x1))
#print("\n")
#s.pretty_print(1/obr12**2)
#print("\n")
#s.pretty_print(sep/r12*s.diff(1/obr12**2,x1))
else: 
	import hotshot
	prof = hotshot.Profile("profile.valgrind")
	prof.runcall(main)
	prof.close()


import sympy

t=sympy.Symbol("t")
mu=sympy.Symbol("mu")
sigma=sympy.Symbol("s")

normal=1./(sigma*sympy.sqrt(2*sympy.pi))*sympy.exp(-(t/2/sigma)**2)
print "normal", normal
sympy.pretty_print(normal)
print sympy.printing.latex(normal)

sine=sympy.exp(sympy.I * 2*sympy.pi*mu*t/nBins)
print "sine", sine
sympy.pretty_print(sine)

print "product", normal*sine
sympy.pretty_print(normal*sine)

integral = sympy.integrate(normal*sine,t)
print "integral", integral

sympy.Plot(integral.subs(sigma,standardDelay*1))

示例#43
0
@Docstring : Solve the quadratic equation.
@Require   : Python==3.7.6; sympy==1.4
@Result    : \\
Poly(C2*x**2 + C1*x + C0, x, domain='ZZ[C0,C1,C2]')
            ________________
           /              2
   C1    \/  -4*C0*C2 + C1
- ---- - -------------------
  2*C2           2*C2
            ________________
           /              2
   C1    \/  -4*C0*C2 + C1
- ---- + -------------------
  2*C2           2*C2
'''
from sympy import symbols, Poly, roots, pretty_print
from sympy.assumptions import assuming, Q

# variables declaration
degree = 2
C = symbols(f'C0:{degree+1}')  # C_0, C_1, ..., C_degree
x = symbols('x')  # x^0, x^1, ..., x^degree
# calculate roots
with assuming(Q.nonzero(C[-1]), *map(Q.complex, C[:-1])):
    quadratic_equation = Poly(reversed(C), x)
    solutions = roots(quadratic_equation)
# display results
pretty_print(quadratic_equation, use_unicode=False)
for solution in solutions:
    pretty_print(solution, use_unicode=False)