Exemple #1
0
    def test_2d5pt_RooflineIACA(self):
        store_file = os.path.join(self.temp_dir, 'test_2d5pt_RooflineIACA.pickle')
        output_stream = StringIO()

        parser = kc.create_parser()
        args = parser.parse_args(['-m', self._find_file('phinally_gcc.yaml'),
                                  '-p', 'RooflineIACA',
                                  self._find_file('2d-5pt.c'),
                                  '-D', 'N', '4000',
                                  '-D', 'M', '1000',
                                  '-vvv',
                                  '--unit=FLOP/s',
                                  '--store', store_file])
        kc.check_arguments(args, parser)
        kc.run(parser, args, output_file=output_stream)

        results = pickle.load(open(store_file, 'rb'))

        # Check if results contains correct kernel
        self.assertEqual(list(results), ['2d-5pt.c'])

        # Check for correct variations of constants
        six.assertCountEqual(self,
            [sorted(map(str, r)) for r in results['2d-5pt.c']],
            [sorted(map(str, r)) for r in [((sympy.var('M'), 1000), (sympy.var('N'), 4000))]])

        # Output of first result:
        result = list(results['2d-5pt.c'].values())[0]

        six.assertCountEqual(self, result, ['RooflineIACA'])

        roofline = result['RooflineIACA']
        self.assertAlmostEqual(roofline['min performance'], 2900000000.0, places=0)
        self.assertEqual(roofline['bottleneck level'], 3)
Exemple #2
0
def symList(string, imin, imax):
    outlist = []
    for i in range(imin, imax+1):
        string2 = (string+('%d' % i))
        sympy.var(string2)
        outlist.append(eval(string2))
    return outlist
Exemple #3
0
    def test_2d5pt_ECMCPU(self):
        store_file = os.path.join(self.temp_dir, 'test_2d5pt_ECMCPU.pickle')
        output_stream = StringIO()

        parser = kc.create_parser()
        args = parser.parse_args(['-m', self._find_file('phinally_gcc.yaml'),
                                  '-p', 'ECMCPU',
                                  self._find_file('2d-5pt.c'),
                                  '-D', 'N', '2000',
                                  '-D', 'M', '1000',
                                  '-vvv',
                                  '--unit=cy/CL',
                                  '--store', store_file])
        kc.check_arguments(args, parser)
        kc.run(parser, args, output_file=output_stream)

        results = pickle.load(open(store_file, 'rb'))

        # Check if results contains correct kernel
        self.assertEqual(list(results), ['2d-5pt.c'])

        # Check for correct variations of constants
        six.assertCountEqual(self,
            [sorted(map(str, r)) for r in results['2d-5pt.c']],
            [sorted(map(str, r)) for r in [((sympy.var('M'), 1000), (sympy.var('N'), 2000))]])

        # Output of first result:
        result = list(results['2d-5pt.c'].values())[0]

        six.assertCountEqual(self, result, ['ECMCPU'])

        ecmd = result['ECMCPU']
        self.assertAlmostEqual(ecmd['T_OL'], 24.8, places=1)
        self.assertAlmostEqual(ecmd['T_nOL'], 20, places=1)
def test_geteqsys():
    var('R1 V0 Isat T')
    k = symbolic.kboltzmann
    qelectron = symbolic.qelectron
    

    c = SubCircuit(toolkit=symbolic)
    c['V0'] = VS('net1', gnd, v=V0, toolkit=symbolic)
    c['R1'] = R('net1', 'net2', r=R1)
    c['D1'] = Diode('net2', gnd, IS=Isat, toolkit=symbolic)

    dc = SymbolicDC(c)

    dc.epar.T = T

    eqsys, x = dc.get_eqsys()

    x0, x2, x3 = x

    eqsys_ref = np.array([x3 + x0/R1 - x2/R1, 
                          -Isat*(1 - sympy.exp(qelectron*x2/(T*k))) + x2/R1 - x0/R1, 
                          x0 - V0])

    assert sympy.simplify(eqsys_ref[0] - eqsys_ref[0]) == 0
    assert sympy.simplify(eqsys_ref[0] - eqsys_ref[0]) == 0
    assert sympy.simplify(eqsys_ref[0] - eqsys_ref[0]) == 0
def test_symbolic_noise_kt_over_C():
    pycircuit.circuit.circuit.default_toolkit = symbolic
    cir = SubCircuit(toolkit = symbolic)

    k = symbolic.kboltzmann
    var('r c w w1 V', real=True, positive=True)

    s = I * w

    cir['vs'] = VS(1, gnd, vac=V)
    cir['R'] = R(1, 2, r=r)
    cir['C'] = C(2, gnd, c=c)

    noise = Noise(cir, inputsrc='vs', outputnodes=('2', gnd), 
                  toolkit = symbolic)
    res = noise.solve(s, complexfreq=True)

    T = noise.par.epar.T

    svnout = simplify(res['Svnout'])

    noise_voltage_power = simplify(integrate(svnout, (w, 0, oo)))

    assert_equal(noise_voltage_power, 2*pi*k*T/c)

    assert_equal(simplify(res['gain'] - 1/(1 + s*r*c)), 0)
Exemple #6
0
def S2():
    var("x y z")
    e = (x**sin(x) + y**cos(y) + z**(x + y))**100
    t1 = clock()
    f = e.expand()
    t2 = clock()
    return t2 - t1
Exemple #7
0
def planar2r():
    robo = Robot('planar2r', 2, 2, 3, False, tools.SIMPLE)
    # update geometric params
    params = {
        1: {'sigma': 0, 'mu': 1, 'theta': var('th1')},
        2: {'sigma': 0, 'mu': 1, 'alpha': 0, 'd': var('L1'), 'theta': var('th2')},
        3: {'sigma': 2, 'd': var('L2')}
    }
    robo.update_params('geos', params)
    # update dynamic params
    params = {
        1: {'xx': 0, 'xy': 0, 'xz': 0, 'yy': 0, 'yz': 0, 'ia': 0}
    }
    robo.update_params('dyns', params)
    # update joint params
    params = {
        0: {'qdots': 0, 'qddots': 0, 'torques': 0}
    }
    robo.update_params('misc', params)
    # update gravity vector
    params = {
        0: {'gravity': 0},
        1: {'gravity': 0},
        2: {'gravity': var('G3')},
    }
    robo.update_params('misc', params)
    return robo
Exemple #8
0
def R3():
    var('x y z')
    f = x+y+z
    t1 = clock()
    a = [bool(f==f) for _ in range(10)]
    t2 = clock()
    return t2 - t1
Exemple #9
0
def R7():
    var('x')
    f = x**24+34*x**12+45*x**3+9*x**18 +34*x**10+ 32*x**21
    t1 = clock()
    a = [f.subs({x : random()}) for _ in xrange(10^4)]
    t2 = clock()
    return t2 - t1
def create_layer_sympy_var_and_maps(layer_prop=['z','kv','kh','et', 'mv',
                                                'surz', 'vacz']):
    """Create sympy variables and maps for use with integrating \
    to generate 1d spectral equations.
    
    Each x in layer prop will get a 'top', and 'bot', suffix
    Each 'xtop' will get mapped to 'xt[layer]', each 'xbot' to 'xb[layer] 
    and added to `prop_map` dict.
    Each s in layer prop will get a linear representation added to the 
    `linear_expression` dict:
        x = (xbot-xtop)/(zbot-ztop)*(z-zbot) +xtop
    `prop_map` will also get a 'mi' to m[i], and mj to m[j] map.
    'z, mi, mj' will become global variables
            
    Parameters
    ----------
    layer_prop : ``list`` of ``str``, optional
        label for properties that vary in a layer
        (default is ['z','kv','kh','et', 'mv', 'surz',' vacz'])
    
         
    Returns
    -------
    prop_map : ``dict``
        maps the string version of a variable to the sympy.tensor.IndexedBase 
        version e.g. prop_map['kvtop'] = kvt[layer]
    linear_expressions : ``dict``
        maps the string version of a variable to an expression describing how 
        that varibale varies linearly within a layer    
        
    Examples
    --------
    >>> prop_map, linear_expressions = create_layer_sympy_var_and_maps(layer_prop=['z','kv'])
    >>> prop_map
    {'kvtop': kvt[layer], 'mi': m[i], 'mj': m[j], 'zbot': zb[layer], 'ztop': zt[layer], 'kvbot': kvb[layer]}
    >>> linear_expressions
    {'z': z, 'kv': kvtop + (kvbot - kvtop)*(z - ztop)/(zbot - ztop)}

    """
    #http://www.daniweb.com/software-development/python/threads/111526/setting-a-string-as-a-variable-name    
    m = sympy.tensor.IndexedBase('m')
    i = sympy.tensor.Idx('i')
    j = sympy.tensor.Idx('j')
    layer = sympy.tensor.Idx('layer')
    
    sympy.var('z, mi, mj')
    suffix={'t':'top','b': 'bot'}        
    prop_map = {}
    linear_expressions ={}
    
    prop_map['mi'] = m[i]
    prop_map['mj'] = m[j]
    
    for prop in layer_prop:            
        for s1, s3 in suffix.iteritems():
            vars()[prop + s1] = string_to_IndexedBase(prop + s1)            
            sympy.var(prop + s3)                        
            prop_map[prop + s3] = vars()[prop + s1][layer]        
        linear_expressions[prop]=linear(z, ztop, eval(prop+suffix['t']), zbot, eval(prop+suffix['b']))
    return (prop_map, linear_expressions)
Exemple #11
0
def parse_formulas(formulas, variables):
    """
    Takes formulas as a dict of strings and returns a dict
    where dependent (left-hand side) variable and (right-hand side) formula
    are separated and converted to sympy expressions.

    input variable example:
    formulas = {'a(t)=a(t-1)*a_rate(t)': 6, 'b(t)=b_share(t)*a(t)': 11}

    output example:
    formulas_dict = {5: {'dependent_var': a(t), 'formula': a(t-1)*a_rate(t)},
                     9: {'dependent_var': b(t), 'formula': b(t-1)+2}}

    5, 6, 9, 11 are the row indices in the sheet. Row indices in formulas_dict changed to rows with variables.
    These rows contain data and are used to fill in formulas in forecast period.
    a(t), b(t-1)+2, ... are sympy expressions.
    """
    varirable_list = list(variables.keys()) + TIME_INDEX_VARIABLES

    # declares sympy variables
    var(" ".join(varirable_list))
    parsed_formulas = dict()

    for formula_string in formulas.keys():
        # removing white spaces
        formula_string = formula_string.strip()
        dependent_var, formula = formula_string.split("=")
        dependent_var = evaluate_variable(dependent_var)
        formula = evaluate_variable(formula)
        # finding the row where the formula will be applied - may be a function
        row_index = variables[str(dependent_var.func)]
        parsed_formulas[row_index] = {"dependent_var": dependent_var, "formula": formula}

    return parsed_formulas
Exemple #12
0
def check_expression(expr, var_symbols):
    """Does eval(expr) both in Sage and SymPy and does other checks."""

    # evaluate the expression in the context of Sage:
    if var_symbols:
        sage.var(var_symbols)
    a = globals().copy()
    # safety checks...
    assert not "sin" in a
    a.update(sage.__dict__)
    assert "sin" in a
    e_sage = eval(expr, a)
    assert not isinstance(e_sage, sympy.Basic)

    # evaluate the expression in the context of SymPy:
    if var_symbols:
        sympy.var(var_symbols)
    b = globals().copy()
    assert not "sin" in b
    b.update(sympy.__dict__)
    assert "sin" in b
    b.update(sympy.__dict__)
    e_sympy = eval(expr, b)
    assert isinstance(e_sympy, sympy.Basic)

    # Do the actual checks:
    assert sympy.S(e_sage) == e_sympy
    assert e_sage == sage.SR(e_sympy)
