コード例 #1
0
def batman_equations():

    x = sm.symbols('x', real=True)

    shoulder = ((sm.S(6) * sm.Abs(sm.sqrt(10)) / 7 +
                 (sm.S(3) / 2 - sm.Abs(x) / 2)) -
                (sm.S(6) * sm.Abs(sm.sqrt(10)) / 14) *
                sm.Abs(sm.sqrt(4 - (sm.Abs(x) - 1)**2)))
    cheek = 9 - 8 * sm.Abs(x)
    ear = 3 * sm.Abs(x) + sm.S(3) / 4
    head = 2 + sm.S(2) / 4
    top_wing = 3 * sm.sqrt(-x**2 + 49) / 7
    bottom_wing = -top_wing
    tail = ((sm.Abs(x / 2) - ((3 * sm.sqrt(33) - 7) / 112) * x**2 - 3) +
            sm.sqrt(1 - (sm.Abs(sm.Abs(x) - 2) - 1)**2))

    top = sm.Piecewise((top_wing, x >= 3), (shoulder, x >= 1),
                       (cheek, x >= sm.S(3) / 4), (ear, x >= sm.S(7) / 12),
                       (head, x >= -sm.S(7) / 12), (ear, x >= -sm.S(3) / 4),
                       (cheek, x >= -1), (shoulder, x >= -3), (top_wing, True))

    bottom = sm.Piecewise((bottom_wing, x >= 4), (tail, x >= -4),
                          (bottom_wing, True))

    return top, bottom
コード例 #2
0
def test_trig_solution(theta, phi, lamb, xi, theta1, theta2):
    r"""Test if arguments are a solution to a system of equations.

    .. math::
       \cos(\phi+\lambda) \cos(\\theta) = \cos(xi) * \cos(\\theta1+\\theta2)

       \sin(\phi+\lambda) \cos(\\theta) = \sin(xi) * \cos(\\theta1-\\theta2)

       \cos(\phi-\lambda) \sin(\\theta) = \cos(xi) * \sin(\\theta1+\\theta2)

       \sin(\phi-\lambda) \sin(\\theta) = \sin(xi) * \sin(-\\theta1+\\theta2)

    Returns the maximum absolute difference between right and left hand sides
    as a Max symbol. See:
    http://docs.sympy.org/latest/modules/functions/elementary.html?highlight=max
    """
    delta1 = sympy.Abs(
        sympy.cos(phi + lamb) * sympy.cos(theta) -
        sympy.cos(xi) * sympy.cos(theta1 + theta2))
    delta2 = sympy.Abs(
        sympy.sin(phi + lamb) * sympy.cos(theta) -
        sympy.sin(xi) * sympy.cos(theta1 - theta2))
    delta3 = sympy.Abs(
        sympy.cos(phi - lamb) * sympy.sin(theta) -
        sympy.cos(xi) * sympy.sin(theta1 + theta2))
    delta4 = sympy.Abs(
        sympy.sin(phi - lamb) * sympy.sin(theta) -
        sympy.sin(xi) * sympy.sin(-theta1 + theta2))

    return sympy.Max(delta1, delta2, delta3, delta4)
コード例 #3
0
    def cylinder_grasp_affordance(self, gripper, obj_input):
        frame = obj_input.get_frame()
        shape = obj_input.get_dimensions()
        cylinder_z = frame.col(2)
        cylinder_pos = pos_of(frame)

        gripper_x = gripper.frame.col(0)
        gripper_z = gripper.frame.col(2)
        gripper_pos = pos_of(gripper.frame)
        c_to_g = gripper_pos - cylinder_pos

        zz_align = sp.Abs(gripper_z.dot(cylinder_z))
        xz_align = gripper_x.dot(cylinder_z)
        dist_z = cylinder_z.dot(c_to_g)
        border_z = (shape[2] - gripper.height) * 0.5
        cap_dist_normalized_signed = dist_z / border_z
        cap_dist_normalized = sp.Abs(cap_dist_normalized_signed)

        cap_top_grasp = 1 - sp.Max(-xz_align * sp.Min(cap_dist_normalized_signed, 1), 0)
        cap_bottom_grasp = 1 - sp.Min(xz_align * sp.Max(cap_dist_normalized_signed, -1), 0)

        dist_z_center_normalized = sp.Max(1 - cap_dist_normalized, 0)
        dist_ax = sp.sqrt(frame.col(0).dot(c_to_g) ** 2 + frame.col(1).dot(c_to_g) ** 2)

        center_grasp = (1 - dist_z_center_normalized - dist_ax) * zz_align

        return sp.Max(center_grasp, cap_top_grasp, cap_bottom_grasp) * obj_input.get_class_probability()
