def get_freestream(circle_center, r, vel, aoa):
    aoa = sp.rad(aoa)
    zeta = sp.symbols('zeta', real=False)
    function1 = vel * zeta * (sp.cos(aoa) - 1j * sp.sin(aoa))
    function2 = vel * (r**2 / (zeta - circle_center)) * (sp.cos(aoa) +
                                                         1j * sp.sin(aoa))
    return function1 + function2
Пример #2
0
def rotation_matrix(theta: int,
                    axis='z',
                    unit: str = 'rad',
                    numpy: bool = False):
    """
    Create a z-axis rotation matrix given an angle.

    Parameters
    ----------
    theta : int
        Rotation about the z-axis
    axis : {'x', 'y', 'z'}
        Axis of rotation
    unit : {'rad', 'deg'}, optional
        Radians or degrees. By default 'rad'.
    numpy : bool, optional
        If True, return a Numpy array, otherwise return a sympy matrix.
        By default False.

    Returns
    -------
    {np.array, sp.Matrix}
        If `numpy` is True, will return rotation matrix as np.array. Otherwise,
        will return a sp.Matrix.

    """
    sin = sp.sin
    cos = sp.cos

    if unit == 'deg':
        theta = sp.rad(theta)

    R = sp.Matrix([[sp.cos(theta), -sp.sin(theta), 0],
                   [sp.sin(theta), sp.cos(theta), 0], [0, 0, 1]])
    return sp.matrix2numpy(R, dtype='float32') if numpy else R
Пример #3
0
def apply_grad_cartesian_tensor(grad_X, zmat_dist):
    """Apply the gradient for transformation to cartesian space onto zmat_dist.

    Args:
        grad_X (:class:`numpy.ndarray`): A ``(3, n, n, 3)`` array.
            The mathematical details of the index layout is explained in
            :meth:`~chemcoord.Cartesian.get_grad_zmat()`.
        zmat_dist (:class:`~chemcoord.Zmat`):
            Distortions in Zmatrix space.

    Returns:
        :class:`~chemcoord.Cartesian`: Distortions in cartesian space.
    """
    columns = ['bond', 'angle', 'dihedral']
    C_dist = zmat_dist.loc[:, columns].values.T
    try:
        C_dist = C_dist.astype('f8')
        C_dist[[1, 2], :] = np.radians(C_dist[[1, 2], :])
    except (TypeError, AttributeError):
        C_dist[[1, 2], :] = sympy.rad(C_dist[[1, 2], :])
    cart_dist = np.tensordot(grad_X, C_dist, axes=([3, 2], [0, 1])).T
    from chemcoord.cartesian_coordinates.cartesian_class_main import Cartesian
    return Cartesian(atoms=zmat_dist['atom'],
                     coords=cart_dist,
                     index=zmat_dist.index)
Пример #4
0
 def __init__(self, vel, aoa):  # initially create freestream
     self.vel, self.aoa = vel, sp.rad(
         aoa)  # create variables, aoa is converted into radians
     self.z = sp.symbols('z', real=False)  # create z complex number
     self.x, self.y = sp.symbols(
         'x, y', real=True
     )  # create x,y variables. real and imaginery parts of the z
Пример #5
0
 def getConfigurationMatrixCart(self):
     angle = sp.rad(self.angleCart)
     M = sp.Matrix([[sp.cos(angle), -sp.sin(angle), 0,
                     sp.N(self.x)],
                    [sp.sin(angle),
                     sp.cos(angle), 0,
                     sp.N(self.y)], [0, 0, 1, self.offset], [0, 0, 0, 1]])
     print("caa cart>>", M)
     return M
def convertToRadians(expr):
    newExpr = None
    if trigUnit == TrigUnit.Degrees:
        newExpr = sympy.rad(expr)
    elif trigUnit == TrigUnit.Gradients:
        newExpr = expr * sympy.pi / 200
    else:
        newExpr = expr

    return newExpr
Пример #7
0
    def __updateDistanceRos__(self, xName, yName, angle, distance, timePerRev):
        #now = time()
        #future = now+distance/157*timePerRev
        #print( "update: now, future", now, future )
        #cutoff = now
        #while now-cutoff < future-cutoff:
        #    print( now-cutoff, future-cutoff, now-cutoff < future-cutoff )
        #    setattr( self, xName, sp.N( sp.cos( sp.rad(angle))* (now-cutoff)/(future-cutoff)*distance) )
        #    setattr( self, yName, sp.N( sp.sin( sp.rad(angle))* (now-cutoff)/(future-cutoff)*distance) )

        #    print( "getAttr", getattr( self, xName ) )
        #    print( "getAttr", getattr( self, yName ) )
        #    print( "------>", sp.N( sp.cos( sp.rad(angle))* (now-cutoff)/(future-cutoff)*distance) )
        #    print( "------>", sp.N( sp.sin( sp.rad(angle))* (now-cutoff)/(future-cutoff)*distance) )
        #    rclpy.sleep(0.1)

        #    now = time()
        setattr(self, xName, sp.N(sp.cos(sp.rad(angle)) * distance))
        setattr(self, yName, sp.N(sp.sin(sp.rad(angle)) * distance))