Exemple #13
0
def variables(rows, cols, pivots, linear=False):
    """
    Returns a symbolic matrix with as many rows
    as the value of rows and as many columns as
    the value of cols.  The pivots determine the
    position of the last nonzero row.
    The length of the list pivots must equal the
    value of the parameter cols.
    If linear, then the names of the variables
    will following a linear indexing scheme as
    defined by the function double2linear.
    """
    result = sp.Matrix(rows, cols, lambda i, j: 0)
    for i in range(cols):
        result[i, i] = 1
    for k in range(cols):
        for i in range(k+1, pivots[k]+1):
            if linear:
                idx = double2linear(rows, cols, i+1, k+1)
                name = 'x' + str(idx)
            else:
                name = 'x' + '_' + str(i+1) + '_' + str(k+1)
            sp.var(name)
            result[i, k] = eval(name)
    return result
Exemple #14
0
def random_potentials( k ) :
	gios = gio_list_to_var_expr( globGIOList )
	variables = get_all_variables( gios )
	sym.var( variables )
	
	gios = map( lambda cycle : map( eval, cycle ), gios )
	giosShort = map( lambda cycle : reduce( lambda x, y : x * y, cycle ), [ c for c in gios if len( c ) > 2 ] )
	gios = str( map( lambda cycle : reduce( lambda x, y : x * y, cycle ), gios ) )
	
	index, samples, wList = 0, [], ''
	fh = open( fileDict['bg_m2in_r_file'] % k, 'w' )
	while index < globSampleSize :
		rand = random_number( 1, globBaseNumber ** len( globBigGIOList ) )
		coeffs = to_digits( rand )
		if rand in samples or to_number( to_complement_digits( coeffs ) ) in samples :
			continue
		index += 1
		
		w = inner_prod( [ globJointCoeffTuple[c] for c in coeffs ], giosShort )
		fterms = str( map( w.diff, variables ) )
		fh.write( gen_m2_input( gios, fterms, variables ) )
		wList += wterm_to_expr( globBigGIOList, coeffs )
	
	if wList :
		open( fileDict['bg_spot_r_file'] % k, 'w' ).write( wList )
	return index
Exemple #15
0
def test_var_accepts_comma():
    v1 = var('x y z')
    v2 = var('x,y,z')
    v3 = var('x,y z')

    assert v1 == v2
    assert v1 == v3
Exemple #16
0
def test_var():
    var("a")
    assert a  == Symbol("a")

    var("b bb cc zz _x")
    assert b  == Symbol("b")
    assert bb == Symbol("bb")
    assert cc == Symbol("cc")
    assert zz == Symbol("zz")
    assert _x == Symbol("_x")

    v = var(['d','e','fg'])
    assert d  == Symbol('d')
    assert e  == Symbol('e')
    assert fg == Symbol('fg')

    # check return value
    assert v  == (d, e, fg)

    # see if var() really injects into global namespace
    raises(NameError, "z1")
    make_z1()
    assert z1 == Symbol("z1")

    raises(NameError, "z2")
    make_z2()
    assert z2 == Symbol("z2")
Exemple #17
0
def wall_function_momentum_traction(uvec, nvec, p, k, eps, x, y, tau_type, symbolic=True, parts=True):
    if symbolic:
        cmu = sp.var('c_{\mu}')
        yStarPlus = sp.var('y_{\mu}')
    else:
        cmu = 0.09
        yStarPlus = 11.06
    if tau_type == "vel":
        uvec_norm = sp.sqrt(uvec.transpose() * uvec)[0, 0]
        uTau = uvec_norm / yStarPlus
    elif tau_type == "kin":
        uTau = cmu**.25 * sp.sqrt(k)
    else:
        raise ValueError("Must either pass 'vel' or 'kin' for tau_type")

    mu, rho = sp.var('mu rho')
    normal_stress_term = (-nvec.transpose() * mu * strain_rate(uvec, x, y) * nvec * nvec.transpose()).transpose()
    tangential_stress_term = uTau / yStarPlus * uvec
    muT = rho * cmu * k * k / eps
    turbulent_stress_term = (-nvec.transpose() * muT * strain_rate(uvec, x, y)).transpose()
    if parts:
        pressure_term = (nvec.transpose() * eye2() * p).transpose()
    else:
        pressure_term = zeroVec2()
    return normal_stress_term + tangential_stress_term + turbulent_stress_term + pressure_term
def test_symbolic_twoport():
    circuit.default_toolkit = symbolic
    cir = SubCircuit()

    k = symbolic.kboltzmann
    var('R1 R0 C1 w T', real=True, positive=True)
    s = 1j*w

    cir['R0'] = R(1, gnd, r=R0)
    cir['R1'] = R(1, 2, r=R1)
#    cir['C1'] = C(2, gnd, c=C1)

    ## Add an AC source to verify that the source will not affect results
#    cir['IS'] = IS(1, gnd, iac=1) 

    ## Run symbolic 2-port analysis
    twoport_ana = TwoPortAnalysis(cir, Node('1'), gnd, Node('2'), gnd,
                                  noise = True, toolkit=symbolic,
                                  noise_outquantity = 'v')
    result = twoport_ana.solve(freqs=s, complexfreq=True)
    
    ABCD = Matrix(result['twoport'].A)
    ABCD.simplify()

    assert_array_equal(ABCD, np.array([[1 + 0*R1*C1*s, R1],
                                    [(1 + 0*R0*C1*s + 0*R1*C1*s) / R0,  (R0 + R1)/R0]]))

    assert_array_equal(simplify(result['Sin'] - (4*k*T/R0 + 4*R1*k*T/R0**2)), 0)
    assert_array_equal(simplify(result['Svn']), 4*k*T*R1)
Exemple #19
0
def rx90():
    """Generate Robot instance of RX90"""
    robo = Robot('RX90', 6, 6, 6, False)
    # table of geometric parameters RX90
    robo.sigma = [2, 0, 0, 0, 0, 0, 0, 0]
    robo.alpha = [0, 0, pi/2, 0, -pi/2, pi/2, -pi/2]
    robo.d = [0, 0, 0, var('D3'), 0, 0, 0]
    robo.theta = [0] + list(var('th1:7'))
    robo.r = [0, 0, 0, 0, var('RL4'), 0, 0]
    robo.b = [0, 0, 0, 0, 0, 0, 0]
    robo.gamma = [0, 0, 0, 0, 0, 0, 0]
    robo.mu = [0, 1, 1, 1, 1, 1, 1]
    robo.structure = tools.SIMPLE
#        robo.w0 = zeros(3, 1)
#        robo.wdot0 = zeros(3, 1)
#        robo.v0 = zeros(3, 1)
#        robo.vdot0 = zeros(3, 1)
#        robo.qdot = [var('QP{0}'.format(i)) for i in num]
#        robo.qddot = [var('QDP{0}'.format(i)) for i in num]
#        robo.Nex= [zeros(3, 1) for i in num]
#        robo.Nex[-1] = Matrix(var('CX{0}, CY{0}, CZ{0}'.format(robo.NJ)))
#        robo.Fex = [zeros(3, 1) for i in num]
#        robo.Fex[-1] = Matrix(var('FX{0}, FY{0}, FZ{0}'.format(robo.NJ)))
#        robo.FS = [var('FS{0}'.format(i)) for i in num]
#        robo.IA = [var('IA{0}'.format(i)) for i in num]
#        robo.FV = [var('FV{0}'.format(i)) for i in num]
#        robo.MS = [Matrix(var('MX{0}, MY{0}, MZ{0}'.format(i))) for i in num]
#        robo.M = [var('M{0}'.format(i)) for i in num]
#        robo.GAM = [var('GAM{0}'.format(i)) for i in num]
#        robo.J = [Matrix(3, 3, var(('XX{0}, XY{0}, XZ{0}, '
#                            'XY{0}, YY{0}, YZ{0}, '
#                            'XZ{0}, YZ{0}, ZZ{0}').format(i))) for i in num]
#        robo.G = Matrix([0, 0, var('G3')])
#        robo.num.append(0)
    return robo
Exemple #20
0
    def compute_psi_stats(self):
        # define some normal distributions
        mus = [sp.var("mu_%i" % i, real=True) for i in range(self.input_dim)]
        Ss = [sp.var("S_%i" % i, positive=True) for i in range(self.input_dim)]
        normals = [
            (2 * sp.pi * Si) ** (-0.5) * sp.exp(-0.5 * (xi - mui) ** 2 / Si) for xi, mui, Si in zip(self._sp_x, mus, Ss)
        ]

        # do some integration!
        # self._sp_psi0 = ??
        self._sp_psi1 = self._sp_k
        for i in range(self.input_dim):
            print "perfoming integrals %i of %i" % (i + 1, 2 * self.input_dim)
            sys.stdout.flush()
            self._sp_psi1 *= normals[i]
            self._sp_psi1 = sp.integrate(self._sp_psi1, (self._sp_x[i], -sp.oo, sp.oo))
            clear_cache()
        self._sp_psi1 = self._sp_psi1.simplify()

        # and here's psi2 (eek!)
        zprime = [sp.Symbol("zp%i" % i) for i in range(self.input_dim)]
        self._sp_psi2 = self._sp_k.copy() * self._sp_k.copy().subs(zip(self._sp_z, zprime))
        for i in range(self.input_dim):
            print "perfoming integrals %i of %i" % (self.input_dim + i + 1, 2 * self.input_dim)
            sys.stdout.flush()
            self._sp_psi2 *= normals[i]
            self._sp_psi2 = sp.integrate(self._sp_psi2, (self._sp_x[i], -sp.oo, sp.oo))
            clear_cache()
        self._sp_psi2 = self._sp_psi2.simplify()
def main():
    var("mu nu rho theta phi sigma tau a t x y z w")

    transform("polar", Matrix([rho*cos(phi), rho*sin(phi)]), [rho, phi])

    transform("cylindrical", Matrix([rho*cos(phi), rho*sin(phi), z]),
            [rho, phi, z])

    transform("spherical",
            Matrix([rho*sin(theta)*cos(phi), rho*sin(theta)*sin(phi),
                rho*cos(theta)]),
            [rho, theta, phi],
            recursive=True
            )

    transform("rotating disk",
            Matrix([t, x*cos(w*t)-y*sin(w*t), x*sin(w*t)+y*cos(w*t), z]),
            [t, x, y, z])

    transform("parabolic",
            Matrix([sigma*tau, (tau**2-sigma**2)/2]),
            [sigma, tau])

    # too complex:
    #transform("bipolar",
    #        Matrix([a*sinh(tau)/(cosh(tau)-cos(sigma)),
    #            a*sin(sigma)/(cosh(tau)-cos(sigma))]),
    #        [sigma, tau]
    #        )

    transform("elliptic",
            Matrix([a*cosh(mu)*cos(nu), a*sinh(mu)*sin(nu)]),
            [mu, nu]
            )
Exemple #22
0
def test_var_return():
    raises(ValueError, lambda: var(''))
    v2 = var('q')
    v3 = var('q p')

    assert v2 == Symbol('q')
    assert v3 == (Symbol('q'), Symbol('p'))
def test_FunctionWrapper():
    import sympy
    sympy.var("n, m, theta, phi")
    r = sympy.Ynm(n, m, theta, phi)
    s = Integer(2)*r
    assert isinstance(s, Mul)
    assert isinstance(s.args[1]._sympy_(), sympy.Ynm)
Exemple #24
0
def test_coeff2_0():
    var('r, kappa')
    psi = Function("psi")
    g = 1/r**2 * (2*r*psi(r).diff(r, 1) + r**2 * psi(r).diff(r, 2))
    g = g.expand()

    assert g.coeff(psi(r).diff(r, 2)) == 1