コード例 #4
0
    def tick(self, tick):
        curr_unk = tick.blackboard.get('curr_unk')
        eq1 = curr_unk.eqntosolve.RHS
        eq2 = curr_unk.secondeqn.RHS

        unknowns = tick.blackboard.get('unknowns')
        R = tick.blackboard.get('Robot')

        A = eq1.coeff(sp.sin(curr_unk.symbol))
        B = eq1.coeff(sp.cos(curr_unk.symbol))

        C = A * sp.sin(curr_unk.symbol) + B * sp.cos(curr_unk.symbol) - eq1
        C = C.simplify()

        D = A * sp.cos(curr_unk.symbol) - B * sp.sin(curr_unk.symbol) - eq2
        D = D.simplify()

        if C == 0 and D == 0:
            print "Simultaneous Eqn Unsuccessful: divded by 0"
            return b3.FAILURE

        sol = sp.atan2(A * C - B * D, A * D + B * C)

        curr_unk.solutions = [sol]
        # enable test for atan(0,0) case
        curr_unk.argument = sp.Abs(A*C - B*D) + \
                            sp.Abs(A*D + B*C)
        curr_unk.nsolutions = 1

        curr_unk.set_solved(R, unknowns)

        return b3.SUCCESS
コード例 #5
0
def testSolution(theta, phi, lamb, xi, theta1, theta2, eps):
    sinxi = sympy.sin(xi)
    cosxi = sympy.cos(xi)
    sintheta = sympy.sin(theta)
    costheta = sympy.cos(theta)

    #the max value of the four deltas must be less than eps
    delta1 = sympy.Abs(
        sympy.cos(phi + lamb) * costheta - cosxi * sympy.cos(theta1 + theta2))
    if delta1.evalf() > eps:
        return False

    delta2 = sympy.Abs(
        sympy.sin(phi + lamb) * costheta - sinxi * sympy.cos(theta1 - theta2))
    if delta2.evalf() > eps:
        return False

    delta3 = sympy.Abs(
        sympy.cos(phi - lamb) * sintheta - cosxi * sympy.sin(theta1 + theta2))
    if delta3.evalf() > eps:
        return False

    delta4 = sympy.Abs(
        sympy.sin(phi - lamb) * sintheta - sinxi * sympy.sin(-theta1 + theta2))
    if delta4.evalf() > eps:
        return False
    return True
コード例 #6
0
ファイル: sympy_utils.py プロジェクト: arlk/flashlight
def norm(A_expr, axis=None, ord=2):

    assert axis is None or axis == 0 or axis == 1
    if axis is None:
        if not A_expr.is_Matrix:
            return sympy.Abs(A_expr)
        assert A_expr.cols == 1 or A_expr.rows == 1
        if A_expr.cols == 1 and A_expr.rows == 1:
            return sympy.Abs(A_expr)
        if A_expr.cols == 1:
            return sympy.root(
                sympy.Add(*[a_expr**ord for a_expr in A_expr[:, 0]]), ord)
        if A_expr.rows == 1:
            return sympy.root(
                sympy.Add(*[a_expr**ord for a_expr in A_expr[0, :]]), ord)
    if axis == 0:
        A_norm_expr = sympy.Matrix.zeros(1, A_expr.cols)
        for c in range(A_expr.cols):
            A_norm_expr[0, c] = sympy.root(
                sympy.Add(*[a_expr**ord for a_expr in A_expr[:, c]]), ord)
        return A_norm_expr
    if axis == 1:
        A_norm_expr = sympy.Matrix.zeros(A_expr.rows, 1)
        for r in range(A_expr.rows):
            A_norm_expr[r, 0] = sympy.root(
                sympy.Add(*[a_expr**ord for a_expr in A_expr[r, :]]), ord)
        return A_norm_expr
    assert False
    return None
コード例 #7
0
 def rfoo(x, Ycd, Ydd):
     psubs = {em.bc: x[0], em.bd: x[1]}
     res = [
         sp.re(sp.Abs(fYc.subs(psubs) - Ycd).evalf()),
         sp.re(sp.Abs(fYd.subs(psubs) - Ydd).evalf())
     ]
     return res