Пример #8
0
    def grad_V(values=None, get_calculated=False,
          calculated=[]):  # pylint:disable=dangerous-default-value
        if get_calculated:
            return calculated
        elif values is not None:
            substitutions = list(zip(symbolic_expressions, values))
            new_zmat = zmolecule.subs(substitutions)

            if isfile(input_path(len(calculated))):
                result = {}
                while len(result.keys()) < 3:
                    try:
                        result = molcas.parse_output(output_path(len(calculated)))
                    except FileNotFoundError:
                        pass
                    sleep(0.5)
            else:
                result = molcas.calculate(
                    molecule=new_zmat, forces=True,
                    el_calc_input=input_path(len(calculated)),
                    start_orb=start_orb_path(len(calculated) - 1) if calculated else start_orb,
                    hamiltonian=hamiltonian, basis=basis,
                    charge=charge, title=title,
                    multiplicity=multiplicity,
                    num_procs=num_procs, mem_per_proc=mem_per_proc, **kwargs)

            energy, grad_energy_X = result['energy'], result['gradient']

            grad_energy_C = _get_grad_energy_C(new_zmat, grad_energy_X)
            zm_values_rad = zmolecule.loc[:, value_cols].values
            zm_values_rad[:, [1, 2]] = sympy.rad(zm_values_rad[:, [1, 2]])
            energy_symb = np.sum(zm_values_rad * grad_energy_C)
            grad_energy_symb = sympy.Matrix([
                energy_symb.diff(arg) for arg in symbolic_expressions])
            grad_energy_symb = np.array(grad_energy_symb.subs(substitutions))
            grad_energy_symb = grad_energy_symb.astype('f8').flatten()

            new_zmat.metadata['energy'] = energy
            new_zmat.metadata['symbols'] = substitutions
            calculated.append({'energy': energy, 'structure': new_zmat,
                               'symbols': substitutions})
            with open(md_out, 'a') as f:
                f.write(_get_table_row(calculated, grad_energy_symb))

            if is_converged(calculated, etol=etol):
                raise ConvergenceFinished(successful=True)
            elif len(calculated) >= max_iter:
                raise ConvergenceFinished(successful=False)

            return grad_energy_symb
        else:
            raise ValueError
Пример #9
0
def new_vortex_position(trailing_edge, center, angle, distance, a):
    """
    :param center: center of airfoil
    :param a: joukowski parameter
    :param trailing_edge: current trailing edge of the airfoil
    :param angle: vortex position angle
    :param distance: vortex position distance relative to the chord length
    :return: z coordinate zeta coordinate
    """
    z = trailing_edge + distance * sp.exp(-1j * sp.rad(angle)).evalf()
    zeta = mapzeta(z, a)
    zeta = check_in_zeta(zeta, center, a)
    return [z, zeta]
Пример #10
0
 def pxpzhat0_values(self, contour_values_: Union[List[float],
                                                  Tuple[float]],
                     sub_: Dict) -> List[Tuple[float, float]]:
     r"""Generate initial values for :math:`\hat{p}_x`, :math:`\hat{p}_z`."""
     pxpzhat_values_ = [(float(0), float(0))] * len(contour_values_)
     for i_, Ci_ in enumerate(contour_values_):
         tmp_sub_ = omitdict(sub_, [rxhat, Ci])
         tmp_sub_[Ci] = rad(Ci_)
         # pzhat for pxhat=1 which is true when rxhat=0
         pzhat_ = self.pzhat_lambda(tmp_sub_, 0, 1).n()
         eqn_ = self.pxhatsqrd_Ci_polylike_eqn(tmp_sub_, pzhat_)
         x_ = float(self.pxhat_Ci_soln(eqn_, tmp_sub_, rxhat.subs(sub_)))
         y_ = float(self.pzhat_lambda(tmp_sub_, 0, 1).n())
         pxpzhat_values_[i_] = (x_, y_)
     return pxpzhat_values_