Exemple #25
0
 def test_robo_misc(self):
     print "######## test_robo_misc ##########"
     self.robo = symoro.Robot.SR400()
     q = list(var('th1:10'))
     self.assertEqual(self.robo.q_vec, q)
     self.assertEqual(self.robo.chain(6), [6, 5, 4, 3, 2, 1])
     self.assertEqual(self.robo.chain(6, 3), [6, 5, 4])
     self.assertEqual(self.robo.loop_chain(8, 9), [8, 9])
     self.assertEqual(self.robo.loop_chain(0, 6), [0, 1, 2, 3, 4, 5, 6])
     self.assertEqual(self.robo.loop_chain(6, 0), [6, 5, 4, 3, 2, 1, 0])
     self.assertEqual(self.robo.loop_chain(9, 10), [9, 8, 7, 1, 2, 3, 10])
     self.assertEqual(self.robo.loop_terminals, [(9, 10)])
     l1 = self.robo.get_geom_head()
     l2 = self.robo.get_dynam_head()
     l3 = self.robo.get_ext_dynam_head()
     for Name in l1[1:] + l2[1:] + l3[1:]:
         for i in xrange(self.robo.NL):
             if Name in symoro.INT_KEYS:
                 self.assertEqual(self.robo.put_val(i, Name, i), symoro.OK)
             else:
                 v = var(Name + str(i))
                 self.assertEqual(self.robo.put_val(i, Name, v), symoro.OK)
     for Name in l3[1:]+l2[1:]+l1[1:]:
         for i in xrange(self.robo.NL):
             if Name in symoro.INT_KEYS:
                 self.assertEqual(self.robo.get_val(i, Name), i)
             else:
                 v = var(Name + str(i))
                 self.assertEqual(self.robo.get_val(i, Name), v)
def test__validate_production_function():
    """Testing validation of production function attribute."""

    # production function must have type sym.Basic
    def invalid_F(x, y, l, r, A, kappa, nu, rho, gamma):
        """Valid F must return a SymPy expression."""
        return r * A * kappa * (nu * x**rho + (1 - nu) * (y * (l / r))**rho)**(gamma / rho)

    with nose.tools.assert_raises(AttributeError):
        models.Model('positive', workers, firms, production=invalid_F,
                     params=valid_F_params)

    # production function must share vars with workers and firms
    m, n = sym.var('m, n')
    invalid_F = r * A * kappa * (nu * m**rho + (1 - nu) * (n * (l / r))**rho)**(gamma / rho)

    with nose.tools.assert_raises(AttributeError):
        models.Model('negative', workers, firms, production=invalid_F,
                     params=valid_F_params)

    # production function must depend on r and l
    m, n = sym.var('m, n')
    invalid_F = r * A * kappa * (nu * x**rho + (1 - nu) * (y * (m / n))**rho)**(gamma / rho)

    with nose.tools.assert_raises(AttributeError):
        models.Model('positive', workers, firms, production=invalid_F,
                     params=valid_F_params)
Exemple #27
0
def alphaBetaToTransfer(adjMat, alphas, betas):
    s = sympy.Symbol('s')
    subs = {}

    # iterate over the columns of the adjacency matrix
    for i, col in enumerate(adjMat.getA()):
        expr = sympy.S(0)
        i += 1
        # iterate over the elements in each column of the adjacency matrix
        # this is to build the replacement expression for what were once "output to env"s
        # but are now the turnover rates of each node
        for j, elem in enumerate(col):
            j += 1
            if elem != 0:
                expr += (-sympy.var('a_%d%d' % (j,i)))

        subs[sympy.var('a_%d%d' % (i,i))] = expr

    #print "*** VAR->EXPR SUBSTITUTIONS: "
    #print subs

    for pos in range(0, len(betas)):
        orderedKeysBeta = getOrderedKeys(betas[pos])
        for key in orderedKeysBeta:
            betas[pos][s**key] = sympy.simplify(sympy.expand(betas[pos][s**key].xreplace(subs)))

        #finished all the betas so add the alphas, but only once
        orderedKeysAlpha = getOrderedKeys(alphas[pos])
        for key in orderedKeysAlpha:
            alphas[pos][s**key] = sympy.simplify(sympy.expand(alphas[pos][s**key].xreplace(subs)))
Exemple #28
0
def Parse(str):
    print("Parse(): str = %s" % str)

    # Inspired from email mailing list sympy, Jan 29, 2015, Aaron Meurer

    #exp0 = parse_expr("a1*x1**2+a2*x1+a3+a4*x1*x2+a5*x2**2") #, transformations=(auto_number,auto_symbol))
    exp = parse_expr(str)

    print("Parse(): exp = %s" % exp)

    #exp0.subs(a1,10)

    for crtSym in exp.atoms(sympy.Symbol):
        sympy.var(crtSym.name) #__str__())
    if False:
        for crtSym in exp.atoms(): #sympy.Symbol):
            #sympy.var(crtSym. name)
            print crtSym

    """
    auto_symbol doesn't do namespace injection.
      It just means that the parser won't fail with a NameError (undefined names in the namespace that the parser users will be converted to Symbols).
      Your hack works (I would use each_sym.name instead of __str__(), and note that str(each_sym) is the same as each_sym.__str__()).
    """

    #print exp.subs(cosTheta, 0.1)
    return exp
Exemple #29
0
 def setUp(self):
     # setup params for symbolic computation
     th1 = var('th1')
     l1 = var('L1')
     self.sym_gamma = 0
     self.sym_b = 0
     self.sym_alpha = 0
     self.sym_d = l1
     self.sym_theta = th1
     self.sym_r = 0
     self.sym_tmat = Matrix([
         [cos(th1), -sin(th1), 0, l1],
         [sin(th1), cos(th1), 0, 0],
         [0, 0, 1, 0],
         [0, 0, 0, 1]
     ])
     # setup params for numeric computation
     th1 = pi/2
     l1 = 1
     self.num_gamma = 0
     self.num_b = 0
     self.num_alpha = 0
     self.num_d = l1
     self.num_theta = th1
     self.num_r = 0
     self.num_tmat = Matrix([
         [cos(th1), -sin(th1), 0, l1],
         [sin(th1), cos(th1), 0, 0],
         [0, 0, 1, 0],
         [0, 0, 0, 1]
     ])
Exemple #30
0
    def eq_sympy(input_dim, output_dim, ARD=False):
        """
        Latent force model covariance, exponentiated quadratic with multiple outputs. Derived from a diffusion equation with the initial spatial condition layed down by a Gaussian process with lengthscale given by shared_lengthscale.

        See IEEE Trans Pattern Anal Mach Intell. 2013 Nov;35(11):2693-705. doi: 10.1109/TPAMI.2013.86. Linear latent force models using Gaussian processes. Alvarez MA, Luengo D, Lawrence ND.

        :param input_dim: Dimensionality of the kernel
        :type input_dim: int
        :param output_dim: number of outputs in the covariance function.
        :type output_dim: int
        :param ARD: whether or not to user ARD (default False).
        :type ARD: bool

        """
        real_input_dim = input_dim
        if output_dim>1:
            real_input_dim -= 1
        X = sp.symbols('x_:' + str(real_input_dim))
        Z = sp.symbols('z_:' + str(real_input_dim))
        scale = sp.var('scale_i scale_j',positive=True)
        if ARD:
            lengthscales = [sp.var('lengthscale%i_i lengthscale%i_j' % i, positive=True) for i in range(real_input_dim)]
            shared_lengthscales = [sp.var('shared_lengthscale%i' % i, positive=True) for i in range(real_input_dim)]
            dist_string = ' + '.join(['(x_%i-z_%i)**2/(shared_lengthscale%i**2 + lengthscale%i_i**2 + lengthscale%i_j**2)' % (i, i, i) for i in range(real_input_dim)])
            dist = parse_expr(dist_string)
            f =  variance*sp.exp(-dist/2.)
        else:
            lengthscales = sp.var('lengthscale_i lengthscale_j',positive=True)
            shared_lengthscale = sp.var('shared_lengthscale',positive=True)
            dist_string = ' + '.join(['(x_%i-z_%i)**2' % (i, i) for i in range(real_input_dim)])
            dist = parse_expr(dist_string)
            f =  scale_i*scale_j*sp.exp(-dist/(2*(lengthscale_i**2 + lengthscale_j**2 + shared_lengthscale**2)))
        return kern(input_dim, [spkern(input_dim, f, output_dim=output_dim, name='eq_sympy')])
Exemple #31
0
        "f_51":   "f_foliage2stlit",
        "f_52":   "f_wood2stlit",
        "f_43":   "f_fineroots2metlit",
        "f_53":   "f_fineroots2stlit",
        "f_64":   "f_metlit2fastsom",
        "f_65":   "f_stlit2fastsom",
        "f_75":   "f_stlit2slowsom",
        "f_76":   "f_fastsom2slowsom",
        "f_86":   "f_fastsom2passsom",
        "f_67":   "f_slowsom2fastsom",
        "f_87":   "f_slowsom2passsom",
        "f_68":   "f_passsom2fastsom",
}
from sympy import var, Symbol
for old, new in rename_dict.items():
    var(old)
    var(new)
subs_dict = { 
    Symbol(old): Symbol(new)
    for old, new in rename_dict.items()
}
# We want to compute the fluxes with renamed symbols.
# We first check what we have to substitute.
# +

mvs_TECO.provided_mvar_types


# -

import sympy
from sympy import Matrix

from pim.sympytools import print_as_sparse, print_as_array, print_as_full

sympy.var('u, v, w, phix, phiy')
sympy.var('nx1, ny1')
sympy.var('nx2, ny2')
sympy.var('nx3, ny3')
sympy.var('nx4, ny4')
sympy.var('f11, f12, f13, f14')
sympy.var('f21, f22, f23, f24')
sympy.var('f31, f32, f33, f34')
sympy.var('f41, f42, f43, f44')
sympy.var('A11, A12, A16, A22, A26, A66')
sympy.var('B11, B12, B16, B22, B26, B66')
sympy.var('D11, D12, D16, D22, D26, D66')
sympy.var('E44, E45, E55')
sympy.var('le1, le2, le3, le4, Ac')

# approximation for linear interpolation within a tria
# u = u1*f1 + u2*f2 + u3*f3
# v = v1*f1 + v2*f2 + v3*f3
# w = w1*f1 + w2*f2 + w3*f3
# phix = phix1*f1 + phix2*f2 + phix3*f3
# phiy = phiy1*f1 + phiy2*f2 + phiy3*f3

# in matrix form
# u =    [f1, 0, 0, 0, 0, f2, 0, 0, 0, 0, f3, 0, 0, 0, 0] * [u1, v1, w1, phix1, phiy1, u2, v2, ... , u5, v5, w5, phix5, phiy5]
# v =    [0, f1, 0, 0, 0, 0, f2, 0, 0, 0, 0, f3, 0, 0, 0] *   ||
# w =    [0, 0, f1, 0, 0, 0, 0, f2, 0, 0, 0, 0, f3, 0, 0] *   ||
Exemple #33
0
 def _cell_variable(cell):
     """
     Return the appropriate variable to track the number of point in the
     given cell.
     """
     return var("y_{}_{}".format(*cell))