コード例 #8
0
def three_point_error(p: list, func) -> list:
    ''' 
    Calculated the actual errors of the list of points and their approximated derivatives that
    were computed and passed from the above function, also computes the error bound, and prints
    results.
    
    --- Required ---
    list of points must have pre estimated derivatives, and a list of inputs in the current domain
    to try and maximize, or passed through the above function successfully
    
    --- Parameters ---
    p : (points) a list of p [x, fx, [m1, m2, ..], e_dfx], where e_dfx is the estimated derivative, 
        and [m1, ...] is the list of points in the domain to try for the maximizing equation

    --- Returns ---
    p : (updated) list of the original p plus the error bound and actual error for each point '''

    x = sp.Symbol('x')
    n = len(p)
    h = p[1][0] - p[0][0]

    df = sp.diff(func, x)
    df2 = sp.diff(df, x)
    df3 = sp.diff(df2, x)

    dfx = sp.lambdify(x, df)
    print(f'\n[Error Calcs]:')
    for i in range(n):

        d = 3 if (i == 0 or i == (n - 1)) else 6
        print(f' for f\'({p[i][0]}) = {p[i][2]:<1.5f}')
        [xm, fxm] = find_max_save_value(df3, p[i][3])
        p[i][4] = sp.Abs((h**2) / d) * fxm  # store bound
        p[i][5] = sp.Abs(p[i][2] - dfx(p[i][0]))  # store actual

        print(
            f'  bound  : Pick x = {xm} to maximize |(h^2/3)*{df3}| = {p[i][4]:1.6f}'
        )
        print(
            f'  actual : |{p[i][1]:<1.5f} - {df}| =  |{p[i][1]:<1.5f} - {dfx(p[i][0]):<1.6f}| = {p[i][5]:<1.6f}'
        )

    # print the final table
    for i in range(n):
        if i == 0:
            print('\n[Final Table]:')
            print(f' {"-"*54}')
            print(
                f'|{" x":<8}|{" f(x)":<8}| {" df(x)":<10}| { " e actual":<11}| {" e bound":<11}|'
            )
            print(f' {"-"*54}')
        print(
            f'|{p[i][0]:<8}|{p[i][1]:<8.5f}| {p[i][2]:<9.5f}|  {p[i][5]:<10.6f}|  {p[i][4]:<10.6f}|'
        )
    print(f' {"-"*54}\n')

    return p
コード例 #9
0
ファイル: main.py プロジェクト: vighneshiyer/ee240b-project
        def analyze_noise_power():
            for lut_line in full_lut:
                print("LUT Line: {}".format(lut_line))
                vi2 = 0
                kT4 = 4 * k * ahkab.constants.Tref
                subs['R1_0'] = lut_line[R_idx]
                subs['C1_0'] = lut_line[C_idx]
                subs['C2_0'] = lut_line[C_idx]
                subs['G1_0'] = lut_line[gm_idx]
                subs['RO_0'] = lut_line[ro_idx]

                # Integrate input-referred noise power using symbolic analysis
                for s in nsrcs:
                    if s.startswith('INR'):
                        in2 = kT4 / subs[s[2:]]
                    elif s.startswith('INE') or s.startswith('ING'):
                        in2 = kT4 * nonideal_dict['gamma'] * lut_line[gm_idx]
                    tfn = run_sym(lpf, s)

                    # Just get the input-referred noise density at DC and multiply by the passband to speed up calculation
                    vni2 = sp.lambdify(
                        f,
                        sp.Abs(((tfn['gain'] / tf['gain']).subs(
                            subs_syms(tfn, subs))))**2 * in2)
                    vi2 += quad(vni2, 1, spec.passband_corner.f())[0]

                    # Input referred noise of 2nd stage (assuming same R and C)
                    vni2_2 = sp.lambdify(
                        f,
                        sp.Abs(((tfn['gain'] / tf['gain']**2).subs(
                            subs_syms(tfn, subs))))**2 * in2)
                    vi2 += quad(vni2, 1, spec.passband_corner.f())[0]

                print("\tTotal input referred noise power: {} V^2".format(vi2))

                # Assume allowable swing (zero-peak) is VDD/2 - V*
                dr = 10**(spec.dynamic_range / 10)
                vi_min = sp.sqrt(vi2 * dr * 2)
                print('\tMin reqd voltage swing for DR: {} V'.format(vi_min))
                if vi_min > 0.2:
                    print(
                        '\tFails dynamic range: voltage swing of {} V not attainable!'
                        .format(vi_min))
                else:
                    print('\tPasses dynamic range!')

                def power(Id):
                    diff_factor = 2
                    vdd = 1.2
                    stages = 2
                    branches = 2
                    return diff_factor * Id * vdd * stages * branches

                p = power(lut_line[Id_idx])
                print("\tPower: {} W".format(p))
                yield (vi2, p)