Пример #11
0
 def __updateAngleRos__(self, angleName, angle, maxAngle, timePerRev):
     """
     Continuously updates the angles s.t. ros can turn the coordinate 
     systems in real time.
     """
     #now = time()
     #future = now+angle/maxAngle*timePerRev
     #cutoff = now
     #while now-cutoff < future-cutoff:
     #    #print( now-cutoff, future-cutoff, now-cutoff < future-cutoff )
     #    setattr( self, angleName, sp.N(sp.rad(sp.N((now-cutoff)/(future-cutoff)*angle)) ) )
     #    #print( "getAttr", getattr( self, angleName ) )
     #    #print( "------>", sp.N(sp.rad(sp.N((now-cutoff)/(future-cutoff)*angle)) ))
     #    rclpy.sleep(0.1)
     #    now = time()
     setattr(self, angleName, sp.N(sp.rad(angle)))
        for i in range(len(vortex_velocity)):
            new_x = x_vortex_z[i] + float(sp.re(vortex_velocity[i])) * t_step
            new_y = y_vortex_z[i] - float(sp.im(vortex_velocity[i])) * t_step

            x_vortex_z[i] = float(new_x)
            y_vortex_z[i] = float(new_y)

            zeta1_temp, zeta2_temp = joukowiski.maptozeta(new_x, new_y, a)
            x_vortex_zeta[i] = float(sp.re(zeta1_temp))
            y_vortex_zeta[i] = float(sp.im(zeta1_temp))

    ##################
    distance = 0.015
    theta = 0
    x1_z, y1_z = 2 * a + distance * sp.cos(
        sp.rad(theta)).evalf(), distance * sp.sin(sp.rad(theta)).evalf()
    zeta1, zeta2 = joukowiski.maptozeta(x1_z, y1_z, a)

    vortex_center = zeta1  # vortex center coordinates
    x_vortex_zeta.append(float(sp.re(zeta1)))
    y_vortex_zeta.append(float(sp.im(zeta1)))

    x_vortex_z.append(float(x1_z))
    y_vortex_z.append(float(y1_z))
    '''
    vortex_center = 0
    x1_z, y1_z = 0.0, 0.0
    
    if len(x_vortex_z) == 0:
        distance  = 2*a*0.015
        theta = 2 # degrees
Пример #13
0
 def __init__(self, vel, aoa):
     self.vel, self.aoa = vel, sp.rad(aoa)
     self.z = sp.symbols('z', real = False)
     self.x, self.y = sp.symbols('x, y', real = True)
import function_file as ff

# -------------- parameters ------------------
#
# --------------------------------------------
# plunging parameters
pl_amplitude = 0
pl_frequency = 0

# joukowski paramters
center = -0.2 + 1j * 0.2
joukowski_parameter = 2
radius = np.sqrt(center.imag**2 + (joukowski_parameter - center.real)**2)
velocity = 5.0
aoa = 2.0  # degree
aoa = sp.rad(aoa).evalf()

# time
time_step = 0.05
current_time = 0.00
iteration = 5

# new vortex
distance = 0.015  # portion of the chord length
angle = 0  # degrees

# data store
circulation = []
vortex_strength = []
vortex_z = []
vortex_zeta = []
Пример #15
0
import sympy as sp
import sympy_helpers as sph
from argparse import ArgumentParser
import os
import codegen

R_W_IMU = sp.rot_axis1(sp.rad(-90)) * sp.rot_axis3(sp.rad(-90))
R_W_ACC = sp.rot_axis1(sp.rad(90)) * sp.rot_axis3(sp.rad(-90))

v_IMU = sp.MatrixSymbol("v_IMU", 3, 1)
v_ACC = sp.MatrixSymbol("v_ACC", 3, 1)
v_W = sp.MatrixSymbol("v_W", 3, 1)

def main(args):
    exprs = {"IMU_to_W": [sp.Eq(v_W, R_W_IMU * v_IMU)],
             "ACC_to_W": [sp.Eq(v_W, R_W_ACC * v_ACC)],
             "W_to_IMU": [sp.Eq(v_IMU, R_W_IMU.T * v_W)],
             "W_to_ACC": [sp.Eq(v_ACC, R_W_ACC.T * v_W)]}

    out = codegen.gen_code(exprs, args.prefix, "trans")

    os.makedirs(args.out_dir, exist_ok=True)

    for fid in out:
        path = os.path.join(args.out_dir, fid[0])
        with open(path, "w") as f:
            f.write(fid[1])

if __name__ == "__main__":
    parser = ArgumentParser()
    parser.add_argument("--outdir", dest="out_dir", type=str,
import intelligent_robotics as ir
import sympy
sympy.init_printing()

theta1,theta2 = ir.dynamicsymbols('theta1,theta2')

l1,l1g,l2,l2g,IG1,IG2,m1,m2 = sympy.symbols('l1,l1g,l2,l2g,IG1,IG2,m1,m2')

"""#### DH Parameter

"""

T01 = ir.DH(0,0,l1,theta1)

T12 = ir.DH(0,-sympy.rad(90),0,theta2)

T23 = ir.DH(l2,sympy.rad(90),0,0)

T01, T12, T23

w_0_0 = sympy.Matrix([[0],[0],[0]])
w_1_1 = ir.get_angular_vel_R(T01,w_0_0,theta1.diff())
w_2_2 = ir.get_angular_vel_R(T12,w_1_1,theta2.diff())
w_3_3 = ir.get_angular_vel_R(T23,w_2_2,0)

w_1_1,w_2_2,w_3_3

v_0_0 = sympy.Matrix([[0],[0],[0]])
v_1_1 = ir.get_linear_vel_R(T01,w_0_0,v_0_0)
v_2_2 = ir.get_linear_vel_R(T12,w_1_1,v_1_1)
sp.I  # Unidad imaginaria

# Potencias y raices
sp.Pow(x, potencia)  # Calcular la potencia n-esima
sp.sqrt(num)  # Calcular la raiz cuadrada
sp.cbrt(num)  # Calcular la raiz cubica
sp.Pow(x, sp.Rational(1, n))  # Calcular la raiz n-esima

# Exponentes y logaritmos
sp.exp(num)  # Calcular la exponencial
sp.log(num)  # Calcular el logaritmo natural
sp.log(base, num)  # Calcular el logaritmo en la base especificada

# Conversión de angulos
sp.deg(num)  # Convertir ángulos de radianes a grados.
sp.rad(num)  # Convertir ángulos de grados a radianes.

# Funciones para trigonometría (Angulos en radianes)
sp.sin(num)  # Seno
sp.cos(num)  # Coseno
sp.tan(num)  # tangente
sp.cot(num)  # cotangente
sp.sec(num)  # secante
sp.csc(num)  # cosecante
sp.asin(num)  # Arcoseno
sp.acos(num)  # Arcocoseno
sp.atan(num)  # Arcotangente
sp.atan2(catetoY,
         catetoX)  # Arcotangente de un triangulo segun los catetos (Angulo)
sp.acot(num)  # Arcocotangente
sp.asec(num)  # Arcosecante
Пример #18
0
print(vx, vy)

x0_f, y0_f = 0, 0
x1_f, y1_f = 0, 0

center = Particle((0, 0), 1)
p0 = Particle((x_0, y_0), 3)
p1 = Particle((x_1, y_1), 3)

a = Vec2d(0, 0)
b = Vec2d(0, 0)
v = Vec2d(vx, vy)
print(a, b, v)

p0.speed = v.get_length()
p0.angle = rad(v.get_angle() + 90)
p1.speed = 0
p1.angle = 0

print(p0.angle)

font = pygame.font.Font(None, 32)
clock = pygame.time.Clock()
radius = 30.75 * 2

running = True
moving = False
collide = False
t = 1
while running:
    clock.tick(1)
Пример #19
0
def test_issue_7263():
    assert abs((simplify(30.8**2 - 82.5**2 * sin(rad(11.6))**2)).evalf() - \
            673.447451402970) < 1e-12
Пример #20
0
 def dx(self):
     return cos(rad(self.rotation))
Пример #21
0
 def dy(self):
     return sin(rad(self.rotation))
Пример #22
0
#taking all values for incident angle
all_values = np.linspace(0.00001, 90.0, 100)

#***************************************************Normal Graph [ delta vs i ] *****************************************************

# ------------------------------------------------Delta vs incident angle ( in varying mu )---------------------------------------------------------

# for mu =1.5 & A = 60
y_list = []
x_list = []
for v in all_values:
    try:
        #only possible values should be taken
        y_list.append(
            float(f.evalf(subs={
                i: sp.rad(v),
                A: sp.rad(60),
                mu: 1.5
            })))
        x_list.append(v)
    except:
        pass

# for mu =1.33 & A = 60
y1_list = []
x1_list = []
for v in all_values:
    try:
        y1_list.append(
            float(f.evalf(subs={
                i: sp.rad(v),
Пример #23
0
def test_issue_7263():
    assert abs((simplify(30.8**2 - 82.5**2 * sin(rad(11.6))**2)).evalf() - \
            673.447451402970) < 1e-12
Пример #24
0
    def rotate_vector(self, theta, deg: bool = False):
        # def rotate_vector(self, theta: Union[int, float], deg: bool = False):
        if deg:
            theta = rad(theta)

        self.vector = self.rotation_matrix.subs(self.t, theta) * self.vector