Exemple #34
0
class MonotoneTreeEnumeration(Enumeration):
    """
    Enumeration strategy for a monotone tree tiling.

    A tiling is a monotone tree if it is local, its cell graph is a tree and
    all but possibly one cell are monotone.

    A monotone tree tiling can be described by a tree where the verified object
    are the cells of the tiling.
    """

    _tracking_var = var("t")

    def verified(self):
        no_req_list = all(len(rl) == 1 for rl in self.tiling.requirements)
        num_non_monotone = sum(1 for c in self.tiling.active_cells
                               if not self.tiling.is_monotone_cell(c))
        return (self.tiling.dimensions != (1, 1)
                and LocalEnumeration(self.tiling).verified()
                and no_req_list and num_non_monotone <= 1 and is_tree(
                    self.tiling.active_cells, self.tiling.cell_graph()))

    def _cell_tree_traversal(self, start):
        """
        Traverse the tree by starting at `start` and always visiting an entire
        row or column before going somewhere else.

        The start vertices is not yielded.
        """
        queue = deque(
            chain(self.tiling.cells_in_col(start[0]),
                  self.tiling.cells_in_row(start[1])))
        visited = set([start])
        while queue:
            cell = queue.popleft()
            if cell not in visited:
                yield cell
                visited.add(cell)
                queue.extend(self.tiling.cells_in_row(cell[1]))
                queue.extend(self.tiling.cells_in_col(cell[0]))

    def _visted_cells_aligned(self, cell, visited):
        """
        Return the cells that are in visited and in the same row or column as
        `cell`.
        """
        row_cells = self.tiling.cells_in_row(cell[1])
        col_cells = self.tiling.cells_in_col(cell[0])
        return (c for c in visited if (c in row_cells or c in col_cells))

    def get_genf(self, **kwargs) -> Expr:
        # pylint: disable=too-many-locals
        if not self.verified():
            raise InvalidOperationError("The tiling is not verified")
        if self.tiling.extra_parameters:
            raise NotImplementedError(
                "Not implemented monotone verified with extra parameters.")
        try:
            start = next(c for c in self.tiling.active_cells
                         if not self.tiling.is_monotone_cell(c))
        except StopIteration:
            start = next(iter(self.tiling.active_cells))
        start_basis = self.tiling.cell_basis()[start][0]
        start_reqs = [[p] for p in self.tiling.cell_basis()[start][1]]
        start_tiling = self.tiling.from_perms(obstructions=start_basis,
                                              requirements=start_reqs)
        start_gf = start_tiling.get_genf()
        F = start_gf.subs({x: x * self._cell_variable(start)})
        visited = set([start])
        for cell in self._cell_tree_traversal(start):
            interleaving_cells = self._visted_cells_aligned(cell, visited)
            substitutions = {
                scv: scv * self._tracking_var
                for scv in map(self._cell_variable, interleaving_cells)
            }
            F_tracked = F.subs(substitutions)
            minlen, maxlen = self._cell_num_point(cell)
            if maxlen is None:
                F = self._interleave_any_length(F_tracked, cell)
                if minlen > 0:
                    F -= self._interleave_fixed_lengths(
                        F_tracked, cell, 0, minlen - 1)
            else:
                F = self._interleave_fixed_lengths(F_tracked, cell, minlen,
                                                   maxlen)
            visited.add(cell)
        F = simplify(F.subs({v: 1 for v in F.free_symbols if v != x}))
        # A simple test to warn us if the code is wrong
        if __debug__:
            lhs = taylor_expand(F, n=6)
            rhs = [len(list(self.tiling.objects_of_size(i))) for i in range(7)]
        assert lhs == rhs, f"Bad genf\n{lhs}\n{rhs}"
        return F

    @staticmethod
    def _cell_variable(cell):
        """
        Return the appropriate variable to track the number of point in the
        given cell.
        """
        return var("y_{}_{}".format(*cell))

    def _interleave_any_length(self, F, cell):
        """
        Return the generating function for interleaving any number of point of
        a monotone sequence into the region tracked by
        `MonotoneTreeEnumeration._tracking_var` in `F`.
        A variable is added to track the number of point in cell.
        """
        cell_var = self._cell_variable(cell)
        gap_filler = 1 / (1 - x * cell_var)
        return F.subs({self._tracking_var: gap_filler}) * gap_filler

    def _interleave_fixed_lengths(self, F, cell, min_length, max_length):
        """
        Return the generating function for interleaving between min_point and
        max_point (both included) number of point of
        a monotone sequence into the region tracked by
        `MonotoneTreeEnumeration._tracking_var` in `F`.
        A variable is added to track the number of point in cell.
        """
        return sum(
            self._interleave_fixed_length(F, cell, i)
            for i in range(min_length, max_length + 1))

    def _interleave_fixed_length(self, F, cell, num_point):
        """
        Return the generating function for interleaving num_point
        number of point of a monotone sequence into the region tracked by
        `MonotoneTreeEnumeration._tracking_var` in `F`.
        A variable is added to track the number of point in cell.
        """
        new_genf = self._tracking_var**num_point * F
        for i in range(1, num_point + 1):
            new_genf = diff(new_genf, self._tracking_var) / i
        new_genf *= self._cell_variable(cell)**num_point
        new_genf *= x**num_point
        return new_genf.subs({self._tracking_var: 1})

    def _cell_num_point(self, cell):
        """
        Return a pair of integer `(min, max)` that describe the possible
        number of point in the cell. If the number of point is unbounded,
        `max` is None.

        We assume that the cell is monotone
        """
        obs, reqs = self.tiling.cell_basis()[cell]
        ob_lens = sorted(map(len, obs))
        assert ob_lens[0] == 2, "Unexpected obstruction"
        assert len(reqs) <= 1, "Unexpected number of requirement"
        if len(obs) == 1:
            maxlen = None
        elif len(obs) == 2:
            maxlen = ob_lens[1] - 1
        else:
            raise RuntimeError("Unexpected number of obstructions")
        if not reqs:
            minlen = 0
        elif len(reqs) == 1:
            minlen = len(reqs[0])
        else:
            raise RuntimeError("Unexpected number of requirements")
        return minlen, maxlen
Exemple #35
0
             'lower_hs_stack',
             'effective_top_tube',
             # 'seat_tube_length',
             # 'saddle_height',
             # 'saddle_extension',
            ]
            
constants = [
             'bb_height',
             'head_tube_angle',
             'crown_to_steering_axis_intersection',
             'front_wheelbase',
             'ground_trail'
            ]

for v in var_names + constants:
    sp.var(v)   

input_names = var_names
            
equations = [
             sp.Eq(stack, (crown_to_steering_axis_intersection + head_tube_length + lower_hs_stack)*sp.sin(head_tube_angle*to_rad)-bb_height),
             sp.Eq(reach, (front_wheelbase+ground_trail)-(crown_to_steering_axis_intersection + head_tube_angle + lower_hs_stack)*sp.cos(head_tube_angle*to_rad)),
             sp.Eq(ht_top_to_ground, stack+bb_height),
             sp.Eq(effective_top_tube, stack * sp.tan((90-seat_tube_angle)*to_rad) + reach),
             # sp.Eq(saddle_extension, saddle_height - seat_tube_length),
            ]
            
input_vars, soln_vars, solns = solution_handler(var_names=var_names, input_names=input_names, equations=equations)
            
Exemple #36
0
    def tick(self, tick):
        unknowns = tick.blackboard.get(
            'unknowns')  # the current list of unknowns
        R = tick.blackboard.get('Robot')  # the current robot instance
        if (self.BHdebug):
            print "running: ", self.Name
            print 'number of matrix equations: ', len(R.mequation_list)
            print 'first matrix equation: ', R.mequation_list[0]
            print 'number of input equations: ', len(
                R.mequation_list[0].get_kequation_list())
            print "unknowns:"
            for u in unknowns:
                print u.symbol, ', solved: ', u.solved
            print ''

        #   We're going to look at the first N equations in the mequation_list
        N = 1  #  were only looking at first 2 matrix equations (at least for now)
        assert (N <= len(
            R.mequation_list)), 'sub_transform test wants too many meqns '

        # identify elements of eqns where another elemnet can be substituted in
        #    to eliminate unknowns
        #
        found = False

        sp.var('a z')
        z = a - a  #  (define symbolic zero!)

        cols = [0, 1, 2, 3]
        rows = [0, 1, 2]  # we don't care about row 4 ([0,0,0,1])!

        for m in range(0, N):
            for i in rows:
                for j in cols:
                    e2 = R.mequation_list[m].Ts[i, j]
                    for k in rows:
                        for l in cols:
                            e1 = R.mequation_list[m].Ts[k, l]
                            # substitute with e1 or -e1      ####################################3    *******    adapt ".has" to both LHS and RHS??
                            if ((e1 != e2) and e2 != z
                                    and e2.has(e1)):  # we found a substitution
                                if (self.BHdebug):
                                    print ''
                                    print self.Name, ' found a sub transform (+)'
                                    print e1, ' / ', e2
                                    print 'new: ', e2, ' = ', e2.subs(e1, e2)
                                nold = count_unknowns(unknowns, e2)
                                new = e2.subs(
                                    e1,
                                    R.mequation_list[m].Td[k, l])  # substitute
                                nnew = count_unknowns(unknowns, new)
                                if (self.BHdebug):
                                    print 'Unknowns: old/new:', nold, '/', nnew
                                    print 'Prop Sub: ', e2, '/', new
                                if (nnew < nold):
                                    R.mequation_list[m].Ts[i, j] = new
                                    found = True

                            elif ((e1 != e2) and e2 != z and
                                  e2.has(-e1)):  # we found a substitution -e1
                                if (self.BHdebug):
                                    print self.Name, ' found a (-) sub transform'
                                    print e1, '/', e2
                                nold = count_unknowns(unknowns, e2)
                                new = e2.subs(-e1,
                                              -R.mequation_list[m].Td[k, l]
                                              )  # substitute with -e1
                                nnew = count_unknowns(unknowns, new)
                                if (self.BHdebug):
                                    print 'Unknowns: old/new:', nold, '/', nnew
                                    print 'Prop Sub: ', e2, '/', new
                                if (nnew < nold):
                                    R.mequation_list[m].Ts[i, j] = new
                                    found = True

        if found:
            #  put the tmp_eqns list back into R !!!!  ******************************
            [L1, L2, L3p] = R.scan_for_equations(unknowns)
            tick.blackboard.set('eqns_1u', L1)
            tick.blackboard.set('eqns_2u', L2)
            tick.blackboard.set('eqns_3pu', L3p)
            tick.blackboard.set('Robot', R)

        return b3.SUCCESS
Exemple #37
0
#!/usr/bin/python3

import ralgo
import sympy
import matplotlib.pyplot as plt

sympy.var("s T ksi Ki Kp")

W = (Ki * 1 / s + Kp) * 1 / s
W = W / (1 + W)  #* 1/s
W = W.factor()
W = W.subs([(Ki, 1 / (T**2)), (Kp, 2 * ksi / T)])
print(W)

#W = (2*ksi*T*s+1)/(T**2*s**2+2*ksi*T*s+1)

W = W.subs([(T, 1), (ksi, 2)])

W = (4 * s + 1) / (s**2 + 4 * s + 1)
#W = (1)/(s**2 + 4*s + 1)

#W = (1+2*s)/(s**2 + 2*s + 1)
print(W)

#ralgo.plot_step_responce_tf(W, 30, 1000)
ralgo.plot_step_responce_il(W, 30, 1000)
plt.show()
Exemple #38
0
              title="Abstand",
              symbol="d",
              unit=r"\cm")
Tab.addColumn([J_30mA_err, J_50mA_err, J_75mA_err, J_100mA_err],
              title="Lichtintensität",
              symbol="J_{Ph}",
              unit=r"\milli\watt\per\cm\squared")
Tab.addColumn([P_ein_30mA, P_ein_50mA, P_ein_75mA, P_ein_100mA],
              title="Lichtleistung",
              symbol="P_{Ph}",
              unit=r"\milli\watt")
#Tab.save("Tabellen/Intensitaet_Leistung.tex")
#Tab.show()