コード例 #10
0
def lagrange_error_bound(fx,
                         p: list,
                         x_p: float,
                         n: int,
                         p_out: bool = True) -> float:
    '''  
    Finds a bound for the given function over the interval used in the Lagrange polynomial 
    interpolation, then compares the bound to the actual error using the error formula
    
    --- Parameters ---
    fx    : the function in which we are comparing the Lagrange interpolation with 
    p     : list of known unique points  
    x_p   : the point where the comparason takes place with fx and Px (Lagrange polynomial)
    n     : the degree of the Lagrange polynomial to be constructed for the error comparing 
    p_out : disable of enable a printout of the computed error calculations, default is true
    
    --- Returns ---
    e     : the actual error computed by the Lagrange interpolation polynomial vs. the function fx '''

    if (len(p) < n or len(p) < 2):
        raise ValueError('Not enough known points provided.')
    if (n < 1):
        raise ValueError('Degree has to be at least 1.')

    # actual error
    estimated = lagrange_interpolation(p, x_p, n)
    actual = fx(x_p)
    ae = sp.Abs(actual - estimated)

    if (p_out):
        # maximize the left side of the error funciton
        max_left = fx(x)
        for i in range(n + 1):
            max_left = sp.diff(max_left, x)

        p = sorted(p, key=lambda point: sp.Abs(x_p - point.x))
        bound = [p[0].x, p[n].x]
        max_left /= sp.factorial(n + 1)
        max_left_o = find_max_save_value(max_left, bound)

        # maximize the right size of the error funciton
        max_right = 1
        for i in range(n + 1):
            max_right *= (x - p[i].x)
        max_right_o = find_max_save_value(max_right, [x_p])

        print(
            f'[Max Error]:\nme = (f^(n + 1))(xi)/(n + 1)!)*|(x - x_j)*(x - x_j+1)...|'
        )
        print(f'   = {sp.Abs(max_left)} * |{max_right}|')
        print(f'   = {max_left_o[1]*max_right_o[1]:.12}\n')
        print(
            f'[Actual Error]:\nae = |actual - estimated|\n   = |{actual} - {estimated}|\n   = {ae:.12}\n'
        )

    return ae
コード例 #11
0
    def _execute_controller(self):

        rate = rospy.Rate(10)

        P, I = sp.var('p i')
        min_linear_vel = sp.var("minLinearVel")
        min_angular_vel = sp.var("minAngularVel")

        distErr, distVerticalErr, vertDiff, lastLinearOut = sp.var(
            'distErr distVerticalErr vertDiff lastLinearOut')
        anglErr, lastAngularOut, anglDiff = sp.var(
            'anglErr lastAngularOut anglDiff')

        self.linear_eq = sp.Piecewise(
            (sp.Max(P * distErr + I * lastLinearOut, min_linear_vel),
             sp.And(sp.Abs(anglErr) < anglDiff, distErr >= 0)),
            (sp.Min(P * distErr + I * lastLinearOut, -min_linear_vel),
             sp.And(sp.Abs(anglErr) < anglDiff, distErr < 0)),
            (0, sp.Abs(anglErr) >= anglDiff))

        self.linear_vertical_eq = sp.Piecewise(
            (sp.Max(P * distVerticalErr + I * lastLinearOut,
                    min_linear_vel), distVerticalErr > vertDiff), (0, True))

        angular_eq_temp = P * anglErr + I * lastAngularOut

        self.angular_eq = sp.Piecewise(
            (sp.Min(angular_eq_temp, -min_angular_vel), angular_eq_temp < 0),
            (sp.Max(angular_eq_temp, min_angular_vel), angular_eq_temp >= 0))

        constansts = {
            P: self.current_config["p"],
            I: self.current_config["i"],
            min_linear_vel: self.current_config["min_linear_vel"],
            min_angular_vel: self.current_config["min_angular_vel"],
            anglDiff: self.current_config["angular_diff"],
            vertDiff: self.current_config["vertical_diff"]
        }

        variables = [
            distErr, distVerticalErr, lastLinearOut, anglErr, lastAngularOut
        ]

        self.linear_eq = self.linear_eq.subs(constansts)
        self.linear_vertical_eq = self.linear_vertical_eq.subs(constansts)
        self.angular_eq = self.angular_eq.subs(constansts)

        while not rospy.is_shutdown():

            if self._goal != None and self._enabled:
                self._command_to(self._goal, variables)

            self._reach_publisher.publish(Bool(self._reach))

            rate.sleep()
コード例 #12
0
    def y_max(self):
        y = sp.symbols("y", real=True)

        yset = list(
            sp.solve(
                sp.Eq(
                    sp.Abs(self.stability_function().subs(
                        sp.symbols("z", complex=True), sp.I * y))**2, 1), y))
        return sp.Abs(
            max([sp.re(ysol) for ysol in yset if sp.Abs(sp.im(y)) < 10**-7],
                key=sp.Abs))
コード例 #13
0
async def protected_power(a, b):
	if a == 0 and b == 0:
		raise EvaluationError('Cannot raise 0 to the power of 0')
	sa = float(sympy.Abs(a))
	sb = float(sympy.Abs(b))
	if sa < 4000 and sb < 20:
		return a ** b
	try:
		return await calculator.crucible.run(_protected_power_crucible, (a, b), timeout=2)
	except asyncio.TimeoutError:
		raise EvaluationError('Operation timed out. Perhaps the values were too large?')
コード例 #14
0
ファイル: sym_jones.py プロジェクト: scottprahl/pypolar
def ellipse_orientation(J):
    """
    Return the angle between the major semi-axis and the x-axis.

    This angle is sometimes called the azimuth or psi.
    """
    Ex = sympy.Abs(J[0, :])
    Ey = sympy.Abs(J[1, :])
    delta = phase(J)
    numer = 2 * Ex * Ey * sympy.cos(delta)
    denom = Ex**2 - Ey**2
    psi = 0.5 * sympy.arctan2(numer, denom)
    return psi