print("Fehlergleichungen:")
D, o1, o2 = sym.var("d, d_1, d_2")
d = D - o1 - o2
d_Err = ErrorEquation(d, name="d")
print(d_Err.std)
A, J = sym.var("A, J")
P = A * J
P_Err = ErrorEquation(P, name="P")
print(P_Err.std)
I, U = sym.var("I, U")
P = I * U
P_Err = ErrorEquation(P, name="P")
print(P_Err.std)
R = U / I
R_Err = ErrorEquation(R, name="R")
print(R_Err.std)
P1, P2 = sym.var("P_Ph, P")
    def extract_sub_expressions(self,
                                cache_prefix='cache',
                                sub_prefix='sub',
                                prefix='XoXoXoX'):
        # Do the common sub expression elimination.
        common_sub_expressions, expression_substituted_list = sym.cse(
            self.expression_list, numbered_symbols(prefix=prefix))

        self.variables[cache_prefix] = []
        self.variables[sub_prefix] = []

        # Create dictionary of new sub expressions
        sub_expression_dict = {}
        for var, void in common_sub_expressions:
            sub_expression_dict[var.name] = var

        # Sort out any expression that's dependent on something that scales with data size (these are listed in cacheable).
        cacheable_list = []
        params_change_list = []
        # common_sube_expressions contains a list of paired tuples with the new variable and what it equals
        for var, expr in common_sub_expressions:
            arg_list = [e for e in expr.atoms() if e.is_Symbol]
            # List any cacheable dependencies of the sub-expression
            cacheable_symbols = [
                e for e in arg_list
                if e in cacheable_list or e in self.cacheable_vars
            ]
            if cacheable_symbols:
                # list which ensures dependencies are cacheable.
                cacheable_list.append(var)
            else:
                params_change_list.append(var)

        replace_dict = {}
        for i, expr in enumerate(cacheable_list):
            sym_var = sym.var(cache_prefix + str(i))
            self.variables[cache_prefix].append(sym_var)
            replace_dict[expr.name] = sym_var

        for i, expr in enumerate(params_change_list):
            sym_var = sym.var(sub_prefix + str(i))
            self.variables[sub_prefix].append(sym_var)
            replace_dict[expr.name] = sym_var

        for replace, void in common_sub_expressions:
            for expr, keys in zip(expression_substituted_list,
                                  self.expression_keys):
                setInDict(self.expressions, keys,
                          expr.subs(replace, replace_dict[replace.name]))
            for void, expr in common_sub_expressions:
                expr = expr.subs(replace, replace_dict[replace.name])

        # Replace original code with code including subexpressions.
        for keys in self.expression_keys:
            for replace, void in common_sub_expressions:
                setInDict(
                    self.expressions, keys,
                    getFromDict(self.expressions,
                                keys).subs(replace,
                                           replace_dict[replace.name]))

        self.expressions['parameters_changed'] = {}
        self.expressions['update_cache'] = {}
        for var, expr in common_sub_expressions:
            for replace, void in common_sub_expressions:
                expr = expr.subs(replace, replace_dict[replace.name])
            if var in cacheable_list:
                self.expressions['update_cache'][replace_dict[
                    var.name].name] = expr
            else:
                self.expressions['parameters_changed'][replace_dict[
                    var.name].name] = expr
Exemple #40
0
"""
This example shows how to work with the Hydrogen radial wavefunctions.
"""

from sympy import var, pprint, Integral, oo, Eq
from sympy.physics.hydrogen import R_nl

print "Hydrogen radial wavefunctions:"
var("r a")
print "R_{21}:"
pprint(R_nl(2, 1, a, r))
print "R_{60}:"
pprint(R_nl(6, 0, a, r))

print "Normalization:"
i = Integral(R_nl(1, 0, 1, r)**2 * r**2, (r, 0, oo))
pprint(Eq(i, i.doit()))

i = Integral(R_nl(2, 0, 1, r)**2 * r**2, (r, 0, oo))
pprint(Eq(i, i.doit()))

i = Integral(R_nl(2, 1, 1, r)**2 * r**2, (r, 0, oo))
pprint(Eq(i, i.doit()))
import numpy as np
from scipy import e, linalg as LA
from sympy import var

e2 = var('e2')

a = .105  # predator adult mortality rate
range_a = [0.01, 1]

b = 0.1  # Benefit to the predator of predator adult consumption rate of weevil
range_b = [.01, 1]

c = 0.3  # Negative impact of early harvesting on the weevil population (not being used)
range_c = [.01, 1]

p = .5  # predator adult population gain from nymphs
range_p = [.01, 1]

n = 10
range_n = [1, 10]

k = 100
range_n1 = [1, 250]

ke = .1635  # constant

H = .8
range_H = [.01, 1]

c1 = .15  # Negative impact on the aphids of predator consumption of aphids; previous values used: .1,2
range_c1 = [.01, 1]
import sympy
import scipy.misc
import sys
import itertools as it

from sympy import Rational as sRat
from operator import mul
from functools import partial as par

import simpleode.core.utils as utils
from functools import reduce

# A set of functions for symbolically calculating bdf forumlas.

# Define some (global) symbols to use
dts = list(sympy.var('Delta:9', real=True))
dys = list(sympy.var('Dy:9', real=True))
ys = list(sympy.var('y:9', real=True))

# subs i => step n+1-i (with Delta_{n+1} = t_{n+1} - t_n)


def divided_diff(order, ys, dts):
    """Caluclate divided differences of the list of values given
    in ys at points separated by the values in dts.

    Should work with symbols or numbers, only tested with symbols.
    """
    assert (len(ys) == order + 1)
    assert (len(dts) == order)
Exemple #43
0
    def get_equation(
        self, lhs_func: sympy.Function, rhs_funcs: Tuple[sympy.Function, ...]
    ) -> sympy.Eq:
        if max(self.min_points) > 1:
            raise NotImplementedError(
                "not implemented equation in the case of "
                "left or right containing more than one point"
            )
        rhs_func = rhs_funcs[0]
        subs: Dict[str, sympy.Expr] = {
            child: reduce(mul, [sympy.var(k) for k in parent_vars], 1)
            for child, parent_vars in self.reversed_extra_parameters.items()
        }
        left_vars = reduce(
            mul,
            [
                sympy.var(k)
                for k in self.left_sided_parameters
                if k not in self.parent_fusion_parameters
            ],
            1,
        )
        right_vars = reduce(
            mul,
            [
                sympy.var(k)
                for k in self.right_sided_parameters
                if k not in self.parent_fusion_parameters
            ],
            1,
        )
        p, q = sympy.Number(1), sympy.Number(1)
        for parent_fuse_parameter, fuse_type in zip(
            self.parent_fusion_parameters, self.fusion_types
        ):
            if fuse_type in ("left", "both"):
                p *= sympy.var(parent_fuse_parameter)
            if fuse_type in ("right", "both"):
                q *= sympy.var(parent_fuse_parameter)
        if left_vars == 1 and right_vars == 1 and p == q:
            raise NotImplementedError(
                "Not handled case with no left and right vars, and new fuse "
                "parameter, or only parent fusion parameter covered entire region"
            )
        subs1 = {**subs}
        subs1[self.fuse_parameter] = q / left_vars
        subs2 = {**subs}
        subs2[self.fuse_parameter] = p / right_vars

        left_right_empty = (
            rhs_func.subs(subs2, simultaneous=True),
            rhs_func.subs(subs1, simultaneous=True),
        )
        to_subtract = 0
        if self.min_points[0] == 1:
            # left side is positive, so the right can't be empty
            to_subtract += left_right_empty[1]
        if self.min_points[1] == 1:
            # right side is positive, so thr left can't be empty
            to_subtract += left_right_empty[0]

        return sympy.Eq(
            lhs_func,
            (
                (q * right_vars * rhs_func.subs(subs1, simultaneous=True))
                - (p * left_vars * rhs_func.subs(subs2, simultaneous=True))
            )
            / (q * right_vars - p * left_vars)
            - to_subtract,
        )
Exemple #44
0
def make_pixel_area_on_unit_spehre(delta_lat, delta_lon, sym=False):
    # we compute the are of a delta_phi * delta_theta patch
    # on the unit ball centered around phi,theta
    # (which depends on theta but not
    # on phi)
    # the infinitesimal area element dA = sin(theta)*d_phi * d_theta
    # we have to integrate it from phi_min to phi_max
    # and from theta_min to theta_max
    if sym:
        # we can do this with sympy (for testing)
        for v in ('theta', 'phi', 'theta_min', 'theta_max', 'phi_min',
                  'phi_max'):
            var(v)

        # We can do this symbolicaly with sympy just for testing...
        A_sym = integrate(integrate(sin(theta), (theta, theta_min, theta_max)),
                          (phi, phi_min, phi_max))
        # translate this to a numeric function
        A_num = lambdify((theta_min, theta_max, phi_min, phi_max),
                         A_sym,
                         modules=['numpy'])
    else:
        # or manually solve the integral since it is very simple
        def A_num(theta_min, theta_max, phi_min, phi_max):
            return ((phi_max - phi_min) *
                    (-np.cos(theta_max) + np.cos(theta_min)))

    delta_theta, delta_phi = map(grad2rad, (delta_lat, delta_lon))
    dth = delta_theta / 2.0
    dph = delta_phi / 2.0

    def A_patch(theta):
        # computes the area of a pixel on the unitsphere
        if np.abs(theta < dth / 100):  #(==0)
            # pixel centered at north pole only extends northwards
            #print("##################### north pole ##########")
            theta_min_v = 0.0
            theta_max_v = dth
        elif np.abs(theta > np.pi - dth / 100):  #==pi)
            # pixel centered at south pole only extends northwards
            #print("##################### south pole ##########")
            theta_min_v = np.pi - dth
            theta_max_v = np.pi
        else:
            # normal pixel extends south and north-wards
            theta_min_v = theta - dth
            theta_max_v = theta + dth

        phi_min_v = -dph
        phi_max_v = +dph
        res = A_num(theta_min_v, theta_max_v, phi_min_v, phi_max_v)
        #print(res)
        return res

    def pixel_area_on_unit_sphere(lat):
        # computes the fraction of the area of the sphere covered by this pixel
        theta_grad = lat + 90
        theta = grad2rad(theta_grad)
        # the area of the unitsphere is 4 * pi
        return A_patch(theta)

    return pixel_area_on_unit_sphere
Exemple #45
0
def speedTest4(mutate=2):
    """Test wrt sympy.

    Results - sympy is 10 to 24 times faster without using arrays (ouch!).
            - diffpy.srfit.equation is slightly slower when using arrays, but
              not considerably worse than versus numpy alone.

    """

    from diffpy.srfit.equation.builder import EquationFactory
    factory = EquationFactory()

    x = numpy.arange(0, 20, 0.05)
    qsig = 0.01
    sigma = 0.003

    eqstr = """\
    b1 + b2*x + b3*x**2 + b4*x**3 + b5*x**4 + b6*x**5 + b7*x**6 + b8*x**7\
    """
    factory.registerConstant("x", x)
    eq = factory.makeEquation(eqstr)

    from sympy import var, exp, lambdify
    from numpy import polyval
    b1, b2, b3, b4, b5, b6, b7, b8, xx = vars = var(
        "b1 b2 b3 b4 b5 b6 b7 b8 xx")
    f = lambdify(vars, polyval([b1, b2, b3, b4, b5, b6, b7, b8], xx), "numpy")

    tnpy = 0
    teq = 0
    import random
    # Randomly change variables
    numargs = len(eq.args)
    choices = range(numargs)
    args = [1.0] * (len(eq.args))
    args.append(x)

    # The call-loop
    random.seed()
    numcalls = 1000
    for _i in xrange(numcalls):
        # Mutate values
        n = mutate
        if n == 0:
            n = random.choice(choices)
        c = choices[:]
        for _j in xrange(n):
            idx = random.choice(c)
            c.remove(idx)
            args[idx] = random.random()

        # Time the different functions with these arguments
        teq += timeFunction(eq, *(args[:-1]))
        tnpy += timeFunction(f, *args)

    print "Average call time (%i calls, %i mutations/call):" % (numcalls,
                                                                mutate)
    print "sympy: ", tnpy / numcalls
    print "equation: ", teq / numcalls
    print "ratio: ", teq / tnpy

    return
Exemple #46
0
h = 0.4
t = np.arange(a, b + h, h)
y = fun_y(t)

# Plot(y, t)
plt.plot(t, y, color="b")
plt.xlim(a, b)
plt.show()

# %%
#
# Ex 2 : f'(x) = x + (f(x) / 5) with f(0) = -3
#
show_example_number(2)

x = sym.var("x")
f = sym.Function("f")

# Equation, then solving
eq2 = sym.Eq(sym.Derivative(f(x), x), x + f(x) / 5)
ics = {f(0): -3}
sol2 = sym.dsolve(eq2, f(x), ics=ics).rhs
print("Solution :", sym.pretty(sym.simplify(sol2)), sep="\n")

# %%
#
# Ex 3 : f'(x) - f(x) = 0 with f(0) = A
#
show_example_number(3)

# Variables and initial condition
Exemple #47
0
import sympy as sm
from sympy import var, pprint


# Main
var('x')
f = 1 / 2 * x**2 + x - 1
tan = 3 * (x - 2) + 3
sm.plot(f, tan, (x, -10, 10))
Exemple #48
0
def speedTest3(mutate=2):
    """Test wrt sympy.

    Results - sympy is 10 to 24 times faster without using arrays (ouch!).
            - diffpy.srfit.equation is slightly slower when using arrays, but
              not considerably worse than versus numpy alone.

    """

    from diffpy.srfit.equation.builder import EquationFactory
    factory = EquationFactory()

    x = numpy.arange(0, 20, 0.05)
    qsig = 0.01
    sigma = 0.003

    eqstr = """\
    A0*exp(-(x*qsig)**2)*(exp(-((x-1.0)/sigma1)**2)+exp(-((x-2.0)/sigma2)**2))\
    + polyval(list(b1, b2, b3, b4, b5, b6, b7, b8), x)\
    """
    factory.registerConstant("x", x)
    eq = factory.makeEquation(eqstr)
    eq.qsig.setValue(qsig)
    eq.sigma1.setValue(sigma)
    eq.sigma2.setValue(sigma)
    eq.A0.setValue(1.0)
    eq.b1.setValue(0)
    eq.b2.setValue(1)
    eq.b3.setValue(2.0)
    eq.b4.setValue(2.0)
    eq.b5.setValue(2.0)
    eq.b6.setValue(2.0)
    eq.b7.setValue(2.0)
    eq.b8.setValue(2.0)

    from sympy import var, exp, lambdify
    from numpy import polyval
    A0, qsig, sigma1, sigma2, b1, b2, b3, b4, b5, b6, b7, b8, xx = vars = var(
        "A0 qsig sigma1 sigma2 b1 b2 b3 b4 b5 b6 b7 b8 xx")
    f = lambdify(
        vars,
        A0 * exp(-(xx * qsig)**2) *
        (exp(-((xx - 1.0) / sigma1)**2) + exp(-((xx - 2.0) / sigma2)**2)) +
        polyval([b1, b2, b3, b4, b5, b6, b7, b8], xx), "numpy")

    tnpy = 0
    teq = 0
    import random
    # Randomly change variables
    numargs = len(eq.args)
    choices = range(numargs)
    args = [1.0] * (len(eq.args))
    args.append(x)

    # The call-loop
    random.seed()
    numcalls = 1000
    for _i in xrange(numcalls):
        # Mutate values
        n = mutate
        if n == 0:
            n = random.choice(choices)
        c = choices[:]
        for _j in xrange(n):
            idx = random.choice(c)
            c.remove(idx)
            args[idx] = random.random()

        # Time the different functions with these arguments
        teq += timeFunction(eq, *(args[:-1]))
        tnpy += timeFunction(f, *args)

    print "Average call time (%i calls, %i mutations/call):" % (numcalls,
                                                                mutate)
    print "sympy: ", tnpy / numcalls
    print "equation: ", teq / numcalls
    print "ratio: ", teq / tnpy

    return
Exemple #49
0
 def setUp(self):
     self.differ = sympy_cell.Differentiate()
     self.differ_cell = QuCell("Quantum::PyCell::Custom::Differentiate")
     self.integral = sympy_cell.Integrate()
     self.integral_cell = QuCell("Quantum::PyCell::Custom::Integrate")
     self.x = var('x')
#!/usr/bin/env python
import sympy
import matplotlib.pyplot as pyplot
import time
sympy.var('a b c d w x y z ')


class pl_true:
    def __init__(self, sentence):
        self.model = {x: True, y: False, z: True, a: False, c: False}
        self.expr = sentence
        self.expr = self.make_simple()
        print("Given Sentence:")
        print(self.expr)
        self.expr = sympy.to_cnf(self.expr)
        # print('in CNF:')
        # print(self.expr)
        self.result = self.logic_solver(self.expr)
        print("Result")
        print self.result

    def make_simple(self):
        # to remove the biconditional and implication operator and
        # replace it appopriate sympy operator
        simple = self.expr
        s = 1
        while (simple.count('<==>')) > 0:
            simple = '(' + self.expr.replace('<==>', '>>',
                                             s) + ')&(' + self.expr.replace(
                                                 '<==>', '<<', s) + ')'
            s += 1
Exemple #51
0
 def __init__(self,
              name,
              NL=0,
              NJ=0,
              NF=0,
              is_floating=False,
              structure=TREE,
              is_mobile=False,
              directory=None,
              par_file_path=None):
     # member variables:
     """  name of the robot: string"""
     self.name = name
     """ directory name"""
     self.directory = self.set_directory(directory)
     """ PAR file path"""
     self.par_file_path = self.set_par_file_path(par_file_path)
     """ whether the base frame is floating: bool"""
     self.is_floating = is_floating
     """ whether the robot is a mobile robot"""
     self.is_mobile = is_mobile
     """  number of links: int"""
     self.nl = NL
     """  number of joints: int"""
     self.nj = NJ
     """  number of frames: int"""
     self.nf = NF
     """ type of robot's structure"""
     self.structure = structure
     """  joint type: list of int"""
     self.sigma = [0 for i in xrange(NF + 1)]
     """  index of antecedent joint: list of int"""
     self.ant = range(-1, self.NF - 1)
     """actuated, if 1, then the joint is actuated"""
     self.mu = [1 for i in xrange(NF + 1)]
     """  geometrical parameter: list of var"""
     self.theta = [0] + [var('th%s' % (i + 1)) for i in xrange(NF)]
     """  geometrical parameter: list of var"""
     self.r = [0 for i in xrange(NF + 1)]
     """  geometrical parameter: list of var"""
     self.alpha = [0 for i in xrange(NF + 1)]
     """  geometrical parameter: list of var"""
     self.d = [0 for i in xrange(NF + 1)]
     """  geometrical parameter: list of var"""
     self.gamma = [0 for i in xrange(NF + 1)]
     """  geometrical parameter: list of var"""
     self.b = [0 for i in xrange(NF + 1)]
     """ transformation from reference frame to zero frame"""
     self.Z = eye(4)
     num = range(self.NL)
     numj = range(self.NJ)
     """  base angular velocity: 3x1 matrix"""
     self.w0 = zeros(3, 1)
     """  base angular acceleration: 3x1 matrix"""
     self.wdot0 = zeros(3, 1)
     """  base linear velocity: 3x1 matrix"""
     self.v0 = zeros(3, 1)
     """  base linear acceleration: 3x1 matrix"""
     self.vdot0 = zeros(3, 1)
     """  joint speed: list of var"""
     self.qdot = [var('QP{0}'.format(i)) for i in numj]
     """  joint acceleration: list of var"""
     self.qddot = [var('QDP{0}'.format(i)) for i in numj]
     """  external moment of link: list of 3x1 matrix"""
     self.Nex = [zeros(3, 1) for i in num]
     self.Nex[-1] = Matrix(var('CX{0}, CY{0}, CZ{0}'.format(self.NL - 1)))
     """  external force of link: list of 3x1 matrix"""
     self.Fex = [zeros(3, 1) for i in num]
     self.Fex[-1] = Matrix(var('FX{0}, FY{0}, FZ{0}'.format(self.NL - 1)))
     """  dry friction coefficient: list of ver"""
     self.FS = [var('FS{0}'.format(i)) for i in num]
     """  joint actuator inertia: list of var"""
     self.IA = [var('IA{0}'.format(i)) for i in num]
     """  viscous friction coefficient: list of var"""
     self.FV = [var('FV{0}'.format(i)) for i in num]
     """  first momentum of link: list of 3x1 matrix"""
     self.MS = [Matrix(var('MX{0}, MY{0}, MZ{0}'.format(i))) for i in num]
     """  mass of link: list of var"""
     self.M = [var('M{0}'.format(i)) for i in num]
     """  joint torques: list of var"""
     self.GAM = [var('GAM{0}'.format(i)) for i in numj]
     """  inertia tensor of link: list of 3x3 matrix"""
     J_str = 'XX{0},XY{0},XZ{0},XY{0},YY{0},YZ{0},XZ{0},YZ{0},ZZ{0}'
     self.J = [Matrix(3, 3, var(J_str.format(i))) for i in num]
     """  gravity vector: 3x1 matrix"""
     self.G = Matrix([0, 0, var('GZ')])
     """  eta - rigid or flexible"""
     self.eta = [0 for j in numj]
     """  k - joint stiffness"""
     self.k = [0 for j in numj]
Exemple #52
0
 def _set_base_defaults(self):
     """
     Set default values for base parameters for those exceptional
     from the ones set in the ctor.
     """
     if self.is_floating or self.is_mobile:
         self.G = Matrix([var('GX'), var('GY'), var('GZ')])
         self.v0 = Matrix([var('VXb'), var('VYb'), var('VZb')])
         self.w0 = Matrix([var('WXb'), var('WYb'), var('WZb')])
         self.vdot0 = Matrix([var('VPXb'), var('VPYb'), var('VPZb')])
         self.wdot0 = Matrix([var('WPXb'), var('WPYb'), var('WPZb')])
         # Z matrix
         for i in range(0, 3):
             for j in range(0, 3):
                 self.Z[i, j] = var('Zr{0}{1}'.format(i + 1, j + 1))
         for j in range(0, 3):
             self.Z[j, 3] = var('Zt{0}'.format(j + 1))
Exemple #53
0
from sympy import Symbol, diff, exp, cos, sin, Matrix, var, symbols
import sympy as sym
import numpy as np
from matplotlib import pyplot as plt

n = 3
# y1,y2,y3=symbols('y[0] y[1] y[2]')
t = Symbol('t')
y = sym.Matrix(n, 1, lambda i, j: var('y[%d]' % (i + 1)))


def f(T, y):
    return sym.Matrix([y[1], -y[1] + 4 * y[0] + T * exp(-T), 2 * y[2]])

A='def pfpt(t,y):\n\treturn np.array(%s)'%(str(f(t,y).diff(t)).replace('Matrix(','').replace('))',')'))+'\n'+\
 'def p2fpt2(t,y):\n\treturn np.array(%s)'%(str(f(t,y).diff(t).diff(t)).replace('Matrix(','').replace('))',')'))+'\n'+\
 'def J(t,y):\n\treturn np.array(%s)'%(str(f(t,y).jacobian(y)).replace('Matrix(','').replace('))',')'))+'\n'+\
 'def pJpt(t,y):\n\treturn np.array(%s)'%(str(f(t,y).jacobian(y).diff(t)).replace('Matrix(','').replace('))',')'))