コード例 #15
0
def batman_equations_heaviside():
    # From : http://mathworld.wolfram.com/BatmanCurve.html

    x = sm.symbols('x', real=True)
    h_ = sm.symbols('h_')

    w = 3 * sm.sqrt(1 - (x / 7)**2)
    l = ((x + 3) / 2 - sm.S(3) / 7 * sm.sqrt(10) * sm.sqrt(4 - (x + 1)**2) +
         sm.S(6) / 7 * sm.sqrt(10))
    r = ((3 - x) / 2 - sm.S(3) / 7 * sm.sqrt(10) * sm.sqrt(4 - (x - 1)**2) +
         sm.S(6) / 7 * sm.sqrt(10))
    f = ((h_ - l) * sm.Heaviside(x + 1, 0) +
         (r - h_) * sm.Heaviside(x - 1, 0) + (l - w) * sm.Heaviside(x + 3, 0) +
         (w - r) * sm.Heaviside(x - 3, 0) + w)
    f_of = f.xreplace(
        {x: sm.Abs(x + sm.S(1) / 2) + sm.Abs(x - sm.S(1) / 2) + 6})
    h = sm.S(1) / 2 * (f_of - 11 * (x + sm.S(3) / 4) + sm.Abs(x - sm.S(3) / 4))
    f = f.xreplace({h_: h})
    g = (sm.S(1) / 2 *
         (sm.Abs(x / 2) + sm.sqrt(1 - (sm.Abs(sm.Abs(x) - 2) - 1)**2) -
          sm.S(1) / 112 * (3 * sm.sqrt(33) - 7) * x**2 +
          3 * sm.sqrt(1 - (sm.S(1) / 7 * x)**2) - 3) *
         ((x + 4) / sm.Abs(x + 4) -
          (x - 4) / sm.Abs(x - 4)) - 3 * sm.sqrt(1 - (x / 7)**2))

    return f, g
コード例 #16
0
ファイル: finitevolumes.py プロジェクト: mabau/pystencils
def VOF(j: ps.field.Field, v: ps.field.Field, ρ: ps.field.Field):
    """Volume-of-fluid discretization of advection

    Args:
        j: the staggered field to write the fluxes to. Should have a D2Q9/D3Q27 stencil. Other stencils work too, but
           incur a small error (D2Q5/D3Q7: v^2, D3Q19: v^3).
        v: the flow velocity field
        ρ: the quantity to advect
    """
    assert ps.FieldType.is_staggered(j)

    fluxes = [[] for i in range(j.index_shape[0])]

    v0 = v.center_vector
    for d, neighbor in enumerate(j.staggered_stencil):
        c = ps.stencil.direction_string_to_offset(neighbor)
        v1 = v.neighbor_vector(c)

        # going out
        cond = sp.And(
            *[sp.Or(c[i] * v0[i] > 0, c[i] == 0) for i in range(len(v0))])
        overlap1 = [1 - sp.Abs(v0[i]) for i in range(len(v0))]
        overlap2 = [c[i] * v0[i] for i in range(len(v0))]
        overlap = sp.Mul(*[(overlap1[i] if c[i] == 0 else overlap2[i])
                           for i in range(len(v0))])
        fluxes[d].append(ρ.center_vector * overlap * sp.Piecewise((1, cond),
                                                                  (0, True)))

        # coming in
        cond = sp.And(
            *[sp.Or(c[i] * v1[i] < 0, c[i] == 0) for i in range(len(v1))])
        overlap1 = [1 - sp.Abs(v1[i]) for i in range(len(v1))]
        overlap2 = [v1[i] for i in range(len(v1))]
        overlap = sp.Mul(*[(overlap1[i] if c[i] == 0 else overlap2[i])
                           for i in range(len(v1))])
        sign = (c == 1).sum() % 2 * 2 - 1
        fluxes[d].append(sign * ρ.neighbor_vector(c) * overlap * sp.Piecewise(
            (1, cond), (0, True)))

    for i, ff in enumerate(fluxes):
        fluxes[i] = ff[0]
        for f in ff[1:]:
            fluxes[i] += f

    assignments = []
    for i, d in enumerate(j.staggered_stencil):
        for lhs, rhs in zip(
                j.staggered_vector_access(d).values(), fluxes[i].values()):
            assignments.append(ps.Assignment(lhs, rhs))
    return assignments