# def Calculate(T,Y):
#     dic={t:T}
#     [dic.update({'y'+str(i+1):Y[i]}) for i in range(n)]
#     return np.array(f(t,y).diff(t).subs(dic).evalf().T)[0],\
#             np.array(f(t,y).diff(t).diff(t).subs(dic).evalf().T)[0],\
#             np.array(f(t,y).jacobian(y).subs(dic).evalf()),\
#             np.array(f(t,y).jacobian(y).diff(t).subs(dic).evalf()),\
#             np.array(f(t,y).subs(dic).evalf().T)[0]
#  pfpt,p2fpt2,J,pJpt,F
Exemple #54
0
import os
import glob

import numpy as np
import sympy
from sympy import pi, sin, cos, var, Matrix

var('i1, k1, i2, j2, k2, l2', integer=True)
var('x, t, xa, xb, L, r, r2, sina, cosa')
var('A11, A12, A16, A22, A26, A66, A44, A45, A55')
var('B11, B12, B16, B22, B26, B66')
var('D11, D12, D16, D22, D26, D66')
var('wx, wt, tLA')
sympy.var('c00, c01, c02, c0i, c1i, c2i, c3i, c4i, c5i, c6i')
sympy.var('c0ij, c1ij, c2ij, c3ij, c4ij, c5ij, c6ij')
sympy.var('c7ij, c8ij, c9ij, c10ij, c11ij, c12ij, c13ij')


def List(*e):
    return list(e)


with open(r'.\numerical\fortran_strainFunc.txt') as f:
    lines = [line.strip() for line in f.readlines()]
string = ''.join(lines)
string = string.replace('Pi', 'pi')
string = string.replace('Sin', 'sin')
string = string.replace('Cos', 'cos')
string = string.replace('\\', '')
tmp = eval(string)
matrix = Matrix(np.atleast_2d(tmp))
    sum_declarations.append("{0} = {1}".format(newvar, sum))

sum_declarations = "\n".join("{tab[0]}{newvar}".format(tab=TAB, newvar=newvar)
                             for newvar in sum_declarations) + "\n"

# ------------------------------------- #
# -- CRYPTIFICATION OF THE SUM TESTS -- #
# ------------------------------------- #

for old_sum_test in [
        "(sa + 3) * (sb + 3) * (sc + 3) * (sd + 3) * (se + 3) * (sf + 3) * (sg + 3) * (sh + 3)",
        "(sa - 3) * (sb - 3) * (sc - 3) * (sd - 3) * (se - 3) * (sf - 3) * (sg - 3) * (sh - 3)"
]:
    for newvar in newvarssum:
        sympy.var(newvar)

    test = eval(old_sum_test)

    PYCODE = PYCODE.replace(old_sum_test, str(test.expand()))

# ---------------------------------------- #
# -- CRYPTIFICATION OF THE PRODUCT TEST -- #
# ---------------------------------------- #

old_test = "a * b * c * d * e * f * g * h * i != 0"

new_test = "2"

for oneletter in "abcdefghi":
    new_test = "({0})**{1}".format(new_test, oneletter)
Exemple #56
0
def robot_params(name):
    pvals = {}  # null for most robots
    List = ['Puma', 'Chair_Helper', 'Wrist', 'MiniDD', 'Olson13','Stanford',\
            'Sims11', 'Srisuan11', 'Axtman13', 'Mackler13', 'Minder13', 'Palm13', 'Parkman13', \
            'Frei13', 'Wachtveitl', 'Bartell', 'DZhang', 'Khat6DOF', 'Chair6DOF']
    assert (name
            in List), 'robot_params(): Unknown robot, ' + name + ', Stopping'

    if (name == 'Puma'):
        dh = sp.Matrix([[0, 0, 0, th_1], [-sp.pi / 2, 0, 0, th_2],
                        [0, a_2, d_3, th_3], [-sp.pi / 2, a_3, d_4, th_4],
                        [sp.pi / 2, 0, 0, th_5], [-sp.pi / 2, 0, 0, th_6]])
        vv = [1, 1, 1, 1, 1, 1]

        variables = [
            unknown(th_1),
            unknown(th_2),
            unknown(th_3),
            unknown(th_4),
            unknown(th_5),
            unknown(th_6)
        ]
        params = [a_2, a_3, d_3, d_4]
        pvals = {a_2: 0.4138, a_3: 0.0203, d_3: 0.15000, d_4: 0.4318}  # meters

    if (name == 'Chair_Helper'):
        vv = [0, 1, 1, 1, 1, 1]  # must be length 5 since 5dof and 5 unks

        dh = sp.Matrix([
            [0, 0, d_1, 0],
            [0, l_1, 0, th_2],
            [sp.pi / 2, 0, l_2, th_3],
            [sp.pi / 2, 0, 0, th_4],  # must fill remaining rows with zeros
            [-sp.pi / 2, 0, l_4, th_5],
            [0, 0, 0, 0]
        ])

        variables = [
            unknown(d_1),
            unknown(th_2),
            unknown(th_3),
            unknown(th_4),
            unknown(th_5)
        ]

        params = [l_1, l_2, l_4]
    if (name == 'Chair6DOF'):
        vv = [0, 1, 1, 1, 1, 1]  # must be length 5 since 5dof and 5 unks

        dh = sp.Matrix([
            [0, 0, d_1, 0],
            [0, l_1, 0, th_2],
            [sp.pi / 2, 0, l_2, th_3],
            [sp.pi / 2, 0, 0, th_4],  # must fill remaining rows with zeros
            [-sp.pi / 2, 0, l_4, th_5],
            [0, 0, l_5, th_6]
        ])
        sp.var('l_5')

        variables = [
            unknown(d_1),
            unknown(th_2),
            unknown(th_3),
            unknown(th_4),
            unknown(th_5),
            unknown(th_6)
        ]

        params = [l_1, l_2, l_4, l_5]

    if (name == 'Wrist'):
        sp.var('A B C')

        ###   These somewhat wierd DH params give you the ZYX Euler Angles
        #       matrix of example 4.7  (don't ask how I got this!)
        dh = sp.Matrix([
            [0, 0, 0, A],
            [-sp.pi / 2, 0, 0, (sp.pi / 2 + B)],
            [sp.pi / 2, 0, 0,
             (sp.pi / 2 + C)],  # must fill remaining rows with zeros
            [-sp.pi / 2, 0, 0, -sp.pi / 2],
            [0, 0, 0, 0],
            [0, 0, 0, 0]
        ])

        vv = [1, 1, 1, 1, 1, 1]
        variables = [unknown(A), unknown(B), unknown(C)]
        params = []

    if (name == 'MiniDD'):
        #
        #    UW BRL Mini Direct Drive Robot, 5-DOF
        #
        dh = sp.Matrix([[0, 0, d_1, 0], [-sp.pi / 2, 0, 0, th_2],
                        [-sp.pi / 2, l_3, 0, th_3], [-sp.pi / 2, 0, l_4, th_4],
                        [-sp.pi / 2, 0, 0, th_5], [0, 0, 0, 0]])
        vv = [0, 1, 1, 1, 1]

        variables = [
            unknown(d_1),
            unknown(th_2),
            unknown(th_3),
            unknown(th_4),
            unknown(th_5)
        ]

        params = [l_3, l_4]

    if (name == 'Olson13'):
        # standardize on the order "alpha N-1, a N-1, d N, theta N' for the DH table columns.

        # Olson 2013
        # DOF: 6
        # methods to test: m5, m3,
        # Yb = d_1, Xb = d_2, L1 = l3, L2 = l4, L3 = l5
        dh = sp.Matrix([[-sp.pi / 2, 0., d_1, sp.pi / 2],
                        [sp.pi / 2, 0., d_2, -sp.pi / 2],
                        [sp.pi / 2, 0., l_3, th_3], [sp.pi / 2, 0., 0., th_4],
                        [0., l_4, 0., th_5], [sp.pi / 2, 0., l_5, th_6]])

        vv = [0, 0, 1, 1, 1, 1]
        variables = [
            unknown(d_1),
            unknown(d_2),
            unknown(th_3),
            unknown(th_4),
            unknown(th_5),
            unknown(th_6)
        ]
        params = [l_3, l_4, l_5]

    if (name == 'Stanford'):
        sp.var('l_4 l_6')
        dh = sp.Matrix([[-sp.pi / 2, 0., l_1, th_1],
                        [sp.pi / 2, 0., l_2, th_2], [0, 0., d_3, -sp.pi / 2],
                        [-sp.pi / 2, 0., l_4, th_4], [sp.pi / 2, 0., 0., th_5],
                        [0., 0., l_6, th_6]])

        vv = [1, 1, 0, 1, 1, 1]
        variables = [
            unknown(th_1),
            unknown(th_2),
            unknown(d_3),
            unknown(th_4),
            unknown(th_5),
            unknown(th_6)
        ]
        params = [l_1, l_2, l_4, l_6]

    if (name == 'Sims11'):
        # Sims 2011,
        # DOF: 5
        # methods to test: m5, m3, m4, m6
        print "looking at Sims11"
        sp.var('l_1 l_2 l_3')
        dh = sp.Matrix([[0., 0., d_1, 0.], [sp.pi / 2, 0., d_2, 0.],
                        [sp.pi / 2, l_1, 0., th_3], [sp.pi / 2, 0., l_2, th_4],
                        [sp.pi / 2, l_3, 0., th_5], [0., 0., 0., 0.]])

        vv = [0, 0, 1, 1, 1, 1, 1]
        variables = [
            unknown(d_1),
            unknown(d_2),
            unknown(th_3),
            unknown(th_4),
            unknown(th_5)
        ]
        params = [l_1, l_2, l_3]

    if (name == 'Srisuan11'):
        # Srisuan 2011,
        # DOF: 6
        dh = sp.Matrix([[0., 0., d_1, 0.], [0., 0., 0., th_2],
                        [sp.pi / 2, 0., l_1, th_3],
                        [sp.pi / 2, 0., d_4, sp.pi / 2], [0., 0., 0., th_5],
                        [sp.pi / 2, 0., 0., th_6]])

        vv = [0, 1, 1, 0, 1, 1]
        variables = [
            unknown(d_1),
            unknown(th_2),
            unknown(th_3),
            unknown(d_4),
            unknown(th_5),
            unknown(th_6)
        ]
        params = [l_1]

    if (name == 'Axtman13'):
        # Axtman 2013sp,
        # DOF: 4
        dh = sp.Matrix([
            [0., 0., d_1, 0.],
            [sp.pi / 2, 0., l_2, th_2],
            [sp.pi / 2, 0., 0., th_3],
            [0., l_3, 0., th_4],
            [0., l_4, 0., 0.],
            [0., 0., 0., 0.],
        ])
        sp.var('l_3 l_4')
        vv = [0, 1, 1, 1, 0, 0]
        variables = [unknown(d_1), unknown(th_2), unknown(th_3), unknown(th_4)]
        params = [l_2, l_3, l_4]

    if (name == 'Mackler13'):
        # Mackler 2013sp
        # DOF: 5
        dh = sp.Matrix([[-sp.pi / 2, h, d_1, 0.], [sp.pi / 2, 0., l_1, th_2],
                        [sp.pi / 2, l_2, 0., th_3], [sp.pi / 2, 0., l_3, th_4],
                        [-sp.pi / 2, 0., 0., th_5], [0, 0, 0, 0]])
        sp.var('l_3')
        vv = [0, 1, 1, 1, 1, 0]
        variables = [
            unknown(d_1),
            unknown(th_2),
            unknown(th_3),
            unknown(th_4),
            unknown(th_5)
        ]
        params = [l_1, l_2, l_3]
    if (name == 'Minder13'):
        # Minder 2013sp
        # DOF: 4

        dh = sp.Matrix([[0., 0., d_1, 0.], [sp.pi / 2, 0., l_2, th_2],
                        [sp.pi / 2, 0., 0., th_3], [sp.pi / 2, 0., -l_3, th_4],
                        [0., 0., 0., 0.], [0., 0., 0., 0.]])
        sp.var('l_3')
        vv = [0, 1, 1, 1, 0, 0]
        variables = [unknown(d_1), unknown(th_2), unknown(th_3), unknown(th_4)]
        params = [l_2, l_3]

    if (name == 'Palm13'):
        # Palm 2013sp
        # DOF: 4
        dh = sp.Matrix([[sp.pi / 2, 0., l_1, th_1],
                        [sp.pi / 2, 0., d_2, -sp.pi / 2], [0., 0., 0., th_3],
                        [-sp.pi / 2, l_3, h, th_4], [0., 0, 0, 0.],
                        [0., 0., 0., 0.]])
        sp.var('l_1 l_3 h')
        vv = [1, 0, 1, 1, 0, 0]
        variables = [unknown(th_1), unknown(d_2), unknown(th_3), unknown(th_4)]
        params = [l_1, l_3, h]
    if (name == 'Parkman13'):
        # Parkman 2013sp
        # DOF: 5
        dh = sp.Matrix([[0., 0., h, th_1], [sp.pi / 2, 0., 0., th_2],
                        [0., l_2, 0., th_3], [sp.pi, l_3, d_4, 0.],
                        [sp.pi / 2, 0., l_5, th_5], [0., 0., 0., 0.]])
        sp.var('h l_2 l_3 l_5')

        vv = [1, 1, 1, 0, 1, 0]
        variables = [
            unknown(th_1),
            unknown(th_2),
            unknown(th_3),
            unknown(d_4),
            unknown(th_5)
        ]
        params = [h, l_2, l_3, l_5]

    if (name == 'Frei13'):
        # Frei 13sp
        # DOF 5
        dh = sp.Matrix([[0., 0., d_1, 0.], [sp.pi / 2, 0., 0., th_2],
                        [sp.pi / 2, 0., l_3, th_3], [sp.pi / 2, 0., 0., th_4],
                        [sp.pi / 2, 0., l_5, th_5], [0., 0., 0., 0.]])
        sp.var('l_3 l_5')
        vv = [0, 1, 1, 1, 1, 0]
        variables = [
            unknown(d_1),
            unknown(th_2),
            unknown(th_3),
            unknown(th_4),
            unknown(th_5)
        ]
        params = [l_3, l_5]

    if (name == 'Wachtveitl'):
        # Wachtveitl 2013sp
        # DOF: 5

        dh = sp.Matrix([[-sp.pi / 2, 0., d_1, 0.], [sp.pi / 2, 0., h, th_2],
                        [sp.pi / 2, 0., 0., th_3], [0., l_2, l_3, th_4],
                        [sp.pi / 2, 0., l_4, th_5], [0., 0., 0, 0.]])
        sp.var('h l_3 l_4')
        vv = [0, 1, 1, 1, 1, 0]
        variables = [
            unknown(d_1),
            unknown(th_2),
            unknown(th_3),
            unknown(th_4),
            unknown(th_5)
        ]
        params = [h, l_2, l_3, l_4]

    if (name == 'Bartell'):
        # Bartell 2013
        # DOF: 5
        dh = sp.Matrix([[0., 0., l_1, th_1], [sp.pi / 2, 0., d_2, 0.],
                        [0., 0., 0., th_3], [sp.pi / 2, 0., d_4, 0.],
                        [0., 0., 0., th_5], [sp.pi / 2, 0., 0., 0.]])

        vv = [1, 0, 1, 0, 1, 1]
        variables = [
            unknown(th_1),
            unknown(d_2),
            unknown(th_3),
            unknown(d_4),
            unknown(th_5)
        ]

        params = [l_1]

    if (name == 'DZhang'):
        # Dianmu Zhang
        # DOF 5
        dh = sp.Matrix([[0., 0., h, th_1], [sp.pi / 2, l_1, 0, th_2],
                        [0, l_3, 0, th_3], [sp.pi / 2, 0., l_4, th_4],
                        [sp.pi / 2, 0., 0, th_5], [0, 0., 0., 0]])

        sp.var('h l_3 l_4')
        vv = [1, 1, 1, 1, 1, 1]
        variables = [
            unknown(th_1),
            unknown(th_2),
            unknown(th_3),
            unknown(th_4),
            unknown(th_5)
        ]
        params = [h, l_1, l_3, l_4]

    if (name == 'Khat6DOF'):
        #
        #   This is Kuka Model KR60
        #    ( as analyzed in Khatamian6DOF_IK2015.pdf)
        # unsolved, 6DOF

        dh = sp.Matrix([  ##  This one requires sum-of-angles.
            [0, a_1, l_1, th_1], [sp.pi / 2, 0, 0, th_2], [0, a_2, 0, th_3],
            [sp.pi / 2, a_3, l_4, th_4], [-sp.pi / 2, 0, 0, th_5],
            [sp.pi / 2, 0, 0, th_6]
        ])
        vv = [1, 1, 1, 1, 1, 1]

        variables = [
            unknown(th_1),
            unknown(th_2),
            unknown(th_3),
            unknown(th_4),
            unknown(th_5),
            unknown(th_6)
        ]

        params = [a_1, l_1, a_2, a_3, l_4]
    ################## (all robots) ######################
    ##  make sure each unknown knows its position (index)
    i = 0
    for v in variables:
        v.n = i
        i += 1

    return [dh, vv, params, pvals, variables]
Exemple #57
0
#程序文件Pex15_4_2.py
import numpy as np
import sympy as sp

x0 = np.array([41, 49, 61, 78, 96, 104])
n = len(x0)
lamda = x0[:-1] / x0[1:]  #计算级比
rang = [lamda.min(), lamda.max()]  #计算级比的范围
theta = [np.exp(-2 / (n + 1)), np.exp(2 / (n + 1))]  #计算级比容许范围
x1 = np.cumsum(x0)  #累加运算
z = 0.5 * (x1[1:] + x1[:-1])
B = np.vstack([-x0[1:], -z, np.ones(n - 1)]).T
u = np.linalg.pinv(B) @ np.diff(x0)  #最小二乘法拟合参数
print("参数u:", u)
sp.var('t')
sp.var('x', cls=sp.Function)  #定义符号变量和函数
eq = x(t).diff(t, 2) + u[0] * x(t).diff(t) + u[1] * x(t) - u[2]
s = sp.dsolve(eq, ics={x(0): x0[0], x(5): x1[-1]})  #求微分方程符号解
xt = s.args[1]  #提取解的符号表达式
print('xt=', xt)
fxt = sp.lambdify(t, xt, 'numpy')  #转换为匿名函数
yuce1 = fxt(np.arange(n))  #求预测值
yuce = np.hstack([x0[0], np.diff(yuce1)])  #还原数据
epsilon = x0 - yuce[:n]  #计算已知数据预测的残差
delta = abs(epsilon / x0)  #计算相对误差
print('相对误差:', np.round(delta * 100, 2))  #显示相对误差
Exemple #58
0
    'alpha_51':
    'flux coefficient from strucutral soil surface litter pool to active soil organic matter pool',
    'alpha_53':
    'flux coefficient from strucutral soil litter pool to active soil organic matter pool',
    'alpha_61':
    'flux coefficient from strucutral soil surface litter pool to slow soil organic matter pool',
    'alpha_63':
    'flux coefficient from strucutral soil litter pool to slow soil organic matter pool',
    'alpha_65':
    'flux coefficient from strucutral soil surface litter pool to slow soil organic matter pool',
    'f_T': 'function of temperature',
    'f_W': 'function of soil moisture'
}

for name in sym_dict.keys():
    var(name)
k_1 = K_1 * exp(-3 * Ls)
k_3 = K_3 * exp(-3 * Ls)
k_5 = K_5 * (1 - 0.75 * Tx)
E_s = 0.85 - 0.68 * Tx
F_m = 0.85 - 0.018 * LN
F_s = 1 - F_m
alpha_51 = 0.55 * (1 - A_l)
alpha_53 = 0.45 * (1 - A_l)
alpha_61 = 0.7 * A_l
alpha_63 = alpha_61
alpha_65 = 1 - E_s - 0.004
t = TimeSymbol("t")  # unit: "year" #??? monthly
x = StateVariableTuple((C_1, C_2, C_3, C_4, C_5, C_6, C_7))
u = InputTuple((J_1 * F_s, J_1 * F_m, J_2 * F_s, J_2 * F_m, 0, 0, 0))
xi = f_T * f_W  #environmental effects multiplier (DEFAG)
Exemple #59
0
def radialwave(n, l, r):
    Z = 1  #atomic constant
    var("r Z")
    radialwave = eval('R_nl(n,l,r,Z)')
    return radialwave
Exemple #60
0
    def __init__(
        self, name, links=0, joints=0, frames=0,
        is_floating=True, structure=tools.TREE, is_mobile=False,
        is_symbolic=True
    ):
        """
        Constructor period.

        Usage:
        """
        """Name of the robot."""
        self.name = name
        """Folder to store the files related to the robot."""
        self.directory = filemgr.get_folder_path(name)
        """Total number of links in the robot."""
        self.num_links = links
        """Total number of joints in the robot."""
        self.num_joints = joints
        """Total number of frames in the robot."""
        self.num_frames = frames
        """To indicate if the base is floating or not."""
        self.is_floating = is_floating
        """Type of the robot structure - simple, tree, closed-loop"""
        self.structure = structure
        """To indicate if the robot is a wheeled mobile robot"""
        self.is_mobile = is_mobile
        """To indicate if computation should be symbolic or numeric"""
        self.is_symbolic = is_symbolic
        # properties dependent on number of links
        """
        List to hold the dynamic parameters. The indices of the list
        start with 0 and it corresponds to parameters of link 0 (virtual
        link of the base).
        """
        self.dyns = [DynParams(j) for j in self.link_nums]
        # properties dependent on number of joints
        """
        To indicate if a joint is rigid or flexible. 0 for rigid and 1
        for flexible. The indices of the list start with 0 and
        corresponds to a virtual joint of the base. This joint is
        usually rigid.
        """
        self.etas = [0 for j in self.joint_nums]
        """Joint stiffness usually indicated by k."""
        self.stiffness = [0 for j in self.joint_nums]
        """Joint velocities."""
        self.qdots = [var('QP{0}'.format(j)) for j in self.joint_nums]
        """Joint accelerations."""
        self.qddots = [var('QDP{0}'.format(j)) for j in self.joint_nums]
        """Joint torques."""
        self.torques = [var('GAM{0}'.format(j)) for j in self.joint_nums]
        # properties dependent on number of frames
        """
        List to hold the geometric parameters. NOTE: This might be moved
        to a separate function.
        The indices of the list start with 0 and the first object
        corresponds to parameters of frame 0 (base) wrt its antecedent
        (some arbitary reference frame).
        """
        self.geos = [GeoParams(j) for j in self.frame_nums]
        # properties independent of number of links, joints and frames
        """Gravity vector a 3x1 Matrix."""
        self.gravity = Matrix([0, 0, var('G3')])
        # the values of properties below would be modified during
        # the computation of dynamic models.
        """Base velocity 6x1 column vector - a Screw."""
        self.base_vel = Screw()
        """Base acceleration 6x1 column vector - a Screw."""
        self.base_accel = Screw()
        """Transformation matrix of base wrt a reference frame at time 0."""
        self.base_tmat = eye(4)
        # call init methods
        self._init_maps()