コード例 #17
0
    def eliminate(rxns, wrt):
        """ Linear combination coefficients for elimination of a substance

        Parameters
        ----------
        rxns : iterable of Equilibrium instances
        wrt : str (substance key)

        Examples
        --------
        >>> e1 = Equilibrium({'Cd+2': 4, 'H2O': 4}, {'Cd4(OH)4+4': 1, 'H+': 4}, 10**-32.5)
        >>> e2 = Equilibrium({'Cd(OH)2(s)': 1}, {'Cd+2': 1, 'OH-': 2}, 10**-14.4)
        >>> Equilibrium.eliminate([e1, e2], 'Cd+2')
        [1, 4]
        >>> print(1*e1 + 4*e2)
        4 Cd(OH)2(s) + 4 H2O = Cd4(OH)4+4 + 4 H+ + 8 OH-; 7.94e-91

        """
        import sympy
        viol = [r.net_stoich([wrt])[0] for r in rxns]
        factors = defaultdict(int)
        for v in viol:
            for f in sympy.primefactors(v):
                factors[f] = max(factors[f], sympy.Abs(v//f))
        rcd = reduce(mul, (k**v for k, v in factors.items()))
        viol[0] *= -1
        return [rcd//v for v in viol]
コード例 #18
0
def group_param_rot_spec(robo, symo, j, lam, antRj):
    """Internal function. Groups inertia parameters according to the
    special rule for a rotational joint.

    Notes
    =====
    robo is the output paramete
    """
    chainj = robo.chain(j)
    r1, r2, orthog = Transform.find_r12(robo, chainj, antRj, j)
    kRj, all_paral = Transform.kRj(robo, antRj, r1, chainj)
    Kj = robo.get_inert_param(j)
    to_replace = {0, 1, 2, 4, 5, 6, 7}
    if Transform.z_paral(kRj):
        Kj[0] = 0  # XX
        Kj[1] = 0  # XY
        Kj[2] = 0  # XZ
        Kj[4] = 0  # YZ
        to_replace -= {0, 1, 2, 4}
    joint_axis = antRj[chainj[-1]].col(2)
    if all_paral and robo.G.norm() == sympy.Abs(joint_axis.dot(robo.G)):
        Kj[6] = 0  # MX
        Kj[7] = 0  # MY
        to_replace -= {6, 7}
    if j == r1 or (j == r2 and orthog):
        Kj[5] += robo.IA[j]  # ZZ
        robo.IA[j] = 0
    for i in to_replace:
        Kj[i] = symo.replace(Kj[i], inert_names[i], j)
    robo.put_inert_param(Kj, j)
コード例 #19
0
def gauss_meth_err_estimation(a, b, knots):
    x_ = sp.Symbol("x")
    f = -sp.Abs(sp.diff(function(0, diff=True), sp.Symbol("x"),
                        2 * len(knots)))
    f = sp.utilities.lambdify(x_, f)
    return (-optimize.minimize_scalar(f, bounds=(a, b), method='Bounded').fun / np.math.factorial(2*len(knots))) * \
        integrate.quad(estimator_func, a, b, args=(knots, 2))[0]
コード例 #20
0
def run_Lagrange_interp_abs_Cheb(N, ymin=None, ymax=None):
    f = sp.Abs(1 - 2 * x)
    fn = sp.lambdify([x], f)
    psi, points = Lagrange_polynomials(x,
                                       N, [0, 1],
                                       point_distribution='Chebyshev')
    u = interpolation(f, psi, points)
    comparison_plot(f, u, Omega=[0, 1],
                    filename='Lagrange_interp_abs_Cheb_%d' % (N+1),
                    plot_title='Interpolation by Lagrange polynomials '\
                    'of degree %d' % N, ymin=ymin, ymax=ymax)
    print 'Interpolation points:', points

    # Make figures of Lagrange polynomials (psi)
    plt.figure()
    xcoor = np.linspace(0, 1, 1001)
    legends = []
    for i in (2, (N + 1) / 2 + 1):
        fn = sp.lambdify([x], psi[i])
        ycoor = fn(xcoor)
        plt.plot(xcoor, ycoor)
        legends.append(r'$\psi_%d$' % i)
        plt.hold('on')
    plt.legend(legends)
    plt.plot(points, [0] * len(points), 'ro')
    #if ymin is not None and ymax is not None:
    #    axis([xcoor[0], xcoor[-1], ymin, ymax])
    plt.savefig('Lagrange_basis_Cheb_%d.pdf' % (N + 1))
    plt.savefig('Lagrange_basis_Cheb_%d.png' % (N + 1))
コード例 #21
0
def dichotomie(a,b,R,A,Z,Q,L):
    eps=R*1e-6
    if b>=R:
        b=R
    b_9=0.9*b
    fb_9=func(b_9,R,A,Z,Q,L)
    fb=func(b,R,A,Z,Q,L)
    while fb_9*fb>0:
        b=b_9
        b_9=0.9*b
        fb_9=func(b_9,R,A,Z,Q,L)
        fb=func(b,R,A,Z,Q,L)
    a=b_9
    fa=func(a,R,A,Z,Q,L)
    ab_2=(a+b)/2.0
    fb=func(ab_2,R,A,Z,Q,L)
    if fa*fb>0:
        a=ab_2
        b=(a+b)/2.0
    else:
        b=ab_2
    while sp.Abs(b-a)>eps:
        fb=func(b,R,A,Z,Q,L)
        ab_2=(a+b)/2
        fab_2=func(ab_2,R,A,Z,Q,L)
        if fab_2==0:
            return ab_2
            break
        if fb*fab_2<0:
            a=ab_2
        else:
            b=ab_2
    return ab_2
コード例 #22
0
def run_abs_by_Lagrange_interp__conv(N=[3, 6, 12, 24]):
    f = sym.Abs(1 - 2 * x)
    f = sym.sin(2 * sym.pi * x)
    fn = sym.lambdify([x], f, modules='numpy')
    resolution = 50001
    xcoor = np.linspace(0, 1, resolution)
    fcoor = fn(xcoor)
    Einf = []
    E2 = []
    h = []
    for _N in N:
        psi, points = Lagrange_polynomials_01(x, _N)
        u, c = interpolation(f, psi, points)
        un = sym.lambdify([x], u, modules='numpy')
        ucoor = un(xcoor)
        e = fcoor - ucoor
        Einf.append(e.max())
        E2.append(np.sqrt(np.sum(e * e / e.size)))
        h.append(1. / _N)
    print(Einf)
    print(E2)
    print(h)
    print(N)
    # Assumption: error = CN**(-N)
    print('convergence rates:')
    for i in range(len(E2)):
        C1 = E2[i] / (N[i]**(-N[i] / 2))
        C2 = Einf[i] / (N[i]**(-N[i] / 2))
        print((N[i], C1, C2))
コード例 #23
0
ファイル: core.py プロジェクト: fossabot/ErrorPropagator
    def calculate_absolute_uncertainty(
            self,
            *assumptions: List[AppliedPredicate],
            refine: bool = False,
            delta_char: str = '\\Delta ') -> 'Expression':
        """Calculate the absolute uncertainty in the expression (IB way), assuming all args given are independent.

        :return: the absolute uncertainty of this expression
        :rtype: Expression

        >>> Expression([a], c * a).calculate_absolute_uncertainty(sympy.Q.positive(c), refine=True, delta_char='Δ')
        f(Δa) = c*Δa
        >>> Expression([a, b, c], a + b - c).calculate_absolute_uncertainty(refine=True, delta_char='Δ')
        f(Δa, Δb, Δc) = Δa + Δb + Δc
        """
        uncertainty_expr = sympy.Integer(0)  # just in case
        uncertainty_args = []
        global_assumptions.add(*assumptions)

        for var in self.args:
            d_var = sympy.Symbol(delta_char + sympy.latex(var))
            uncertainty_args.append(d_var)
            uncertainty_expr += sympy.Abs(self.expr.diff(var)) * d_var
            global_assumptions.add(sympy.Q.positive(var))
        if refine:
            uncertainty_expr = sympy.refine(uncertainty_expr)
        global_assumptions.clear()
        return Expression(uncertainty_args, uncertainty_expr)
コード例 #24
0
ファイル: __init__.py プロジェクト: wgradl/ampform
def _analytic_continuation(rho: sp.Symbol, s: sp.Symbol,
                           s_threshold: sp.Symbol) -> sp.Expr:
    return sp.Piecewise(
        (
            sp.I * rho / sp.pi * sp.log(sp.Abs((1 + rho) / (1 - rho))),
            s < 0,
        ),
        (
            rho + sp.I * rho / sp.pi * sp.log(sp.Abs((1 + rho) / (1 - rho))),
            s > s_threshold,
        ),
        (
            2 * sp.I * rho / sp.pi * sp.atan(1 / rho),
            True,
        ),
    )
コード例 #25
0
 def opt_sto(self, r1, zeta, n):
     r = sp.Symbol('r')
     f = r ** (n - 1) * sp.exp(-zeta * sp.Abs(r))
     N = sp.sqrt(1 / sp.integrate(4 * sp. pi * f * f * r * r, (r, 0, +sp.oo)))
     N = N.subs(sp.pi, np.pi)
     f = r1 ** (n - 1) * np.exp(-zeta * np.abs(r1))
     return f * N
コード例 #26
0
ファイル: vib.py プロジェクト: soranhm/IN5270
def lhs_eq(t, m, b, s, u, damping='linear'):
    """Return lhs of differential equation as sympy expression."""
    v = sym.diff(u, t)
    if damping == 'linear':
        return m * sym.diff(u, t, t) + b * v + s(u)
    else:
        return m * sym.diff(u, t, t) + b * v * sym.Abs(v) + s(u)
コード例 #27
0
ファイル: dolfin.py プロジェクト: pkgw/vernon
    def __init__(self, transformed=True):
        if transformed:
            self.logV = sympy.var('logV') # dropping the C_g subscript
            self.Khat = sympy.var('Khat')
            self.Ksigned = -self.Khat**5
            self.V = sympy.exp(self.logV)
        else:
            self.V = sympy.var('V')
            self.Ksigned = sympy.var('Ksigned')

        self.K = sympy.Abs(self.Ksigned)
        self.L = sympy.var('L') # dropping the asterisk superscript

        self.Cg = sympy.var('Cg')
        self.m0 = sympy.var('m0')
        self.B0 = sympy.var('B0')
        self.R_E = sympy.var('R_E')
        self.c_squared = sympy.var('c^2')

        # Lots of things depend on the pitch angle alpha or its sine `y`,
        # which is obnoxious to compute given V/K/L. So, we compute it
        # numerically and couch the rest of our equations in terms of it.

        self.y = y = sympy.var('y')

        # Here are various useful quantities that don't depend on the
        # diffusion coefficients:

        self.mu = self.V / (self.K + self.Cg)**2
        self.B = self.B0 / self.L**3
        self.p_squared = 2 * self.m0 * self.B * self.mu / y**2
        mc2 = self.m0 * self.c_squared
        self.Ekin = sympy.sqrt(self.p_squared * self.c_squared + mc2**2) - mc2
        self.gamma = self.Ekin / mc2 + 1
        self.beta = sympy.sqrt(1 - self.gamma**-2)
コード例 #28
0
 def intrinsic_func(node):
     name = str(node).upper()
     if name == "EXP" or name == "DEXP":
         return sympy.exp
     elif name == "LOG":
         return sympy.log
     elif name == "LOG10":
         return lambda x: sympy.log(x, 10)
     elif name == "SQRT":
         return sympy.sqrt
     elif name == "SIN":
         return sympy.sin
     elif name == "COS":
         return sympy.cos
     elif name == "ABS":
         return sympy.Abs
     elif name == "TAN":
         return sympy.tan
     elif name == "ASIN":
         return sympy.asin
     elif name == "ACOS":
         return sympy.acos
     elif name == "ATAN":
         return sympy.atan
     elif name == "INT":
         return lambda x: sympy.sign(x) * sympy.floor(sympy.Abs(x))
     elif name == "GAMLN":
         return sympy.loggamma
     else:  # name == "PHI":
         return lambda x: (1 + sympy.erf(x) / sympy.sqrt(2)) / 2
コード例 #29
0
def bisection_s(q,func,iterate0,usinglines):
    q = q[0]
    mp.dps = 100
    epsilon = mpf('0.001')
    test = 12.
    qp_mid = 0.
    q = mpf(q)
    q_plus = q + epsilon
    q_minus = q - epsilon
    for i in range(1000):
        q_mid = (q_plus + q_minus) * mpf('0.5')
        qp_plus = combine_s(q+epsilon,usinglines)
        qp_minus = combine_s(q-epsilon,usinglines)
        qp_mid = combine_s(mpf((q_plus + q_minus)* mpf('0.5') ),usinglines)
        if func(qp_plus,iterate0)[1] * func(qp_minus,iterate0)[1] > 0:
            return qp_mid
        if func(qp_minus,iterate0)[1] * func(qp_mid,iterate0)[1] < 0:
            q_plus = q_mid
        else:
            q_minus = q_mid
        difference = q_plus - q_minus
        if sym.Abs(difference) < 10  ** (-30):
            print("break")
            break
    return qp_mid
コード例 #30
0
def test_events():
    # use bouncing ball to test events work

    # simulate in block diagram
    int_opts = block_diagram.DEFAULT_INTEGRATOR_OPTIONS.copy()
    int_opts['rtol'] = 1E-12
    int_opts['atol'] = 1E-15
    int_opts['nsteps'] = 1000
    int_opts['max_step'] = 2**-3
    x = x1, x2 = Array(dynamicsymbols('x_1:3'))
    mu, g = sp.symbols('mu g')
    constants = {mu: 0.8, g: 9.81}
    ic = np.r_[10, 15]
    sys = SwitchedSystem(
        x1, Array([0]),
        state_equations=r_[x2, -g],
        state_update_equation=r_[sp.Abs(x1), -mu*x2],
        state=x,
        constants_values=constants,
        initial_condition=ic
    )
    bd = BlockDiagram(sys)
    res = bd.simulate(5, integrator_options=int_opts)

    # compute actual impact time
    tvar = dynamicsymbols._t
    impact_eq = (x2*tvar - g*tvar**2/2 + x1).subs(
        {x1: ic[0], x2: ic[1], g: 9.81}
    )
    t_impact = sp.solve(impact_eq, tvar)[-1]

    # make sure simulation actually changes velocity sign around impact
    abs_diff_impact = np.abs(res.t - t_impact)
    impact_idx = np.where(abs_diff_impact == np.min(abs_diff_impact))[0]
    assert np.sign(res.x[impact_idx-1, 1]) != np.sign(res.x[impact_idx+1, 1])