Esempio n. 1
0
def test_nsolve():
    # onedimensional
    from sympy import Symbol, sin, pi
    x = Symbol('x')
    assert nsolve(sin(x), 2) - pi.evalf() < 1e-16
    assert nsolve(Eq(2*x, 2), x, -10) == nsolve(2*x - 2, -10)
    # multidimensional
    x1 = Symbol('x1')
    x2 = Symbol('x2')
    f1 = 3 * x1**2 - 2 * x2**2 - 1
    f2 = x1**2 - 2 * x1 + x2**2 + 2 * x2 - 8
    f = Matrix((f1, f2)).T
    F = lambdify((x1, x2), f.T, modules='mpmath')
    for x0 in [(-1, 1), (1, -2), (4, 4), (-4, -4)]:
        x = nsolve(f, (x1, x2), x0, tol=1.e-8)
        assert mnorm(F(*x),1) <= 1.e-10
    # The Chinese mathematician Zhu Shijie was the very first to solve this
    # nonlinear system 700 years ago (z was added to make it 3-dimensional)
    x = Symbol('x')
    y = Symbol('y')
    z = Symbol('z')
    f1 = -x + 2*y
    f2 = (x**2 + x*(y**2 - 2) - 4*y)  /  (x + 4)
    f3 = sqrt(x**2 + y**2)*z
    f = Matrix((f1, f2, f3)).T
    F = lambdify((x,  y,  z), f.T, modules='mpmath')
    def getroot(x0):
        root = nsolve((f1,  f2,  f3), (x,  y,  z), x0)
        assert mnorm(F(*root),1) <= 1.e-8
        return root
    assert map(round,  getroot((1,  1,  1))) == [2.0,  1.0,  0.0]
Esempio n. 2
0
def velocity_field(psi): #takes a symbolic function and returns two lambda functions
#to evaluate the derivatives in both x and y.
   global w
   if velocity_components:
      u = lambdify((x,y), eval(x_velocity), modules='numpy')
      v = lambdify((x,y), eval(y_velocity), modules='numpy')
   else:
      if is_complex_potential:
         print "Complex potential, w(z) given"
         #define u, v symbolically as the imaginary part of the derivatives
         u = lambdify((x, y), sympy.im(psi.diff(y)), modules='numpy')
         v = lambdify((x, y), -sympy.im(psi.diff(x)), modules='numpy')
      else:
         #define u,v as the derivatives 
         print "Stream function, psi given"
         u = sympy.lambdify((x, y), psi.diff(y), 'numpy')
         v = sympy.lambdify((x, y), -psi.diff(x), 'numpy')
   if (branch_cuts): # If it's indicated that there are branch cuts in the mapping,
                      # then we need to return vectorized numpy functions to evaluate
                      # everything numerically, instead of symbolically 
                      # This of course results in a SIGNIFICANT time increase
                      #   (I don't know how to handle more than the primitive root
                      #   (symbolically in Sympy
      return np.vectorize(u),np.vectorize(v)
   else:
       # If there are no branch cuts, then return the symbolic lambda functions (MUCH faster)
      return u,v
Esempio n. 3
0
def test_msolve():
    x1 = Symbol('x1')
    x2 = Symbol('x2')
    f1 = 3 * x1**2 - 2 * x2**2 - 1
    f2 = x1**2 - 2 * x1 + x2**2 + 2 * x2 - 8
    f = Matrix((f1, f2)).T
    F = lambdify((x1, x2), f.T)
    # numeric.newton is tested in this example too
    for x0 in [(-1., 1.), (1., -2.), (4., 4.), (-4., -4.)]:
        x = msolve((x1, x2), f, x0, tol=1.e-8)
        assert maxnorm(F(*x)) <= 1.e-11
    # The Chinese mathematician Zhu Shijie was the very first to solve this
    # nonlinear system 700 years ago (z was added to make it 3-dimensional)
    x = Symbol('x')
    y = Symbol('y')
    z = Symbol('z')
    f1 = -x + 2*y
    f2 = (x**2 + x*(y**2 - 2) - 4*y)  /  (x + 4)
    f3 = sqrt(x**2 + y**2)*z
    f = Matrix((f1, f2, f3)).T
    F = lambdify((x,  y,  z), f.T)
    def getroot(x0):
        root = msolve((x,  y,  z),  (f1,  f2,  f3),  x0)
        assert maxnorm(F(*root)) <= 1.e-8
        return root
    assert map(round,  getroot((1.,  1.,  1.))) == [2.0,  1.0,  0.0]
Esempio n. 4
0
    def compile_function(self, module="numpy"):
        import sympy
        from sympy.utilities.lambdify import lambdify

        expr = sympy.sympify(self._str_expression)

        rvars = sympy.symbols([s.name for s in expr.free_symbols], real=True)
        real_expr = expr.subs({orig: real_ for (orig, real_) in zip(expr.free_symbols, rvars)})
        # just replace with the assumption that all our variables are real
        expr = real_expr

        eval_expr = expr.evalf()
        # Extract parameters
        parameters = [symbol for symbol in expr.free_symbols if symbol.name != "x"]
        parameters.sort(key=lambda x: x.name)  # to have a reliable order
        # Extract x
        x, = [symbol for symbol in expr.free_symbols if symbol.name == "x"]
        # Create compiled function
        self._f = lambdify([x] + parameters, eval_expr, modules=module, dummify=False)
        parnames = [symbol.name for symbol in parameters]
        self._parameter_strings = parnames
        for parameter in parameters:
            grad_expr = sympy.diff(eval_expr, parameter)
            setattr(
                self,
                "_f_grad_%s" % parameter.name,
                lambdify([x] + parameters, grad_expr.evalf(), modules=module, dummify=False),
            )

            setattr(
                self,
                "grad_%s" % parameter.name,
                _fill_function_args(getattr(self, "_f_grad_%s" % parameter.name)).__get__(self, Expression),
            )
Esempio n. 5
0
 def twin_function_expr(self, value):
     if not value:
         self.twin_function = None
         self.twin_inverse_function = None
         self._twin_function_expr = ""
         self._twin_inverse_sympy = None
         return
     expr = sympy.sympify(value)
     if len(expr.free_symbols) > 1:
         raise ValueError("The expression must contain only one variable.")
     elif len(expr.free_symbols) == 0:
         raise ValueError("The expression must contain one variable, "
                          "it contains none.")
     x = tuple(expr.free_symbols)[0]
     self.twin_function = lambdify(x, expr.evalf())
     self._twin_function_expr = value
     if not self.twin_inverse_function:
         y = sympy.Symbol(x.name + "2")
         try:
             inv = sympy.solveset(sympy.Eq(y, expr), x)
             self._twin_inverse_sympy = lambdify(y, inv)
             self._twin_inverse_function = None
         except BaseException:
             # Not all may have a suitable solution.
             self._twin_inverse_function = None
             self._twin_inverse_sympy = None
             _logger.warning(
                 "The function {} is not invertible. Setting the value of "
                 "{} will raise an AttributeError unless you set manually "
                 "``twin_inverse_function_expr``. Otherwise, set the "
                 "value of its twin parameter instead.".format(value, self))
Esempio n. 6
0
def find_CI(quartile, variable, critical, search = "left", grid_left = None, grid_right = None, precision = 0.001):
    '''
    We take {regions} points in our domain and test every point for its likelihood value,
    then we look at points where values of ll ratio criteria cross critical value of chi^2 distribution
    It means, we should choose {regions} in such way that at least one point lays in the confidence interval
    at the first step.
    '''
    regions = 20
    solution = solutions[quartile]
    ll_hat = -0.5 * commons.chi2(solution)
    critical_val = chi2.ppf(critical, df=1)
    other1 = variable_to_others[variable][0]
    other2 = variable_to_others[variable][1]
    variable_bounds = (grid_left if not grid_left is None else commons.bounds[quartile][variable_index[variable]][0],
                       grid_right if not grid_right is None else commons.bounds[quartile][variable_index[variable]][1])
    grid = np.linspace(start = variable_bounds[0], stop = variable_bounds[1], num = regions)
    other_bounds = (commons.bounds[quartile][variable_index[other1]], commons.bounds[quartile][variable_index[other2]])
    ll_prev_criteria = None
    #print("Critical value is {}".format(critical_val))
    for i, v in enumerate(grid):
        #print("Check {} = {}".format(variable, v))
        ys = sp.Matrix([variable_ref[other1], variable_ref[other2]])
        pll_func_sym = commons.chi2_sym.subs(variable_ref[variable], v)
        pll_func = lambda args: lambdify(ys, pll_func_sym, 'numpy')(*args)[0, 0]
        pll_func_jacob = lambda args: lambdify(ys, pll_func_sym.jacobian(ys), 'numpy')(*args)
        result = opt.minimize(pll_func, [solution[variable_index[other1]], solution[variable_index[other2]]],
                          method='TNC',
                          jac=pll_func_jacob,
                          bounds=other_bounds)
        pll_val = -.5 * result.fun
        ll_criteria = 2 * (ll_hat - pll_val)
        #print("\tProfile LL ratio value = {}".format(ll_criteria))
        if not ll_prev_criteria is None:
            l = grid[i - 1]
            r = grid[i]
            if ll_prev_criteria > critical_val and ll_criteria < critical_val and search == "left":
                #print("Critical point lays between {} and {}\n".format(l, r))
                if (r - l) < precision:
                    return l, r
                else:
                    return find_CI(quartile, variable, critical,
                                   search = search,
                                   grid_left = l,
                                   grid_right = r,
                                   precision = precision)
            elif ll_prev_criteria < critical and ll_criteria > critical and search == "right":
                #print("Critical point lays between {} and {}\n".format(l, r))
                if (r - l) < precision:
                    return l, r
                else:
                    return find_CI(quartile, variable, critical,
                                   search = search,
                                   grid_left = l,
                                   grid_right = r,
                                   precision = precision)
        ll_prev_criteria = ll_criteria
Esempio n. 7
0
def msolve(args, f, x0, tol=None, maxsteps=None, verbose=False, norm=None,
           modules=['mpmath', 'sympy']):
    """
    Solves a nonlinear equation system numerically.

    f is a vector function of symbolic expressions representing the system.
    args are the variables.
    x0 is a starting vector close to a solution.

    Be careful with x0, not using floats might give unexpected results.

    Use modules to specify which modules should be used to evaluate the
    function and the Jacobian matrix. Make sure to use a module that supports
    matrices. For more information on the syntax, please see the docstring
    of lambdify.

    Currently only fully determined systems are supported.

    >>> from sympy import Symbol, Matrix
    >>> x1 = Symbol('x1')
    >>> x2 = Symbol('x2')
    >>> f1 = 3 * x1**2 - 2 * x2**2 - 1
    >>> f2 = x1**2 - 2 * x1 + x2**2 + 2 * x2 - 8
    >>> msolve((x1, x2), (f1, f2), (-1., 1.))
    [-1.19287309935246]
    [ 1.27844411169911]
    """
    if isinstance(f,  (list,  tuple)):
        f = Matrix(f).T
    if len(args) != f.cols:
        raise NotImplementedError('need exactly as many variables as equations')
    if verbose:
        print 'f(x):'
        print f
    # derive Jacobian
    J = f.jacobian(args)
    if verbose:
        print 'J(x):'
        print J
    # create functions
    f = lambdify(args, f.T, modules)
    J = lambdify(args, J, modules)
    # solve system using Newton's method
    kwargs = {}
    if tol:
        kwargs['tol'] = tol
    if maxsteps:
        kwargs['maxsteps'] = maxsteps
    kwargs['verbose'] = verbose
    if norm:
        kwargs['norm'] = norm
    x = newton(f, x0, J, **kwargs)
    return x
Esempio n. 8
0
    def __init__(self, state_vector, next_state_func, observation_vector, observation_func,
                 x0, initial_cov, process_noise_cov, measurement_noise_cov):
        """Create the filter

        :param state_vector: sympy matrix `x`, the full state of the filter
        :param next_state_func: sympy matrix, `x_next` as a function of `x`
            - The dynamics jacobian will be generated internally
        """
        dynamics_jacobian = self.form_dynamics_jacobian(state_vector, next_state_func)
        observation_jacobian = self.form_observation_jacobian(state_vector, observation_vector, observation_func)
        self.x_dim = dynamics_jacobian.shape[0]
        self.observation_dim = observation_vector.shape[0]

        #
        # Input validation
        # Before the arguments even get off the ship, we validate them

        # observation jacobian asserts
        assert observation_jacobian.shape[1] == self.x_dim, "Observation jacobian has the wrong dimension to map to state"
        assert observation_jacobian.shape[0] == self.observation_dim, "Observation jacobian is not the right shape"

        # measurement covariance asserts
        assert measurement_noise_cov.shape[0] == measurement_noise_cov.shape[1], \
            "Measurement noise is not the same shape as symbolic measurement"
        assert measurement_noise_cov.shape[0] == observation_vector.shape[0], "Measurement noise is not square"

        # process covariance asserts
        assert process_noise_cov.shape[0] == process_noise_cov.shape[1], "Process noise is not square"
        assert process_noise_cov.shape[0] == state_vector.shape[0], "Process noise is not the same shape as symbolic state"

        # initial state asserts
        assert x0.shape[0] == state_vector.shape[0], "Supplied initial state is not the same shape as symbolic state"

        self.make_A = lambdify(
            state_vector,
            dynamics_jacobian,
            'numpy'
        )

        self.make_H = lambdify(
            state_vector,
            observation_jacobian,
            'numpy'
        )

        #
        # State/Covariance initialization
        #
        self.x = x0
        self.P = initial_cov
        self.Q = process_noise_cov
        self.R = measurement_noise_cov
Esempio n. 9
0
def test_1d():
    B = gen_BrownianMotion()
    Bs = implemented_function("B", B)
    t = sympy.Symbol('t')
    expr = 3*sympy.exp(Bs(t)) + 4
    expected = 3*np.exp(B.y)+4
    ee_vec = lambdify(t, expr, "numpy")
    assert_almost_equal(ee_vec(B.x), expected)
    # with any arbitrary symbol
    b = sympy.Symbol('b')
    expr = 3*sympy.exp(Bs(b)) + 4
    ee_vec = lambdify(b, expr, "numpy")
    assert_almost_equal(ee_vec(B.x), expected)
Esempio n. 10
0
def make_callable(model, variables, mode=None):
    """
    Take a SymPy object and create a callable function.

    Parameters
    ----------
    model, SymPy object
        Abstract representation of function
    variables, list
        Input variables, ordered in the way the return function will expect
    mode, ['numpy', 'numexpr', 'sympy'], optional
        Method to use when 'compiling' the function. SymPy mode is
        slow and should only be used for debugging. If Numexpr is installed,
        it can offer speed-ups when calling the energy function many
        times on multi-core CPUs.

    Returns
    -------
    Function that takes arguments in the same order as 'variables'
    and returns the energy according to 'model'.

    Examples
    --------
    None yet.
    """
    energy = None
    if mode is None:
        # no mode specified; use numexpr if available, otherwise numpy
        # Note: numexpr support appears to break in multi-component situations
        # See numexpr#167 on GitHub for details
        # For now, default to numpy until a solution/workaround is available
        #if _NUMEXPR:
        #    mode = 'numexpr'
        #else:
        #    mode = 'numpy'
        mode = 'numpy'

    if mode == 'sympy':
        energy = lambda *vs: model.subs(zip(variables, vs)).evalf()
    elif mode == 'numpy':
        logical_np = [{'And': np.logical_and, 'Or': np.logical_or}, 'numpy']
        energy = lambdify(tuple(variables), model, dummify=True,
                          modules=logical_np, printer=NumPyPrinter)
    elif mode == 'numexpr':
        energy = lambdify(tuple(variables), model, dummify=True,
                          modules='numexpr', printer=SpecialNumExprPrinter)
    else:
        energy = lambdify(tuple(variables), model, dummify=True,
                          modules=mode)

    return energy
Esempio n. 11
0
def make_callable(model, variables, mode=None):
    """
    Take a SymPy object and create a callable function.

    Parameters
    ----------
    model, SymPy object
        Abstract representation of function
    variables, list
        Input variables, ordered in the way the return function will expect
    mode, ['numpy', 'numba', 'sympy'], optional
        Method to use when 'compiling' the function. SymPy mode is
        slow and should only be used for debugging. If Numba is installed,
        it can offer speed-ups when calling the energy function many
        times on multi-core CPUs.

    Returns
    -------
    Function that takes arguments in the same order as 'variables'
    and returns the energy according to 'model'.

    Examples
    --------
    None yet.
    """
    energy = None
    if mode is None:
        # no mode specified; use numba if available, otherwise numpy
        if _NUMBA:
            mode = 'numba'
        else:
            mode = 'numpy'

    if mode == 'sympy':
        energy = lambda *vs: model.subs(zip(variables, vs)).evalf()
    elif mode == 'numpy':
        energy = lambdify(tuple(variables), model, dummify=True,
                          modules=[{'where': np.where}, 'numpy'], printer=NumPyPrinter)
    elif mode == 'numba':
        variables = tuple(variables)
        varsig = 'float64({})'.format(','.join(['float64'] * len(variables)))
        energy = lambdify(variables, model, dummify=True,
                          modules=[{'where': nbwhere}, 'numpy'], printer=NumPyPrinter)
        # target=parallel seems to incur too much overhead on small arrays
        energy = _NUMBA.vectorize([varsig], nopython=True, target='cpu')(energy)
    else:
        energy = lambdify(tuple(variables), model, dummify=True,
                          modules=mode)

    return energy
Esempio n. 12
0
def test_blocks():
    on_off = [[1,2],[3,4]]
    tval = np.array([0.4,1.4,2.4,3.4])
    b = blocks(on_off)
    lam = lambdify(t, b)
    assert_array_equal(lam(tval), [0, 1, 0, 1])
    b = blocks(on_off, amplitudes=[3,5])
    lam = lambdify(t, b)
    assert_array_equal(lam(tval), [0, 3, 0, 5])
    # Check what happens with names
    # Default is from step function
    assert_false(re.match(r'step\d+\(t\)$', str(b)) is None)
    # Can pass in another
    b = blocks(on_off, name='funky_chicken')
    assert_equal(str(b), 'funky_chicken(t)')
Esempio n. 13
0
 def num_eval(self, symbol=None, values=None, uncertainties=None):
     if symbol == None:
         return self.value(), self.uncertainty()
     
     valfunc = lambdify(symbol, self.value(), 'numpy')
     if uncertainties == None:        
         uncertaintyfunc = lambdify(symbol, self.uncertainty(), 'numpy')
         return valfunc(values), uncertaintyfunc(values)
     else:
         u_sym = sympy.symbols('u_sym')
         usquared = self.uncertainty_squared() + \
                 (self.formula.diff(symbol).subs(self.values) * u_sym)**2
         u = sympy.sqrt(usquared)
         uncertaintyfunc = lambdify((symbol, u_sym), u, 'numpy')
         return valfunc(values), uncertaintyfunc(values, uncertainties)
Esempio n. 14
0
def test_step_function():
    # test step function
    # step function is a function of t
    s = step_function([0,4,5],[2,4,6])
    tval = np.array([-0.1,0,3.9,4,4.1,5.1])
    lam = lambdify(t, s)
    assert_array_equal(lam(tval), [0, 2, 2, 4, 4, 6])
    s = step_function([0,4,5],[4,2,1])
    lam = lambdify(t, s)
    assert_array_equal(lam(tval), [0, 4, 4, 2, 2, 1])
    # Name default
    assert_false(re.match(r'step\d+\(t\)$', str(s)) is None)
    # Name reloaded
    s = step_function([0,4,5],[4,2,1], name='goodie_goodie_yum_yum')
    assert_equal(str(s), 'goodie_goodie_yum_yum(t)')
Esempio n. 15
0
def test_implemented_function():
    # Here we check if the default returned functions are anonymous - in
    # the sense that we can have more than one function with the same name
    f = implemented_function('f', lambda x: 2*x)
    g = implemented_function('f', lambda x: np.sqrt(x))
    l1 = lambdify(x, f(x))
    l2 = lambdify(x, g(x))
    assert_equal(str(f(x)), str(g(x)))
    assert_equal(l1(3), 6)
    assert_equal(l2(3), np.sqrt(3))
    # check that we can pass in a sympy function as input
    func = sympy.Function('myfunc')
    assert_false(hasattr(func, '_imp_'))
    f = implemented_function(func, lambda x: 2*x)
    assert_true(hasattr(func, '_imp_'))
Esempio n. 16
0
def get_error(expr):
    """ calculates error of an expression possibly containing quantities

    Returns: tuple of error and error formula (as Expr object)
    """
    integrand = 0
    error_formula = 0
    for varToDiff in expr.free_symbols:
        if varToDiff.error is not None:
            differential = diff(expr,varToDiff)
            error_formula += ( Symbol(varToDiff.name+"_err",positive=True) * differential )**2
            diffFunction = lambdify(differential.free_symbols,differential, modules="numpy")

            diffValues = []
            for var in differential.free_symbols:
                diffValues.append(var.value)

            integrand += ( varToDiff.error*diffFunction(*diffValues) )**2
    if isinstance(integrand,np.ndarray):
        if (integrand==0).all():
            return (None,None)
    elif integrand == 0:
        return (None,None)

    return (np.sqrt(integrand),sym_sqrt (error_formula))
def getRelError(variables,func,showFunc = False):
	"""getError generates a function to calculate the error of a function. I.E. a function that
	gives you the error in its result given the error in its input. Output function is numpy ready. 
	Output function will take twice as many args as variables, one for the var and one for the error in that var.

	arguments
	variables      : a list of sympy symbols in func
	errorVariables : list of sympy ymbols representing the error in each value of variables. must be the same length as variables
	func           : a function containing your variables that you want the error of"""
	ErrorFunc = 0 # need to set function to start value
	erVars    = {}
	for i in range(len(variables)): #run through all variables in the function
		v                  = variables[i]
		dv                 =  Symbol('d'+str(v), positive = True)
		erVars['d'+str(v)] = dv
		D                  = (diff(func,v)*dv)**2
		ErrorFunc          += D

	ErrorFunc = sqrt(ErrorFunc)/func
	if showFunc:
		pprint(ErrorFunc)
		
	variables.extend(erVars.values()) #create a list of all sympy symbols involved
	func      = lambdify(tuple(variables), ErrorFunc ,"numpy") #convert ErrorFunc to a numpy rteady python lambda
	return(func)
Esempio n. 18
0
def fit(x_data, y_data, fit_function, parameters, weighted=None):

	args = [x_data]
	args.extend(parameters)
	np_func = lambdify(tuple(args), fit_function, "numpy")

	start_params = []
	for p in parameters:
		if p.value == None:
			start_params.append(np.float_(1))
		else:
			if isinstance(p.value,np.ndarray):
				raise ValueError("fit parameter '%s' is a data set." % p.name)
			else:
				start_params.append(p.value)

	if weighted is False:
		errors = None
	else:
		errors = y_data.error

	if weighted is True and y_data.error is None:
		raise RuntimeError("can't perform weighted fit because error of '%s' is not set." % y_data.name)
	params_opt, params_covar = curve_fit (np_func,x_data.value,y_data.value,sigma=errors,p0=start_params)
	params_err = np.sqrt(np.diag(params_covar))

	return (params_opt,params_err)
def get_ode_fcn_floating_dp(g_, a1_, L1_, m1_, I1_, a2_, L2_, m2_, I2_):
    """ Returns a function object that can be called with fnc(t,x, u),
    where x = [q1, q2, q3, q4, qd1, qd2, qd3, qd4], and tau = [tau1, tau2, tau3, tau4], is the torques at each 
    joint respectively. The function implements the ode for the floating inverted
    double pendulum.

    For faster return of already constructed models, the set of parameters
    are checked against a pickled dict.
    """
    

    params = (g_, a1_, L1_, m1_, I1_, a2_, L2_, m2_, I2_)

    
    tau1, tau2, tau3, tau4 = sy.symbols('tau1, tau2, tau3, tau4')
    q1, q2, q3, q4, qd1, qd2, qd3, qd4 = symbols('q1, q2, q3, q4, qd1, qd2, qd3, qd4', real=True)

    s1 = sy.sin(q1); s1_ = Symbol('s1')
    c1 = sy.cos(q1); c1_ = Symbol('c1')
    s2 = sy.sin(q2); s2_ = Symbol('s2')
    c2 = sy.cos(q2); c2_ = Symbol('c2')
    s12 = sy.sin(q1+q2); s12_ = Symbol('s12') 
    c12 = sy.cos(q1+q2); c12_ = Symbol('c12') 



    odes = get_symbolic_ode_floating_dp(params)

    # Substitute functions for faster evaluation
    odes = odes.subs(s1, s1_).subs(c1,c1_).subs(s2,s2_).subs(c2,c2_).subs(s12,s12_).subs(c12,c12_)

    lmb = lambdify( (q1, q2, q3, q4, q1dot, q2dot, q3dot, q4dot, s1_, c1_, s2_, c2_, s12_, c12_, tau1, tau2, tau3, tau4), odes)
    return partial(lambda_ode, lambdafunc=lmb)
Esempio n. 20
0
    def __init__(self, firing_rate, record=False, **kwargs):
        
        if isinstance(firing_rate, str):
            self.firing_rate_string = str(firing_rate)
            self.closure = lambdify(sym_t,symp.parse_expr(self.firing_rate_string, local_dict={'Heaviside':lambda x: Piecewise((0,x<0), (1,x>0),(.5,True))}))
        elif hasattr(firing_rate, "__call__"):
            self.closure = firing_rate
        else:
            self.firing_rate_string = str(firing_rate)
            self.closure = lambdify(sym_t,symp.parse_expr(self.firing_rate_string))

        self.record = record
        self.type = "external"
        
        # Additional metadata:
        self.metadata = kwargs
Esempio n. 21
0
def test_2d():
    B1, B2 = [gen_BrownianMotion() for _ in range(2)]
    B1s = implemented_function("B1", B1)
    B2s = implemented_function("B2", B2)
    s, t = sympy.symbols(('s', 't'))
    e = B1s(s)+B2s(t)
    ee = lambdify((s,t), e)
    assert_almost_equal(ee(B1.x, B2.x), B1.y + B2.y)
Esempio n. 22
0
 def numerical_equilibrium(self):
     
     res = self.deterministic()
     f = lambdify(res.keys(), res.values())
     g = lambda y, t: f(*y)
     r = odeint(g, y0=np.ones(len(res.keys())), t=[0.0, 1e6])[-1]
     r = odeint(g, y0=r, t=[0.0, 1e6])[-1]
     return dict(zip(res.keys(), r))
def Makeufunc():
    import sympy
    from sympy.utilities.lambdify import lambdify

    x, nu, t = sympy.symbols('x nu t')
    phi = sympy.exp(-(x-4*t)**2/(4*nu*(t+1))) + sympy.exp(-(x-4*t-2*np.pi)**2/(4*nu*(t+1)))
    u = -2*nu*(phi.diff(x)/phi)+4
    return lambdify((t,x,nu),u)
Esempio n. 24
0
 def _lambdify(self):
     lambda_list = []
     vars = [range_[0] for range_ in self._ranges[1:]]
     for sym_sol in self.sym_sols:
         lambda_list.append(lambdify(vars,sym_sol))
     self.__call__.__func__.__doc__ += ('Function signature is f('
                                        +','.join([str(var) for var in vars]
                                                  )+')\n')
     return vars,lambda_list
Esempio n. 25
0
 def num_eval_correlation(self, symbol=None, values=None, uncertainties=None):
     if symbol == None:
         return self.value(), self.uncertainty()
     
     valfunc = lambdify(symbol, self.value_correlation(), 'numpy')
     if uncertainties == None:        
         uncertaintyfunc = lambdify(symbol, self.uncertainty(), 'numpy')
         return valfunc(values), uncertaintyfunc(values)
     else:
         #We define u_sym as a 'DeferredVector' to be able to use it in lambdify as one input.
         u_sym = sympy.DeferredVector('u_sym')
         #To be able to square term by term in a sympy matrix, square terms separately:
         usquared = {}
         for j in range(4):
             usquared[j] = self.uncertainty_squared_correlation()[j] + \
                 (self.formula.diff(symbol).subs(self.values)[j] * u_sym[j])**2
         u = (sympy.sqrt(usquared[0]),sympy.sqrt(usquared[1]),sympy.sqrt(usquared[2]),sympy.sqrt(usquared[3]))
         uncertaintyfunc = lambdify((symbol, u_sym), u, 'numpy')
         return valfunc(values), uncertaintyfunc(values, uncertainties)       
Esempio n. 26
0
    def __init__(self, firing_rate, record=False, **kwargs):

        self.firing_rate_string = str(firing_rate)
        self.closure = lambdify(sym_t, symp.parse_expr(self.firing_rate_string))

        self.record = record
        self.type = "external"

        # Additional metadata:
        self.metadata = kwargs
Esempio n. 27
0
def get_value(expr):
    """ calculates number value of an expression possibly containing quantities
    """
    calcFunction=lambdify(expr.free_symbols, expr, modules="numpy")
    depValues=[]
    for var in expr.free_symbols:
        if var.value is None:
            raise RuntimeError ("quantity '%s' doesn't have a value, yet." % var.name)
        depValues.append(var.value)
    return calcFunction(*depValues)
Esempio n. 28
0
def sympy_to_py(func, vars, params):
    """
    Turn a symbolic expression into a Python lambda function,
    which has the names of the variables and parameters as it's argument names.
    :param func: sympy expression
    :param vars: variables in this model
    :param params: parameters in this model
    :return: lambda function to be used for numerical evaluation of the model.
    """
    return lambdify((vars + params), func, modules='numpy', dummify=False)
Esempio n. 29
0
def _compare_tensorflow_matrix(variables, expr):
    f = lambdify(variables, expr, 'tensorflow')
    random_matrices = [Matrix([[random.randint(0, 10) for k in
        range(i.shape[1])] for j in range(i.shape[0])]) for i in variables]
    random_variables = [eval(tensorflow_code(i)) for i in
            random_matrices]
    r = session.run(f(*random_variables))
    e = expr.subs({k: v for k, v in zip(variables, random_matrices)}).doit()
    if e.is_Matrix:
        e = e.tolist()
    assert (r == e).all()
Esempio n. 30
0
def test_issue_11463():
    numpy = import_module('numpy')
    if not numpy:
        skip("numpy not installed.")
    x = Symbol('x')
    f = lambdify(x, real_root((log(x/(x-2))), 3), 'numpy')
    # numpy.select evaluates all options before considering conditions,
    # so it raises a warning about root of negative number which does
    # not affect the outcome. This warning is suppressed here
    with ignore_warnings(RuntimeWarning):
        assert f(numpy.array(-1)) < -1
Esempio n. 31
0
 def calculate_speed(self):
     self.sp_func["speed"] = sp.sqrt(self.sp_func["x"] * self.sp_func["x"] +
                                     self.sp_func["y"] * self.sp_func["y"])
     self.np_func["speed"] = lambdify(self.sp_func["t"],
                                      self.sp_func["speed"], 'numpy')
     self.np_array["speed"] = self.np_func["speed"](self.np_array["t"])
Esempio n. 32
0
def test_log2():
    if not np:
        skip("NumPy not installed")
    assert abs(lambdify((a,), log2(a), 'numpy')(256) - 8) < 1e-16
Esempio n. 33
0
def Restrictions(i):
    x1 = Symbol('x1')
    x2 = Symbol('x2')
    x3 = Symbol('x3')
    x4 = Symbol('x4')
    x5 = Symbol('x5')
    x6 = Symbol('x6')
    x7 = Symbol('x7')

    inf1 = -log((x1 - 2.6)*10**6)
    inf2 = -log((x2 - 0.7)*10**6)
    inf3 = -log((x3 - 17)*10**6)
    inf4 = -log((x4 - 7.3)*10**6)
    inf5 = -log((x5 - 7.8)*10**6)
    inf6 = -log((x6 - 2.9)*10**6)
    inf7 = -log((x7 - 5)*10**6)

    sup1 = -log((3.6 - x1)*10**6)
    sup2 = -log((0.8 - x2)*10**6)
    sup3 = -log((28 - x3)*10**6)
    sup4 = -log((8.3 - x4)*10**6)
    sup5 = -log((8.3 - x5)*10**6)
    sup6 = -log((3.9 - x6)*10**6)
    sup7 = -log((5.5 - x7)*10**6)

    h = inf1 + inf2**2 + inf3 + inf4 + inf5 + inf6 + inf7 + sup1 + sup2 + sup3 + sup4 + sup5 + sup6 + sup7
    #h = (inf1 + sup1)**(1/2) + (inf2 + sup2)**(1/2) + (inf3 + sup3)**(1/2) + (inf4 + sup4)**(1/2) + (inf5 + sup5)**(1/2) + (inf6 + sup6)**(1/2) + (inf7 + sup7)**(1/2)
    g = [[inf1], [inf2], [inf3], [inf4], [inf5], [inf6], [inf7], [sup1], [sup2], [sup3], [sup4], [sup5], [sup6], [sup7]]
    if i == 1:
        return h
    else:
        g = np.array([lambdify([x1, x2, x3, x4, x5, x6, x7], g(x1), 'numpy')],
                     [lambdify([x1, x2, x3, x4, x5, x6, x7], g(x2), 'numpy')],
                     [lambdify([x1, x2, x3, x4, x5, x6, x7], g(x3), 'numpy')],
                     [lambdify([x1, x2, x3, x4, x5, x6, x7], g(x4), 'numpy')],
                     [lambdify([x1, x2, x3, x4, x5, x6, x7], g(x5), 'numpy')],
                     [lambdify([x1, x2, x3, x4, x5, x6, x7], g(x6), 'numpy')],
                     [lambdify([x1, x2, x3, x4, x5, x6, x7], g(x7), 'numpy')],
                     [lambdify([x1, x2, x3, x4, x5, x6, x7], g(x1), 'numpy')],
                     [lambdify([x1, x2, x3, x4, x5, x6, x7], g(x2), 'numpy')],
                     [lambdify([x1, x2, x3, x4, x5, x6, x7], g(x3), 'numpy')],
                     [lambdify([x1, x2, x3, x4, x5, x6, x7], g(x4), 'numpy')],
                     [lambdify([x1, x2, x3, x4, x5, x6, x7], g(x5), 'numpy')],
                     [lambdify([x1, x2, x3, x4, x5, x6, x7], g(x6), 'numpy')],
                     [lambdify([x1, x2, x3, x4, x5, x6, x7], g(x7), 'numpy')])
        return g
Esempio n. 34
0
_E1 = a1 * sp.Matrix(E1) + b1 * sp.Matrix(E2) + c1 * sp.Matrix(P_i)
_E2 = a2 * sp.Matrix(E1) + b2 * sp.Matrix(E2) + c2 * sp.Matrix(P_i)
R = s * sp.Matrix(E1) + t * sp.Matrix(E2)

f = Matrix([
    _E1.dot(_E1) - 1,
    _E2.dot(_E2) - 1,
    _E1.dot(_E2),
    R.dot(R) - 1,
    _E1.dot(R) - sp.Matrix(E1).dot(R),
    _E2.dot(R) - sp.Matrix(E2).dot(R),
    sp.Matrix(P_i).dot(_E1) - x2_s,
    sp.Matrix(P_i).dot(_E2) - y2_s
])

lam_f = lambdify(var, sp.simplify(f), 'numpy')


def lam(x2, y2, p, e_1, e_2):
    return lambda a1,b1,c1,a2,b2,c2,t,s: \
        ((lam_f(x2, y2, sp.Matrix(p), sp.Matrix(e_1), sp.Matrix(e_2), a1, b1, c1, a2, b2, c2, t, s)) ** 2).sum()
    # np.linalg.norm(~) よりも高速。(速いとは言ってない)


arr = np.array([1, 1, 1, 1, 1, 1, 1, 1])

X_sample = 3 * np.random.random_sample((100, 1)) - 1.5
Y_sample = 3 * np.random.random_sample((100, 1)) - 1.5

print("ready")
Esempio n. 35
0
def test_sqrt():
    if not np:
        skip("NumPy not installed")
    assert abs(lambdify((a,), sqrt(a), 'numpy')(4) - 2) < 1e-16
Esempio n. 36
0
    def _setup_design(self):
        """ Initialize design

        Create a callable object to evaluate the design matrix at a given set
        of parameter values to be specified by a recarray and observed Term
        values, also specified by a recarray.
        """
        # the design expression is the differentiation of the expression
        # for the mean.  It is a list
        d = self.design_expr
        # Before evaluating, we recreate the formula
        # with numbered terms, and numbered parameters.

        # This renaming has no impact on the
        # final design matrix as the
        # callable, self._f below, is a lambda
        # that does not care about the names of the terms.

        # First, find all terms in the mean expression,
        # and rename them in the form "__t%d__" with a
        # random offset.
        # This may cause a possible problem
        # when there are parameters named something like "__t%d__".
        # Using the random offset will minimize the possibility
        # of this happening.

        # This renaming is here principally because of the intercept.

        random_offset = np.random.random_integers(low=0, high=2**30)

        terms = getterms(self.mean)

        newterms = []
        for i, t in enumerate(terms):
            newt = sympy.Symbol("__t%d__" % (i + random_offset))
            for j, _ in enumerate(d):
                d[j] = d[j].subs(t, newt)
            newterms.append(newt)

        # Next, find all parameters that remain in the design expression.
        # In a standard regression model, there will be no parameters
        # because they will all be differentiated away in computing
        # self.design_expr. In nonlinear models, parameters will remain.

        params = getparams(self.design_expr)
        newparams = []
        for i, p in enumerate(params):
            newp = Dummy("__p%d__" % (i + random_offset))
            for j, _ in enumerate(d):
                d[j] = d[j].subs(p, newp)
            newparams.append(newp)

        # If there are any aliased functions, these need to be added
        # to the name space before sympy lambdifies the expression

        # These "aliased" functions are used for things like
        # the natural splines, etc. You can represent natural splines
        # with sympy but the expression is pretty awful.  Note that
        # ``d`` here is list giving the differentiation of the
        # expression for the mean.  self._f(...) therefore also returns
        # a list
        self._f = lambdify(newparams + newterms, d, ("numpy"))

        # The input to self.design will be a recarray of that must
        # have field names that the Formula will expect to see.
        # However, if any of self.terms are FactorTerms, then the field
        # in the recarray will not actually be in the Term.
        #
        # For example, if there is a Factor 'f' with levels ['a','b'],
        # there will be terms 'f_a' and 'f_b', though the input to
        # design will have a field named 'f'. In this sense,
        # the recarray used in the call to self.design
        # is not really made up of terms, but "preterms".

        # In this case, the callable

        preterm = []
        for t in terms:
            if not is_factor_term(t):
                preterm.append(str(t))
            else:
                preterm.append(t.factor_name)
        preterm = list(set(preterm))

        # There is also an argument for parameters that are not
        # Terms.

        self._dtypes = {
            'param': np.dtype([(str(p), np.float) for p in params]),
            'term': np.dtype([(str(t), np.float) for t in terms]),
            'preterm': np.dtype([(n, np.float) for n in preterm])
        }

        self.__terms = terms
Esempio n. 37
0
def createMMSSourceFunctionsHydroOnly(rho,
                                      u,
                                      E,
                                      gamma_value,
                                      cv_value,
                                      alpha_value,
                                      display_equations=False):

    # declare symbolic variables
    x, t, alpha, Qpsim, Qpsip = symbols('x t alpha Qpsim Qpsip')
    gamma, cv, a = symbols('gamma c_v a')

    # compute other thermodynamic quantities based on ideal gas EOS
    e = E / rho - u * u / 2
    p = rho * e * (gamma - 1)
    rhou = rho * u

    # temporal derivatives
    drhodt = diff(rho, t)
    drhoudt = diff(rhou, t)
    dEdt = diff(E, t)

    # spatial derivatives
    drhoudx = diff(rhou, x)
    drhouudx = diff(rhou * u, x)
    dpdx = diff(p, x)
    dEfluxdx = diff((E + p) * u, x)

    # compute sources
    Qrho = drhodt + drhoudx
    Qu = drhoudt + drhouudx + dpdx
    QE = dEdt + dEfluxdx
    Qpsim = 0
    Qpsip = 0

    # display equations
    if display_equations:

        # initialize printing to use prettiest format available (e.g., LaTeX, Unicode)
        init_printing()

        # create an equation and then display it
        eq = Eq(symbols('rho'), rho)
        display(eq)
        eq = Eq(symbols('u'), u)
        display(eq)
        eq = Eq(symbols('E'), E)
        display(eq)
        eq = Eq(symbols('e'), e)
        display(eq)
        eq = Eq(symbols('p'), p)
        display(eq)
        eq = Eq(symbols('Q_rho'), Qrho)
        display(eq)
        eq = Eq(symbols('Q_u'), Qu)
        display(eq)
        eq = Eq(symbols('Q_E'), QE)
        display(eq)

    # substitute for all symbols except x and t
    substitutions = dict()
    substitutions['alpha'] = alpha_value
    substitutions['a'] = GC.RAD_CONSTANT
    substitutions['c_v'] = cv_value
    substitutions['gamma'] = gamma_value

    # make substitutions
    Qrho_sub = Qrho.subs(substitutions)
    Qu_sub = Qu.subs(substitutions)
    QE_sub = QE.subs(substitutions)

    # create MMS source functions
    rho_f = lambdify((symbols('x'), symbols('t')), Qrho_sub, "numpy")
    u_f = lambdify((symbols('x'), symbols('t')), Qu_sub, "numpy")
    E_f = lambdify((symbols('x'), symbols('t')), QE_sub, "numpy")
    psim_f = lambdify((symbols('x'), symbols('t')), Qpsim, "numpy")
    psip_f = lambdify((symbols('x'), symbols('t')), Qpsip, "numpy")

    return (rho_f, u_f, E_f, psim_f, psip_f)
Esempio n. 38
0
def test_exp2():
    if not np:
        skip("NumPy not installed")
    assert abs(lambdify((a,), exp2(a), 'numpy')(5) - 32) < 1e-16
Esempio n. 39
0
    def __init__(self, sympy_function, sympy_variables, args={}):
        self.sympy_function = sympy_function.subs(args)
        self.sympy_variables = sympy_variables
        self.lambdified = lambdify(self.sympy_variables, self.sympy_function)
        clear_cache()
        # I need a unique way to identify the integrand libraries I will be
        # generating. id(self) works sort of, but it may or may not be unique
        # I think. I'm going to try a hash of the underlying sympy function,
        # but I can't allow negative numbers (C gets confused), so I have to
        # generate a positive integer instead. Stackoverflow had this idea:
        self.unique_id = ctypes.c_size_t(hash(self.sympy_function)).value
        # stackoverflow.com/questions/18766535/...
        #   positive-integer-from-python-hash-function
        filename_prefix = os.path.join('integrand_libs',
                                       'integrand' + str(self.unique_id))
        libname_prefix = os.path.join('integrand_libs',
                                      '' + str(self.unique_id))
        # Enable the use of ctypes objects in nquad, once multivariate ctypes objects
        # are appropriate arguments for the QUADPACK library functions.
        try:
            self.generated_code = codegen(
                ('integrand', self.sympy_function),
                'C',
                filename_prefix,
                argument_sequence=self.sympy_variables,
                to_files=True)
        except IOError:
            import pdb
            pdb.set_trace()
        args_str = ",".join([
            "args[" + str(ind) + "]"
            for ind in range(len(self.sympy_variables))
        ])
        extra_c_code = "".join([
            r"""
double integrand_wrapper(int n, double args[n])
{
   return integrand(""", args_str, """);

}
"""
        ])
        extra_h_code = """

double integrand_wrapper(int n, double args[n]);

"""

        f = open(filename_prefix + ".c", 'a')
        f.write(extra_c_code)
        f.close()
        f = open(filename_prefix + ".h", 'a')
        f.write(extra_h_code)
        f.close()
        cmd = ("gcc -dynamiclib -O3 -I. " + filename_prefix + ".c -o " +
               filename_prefix + ".dylib")
        subprocess.call(cmd, shell=True)
        self.ctypeslib = ctypes.CDLL(filename_prefix + '.dylib')
        self.ctypesified = self.ctypeslib.integrand_wrapper
        self.ctypesified.restype = ctypes.c_double
        # Test the reliability of ctypesified function. This should be
        # disabled eventually.
        self.ctypesified.argtypes = (ctypes.c_int, len(self.sympy_variables) *
                                     ctypes.c_double)

        test = []
        for indx in range(0):
            randargs = [random.random() for item in self.sympy_variables]
            temp = (self.lambdified(*randargs) - self.ctypesified(
                ctypes.c_int(len(self.sympy_variables)),
                (len(self.sympy_variables) * ctypes.c_double)(*randargs)))
            if temp**2 > .00000001:
                test.append(temp)
        if test:
            raise IntegrationError("Ctypesified and lambdified do not match!")
        self.ctypesified.argtypes = ctypes.c_int, ctypes.c_double
        return None
Esempio n. 40
0
import sympy as sp
import numpy as np
import scipy.optimize as opt
from commons import *
from sympy.utilities.lambdify import lambdify, implemented_function

chi2_sym = (y_theo_sym - summer2015['y_exp']).T * summer2015['y_covar_inv'] * (
    y_theo_sym - summer2015['y_exp'])
chi2 = lambda args: lambdify(ys, chi2_sym, 'numpy')(*args)[0, 0]

#Symbolic solutions

#print("Symbolic: ")
#print(sp.solvers.solve(chi2_sym.jacobian(ys), ys))

#Numerical solutions

print("Numerical: ")

#Calculate using Newton
result = opt.minimize(chi2, [0, 0, 0.01], method='TNC', bounds=bounds[1])
print("Newton's method")
print(result.fun)
print(result.x.tolist())

#Calculate using jacobian
print("Newton's with Jacobian matrix")
jacobian = lambda x: lambdify(ys, chi2_sym.jacobian(ys), 'numpy')(*x)
hessian = lambda x: sp.hessian(ys, sp.hessian(chi2_sym, ys), 'numpy')(*x)
result = opt.minimize(
    chi2,
Esempio n. 41
0
from numpy import *
from math import *
import sympy as sym
from sympy.utilities.lambdify import lambdify, implemented_function
x = sym.Symbol('x')
s = '5*x-8*sym.log(x)-8'  #сюда функцию в каноническом виде
f = lambdify(x, eval(s), 'numpy')
f_dash = lambdify(x, sym.diff(eval(s), x, 1), 'numpy')
f_2dash = lambdify(x, sym.diff(eval(s), x, 2), 'numpy')

x0 = 345345  #начальное приближение
e = 1e-5  #точность

n = 0
while (True):
    n += 1
    print("Итерация {0} - x сейчас равен {1}".format(n, x0))
    x = x0 - f(x0) / f_dash(x0) - (f(x0)**2 * f_2dash(x0)) / (2 *
                                                              (f_dash(x0)**3))
    if abs(x0 - x) <= e: break
    x0 = x
print("За {0} итераций получили корень {1} с точностью {2}".format(n, x0, e))
Esempio n. 42
0
File: FD.py Progetto: octasam/GeoMaC
def numericalDer(f, x0, h, aprox='All'):
    t = Symbol('x')
    fp = diff(f, t)
    evalfp = lambdify(t, fp, modules=['numpy'])
    evalf = lambdify(t, f, modules=['numpy'])

    fp_value = evalfp(x0)
    ef = np.fabs(fp_value - forwardFD(evalf, x0, h))
    eb = np.fabs(fp_value - backwardFD(evalf, x0, h))
    ec = np.fabs(fp_value - centeredFD(evalf, x0, h))

    xl = np.linspace(x0 - 0.5 * np.pi, x0 + 0.5 * np.pi, 50)
    xv = np.linspace(x0 - np.pi, x0 + np.pi, 50)

    lf = line(xl, x0, x0 + h, evalf(x0), evalf(x0 + h))
    lb = line(xl, x0, x0 - h, evalf(x0), evalf(x0 - h))
    lc = line(xl, x0 - h, x0 + h, evalf(x0 - h), evalf(x0 + h))

    yv = evalf(xv)
    yp = evalfp(xv)

    ancho_linea = 2.0

    fig = plt.figure(figsize=(10, 5))
    fig.suptitle('EF = {:10.4e}, EB = {:10.4e}, EC = {:10.4e}'.format(
        ef, eb, ec))

    ax1 = plt.subplot(1, 2, 1)
    plt.plot(xv, yv, '--', lw=3, color='b', label='f = {}'.format(f))
    plt.scatter(x0, evalf(x0), facecolor='b', edgecolor='k', zorder=10)

    if aprox == 'All':
        plt.scatter(x0 + h,
                    evalf(x0 + h),
                    facecolor='w',
                    edgecolor='k',
                    zorder=10)
        plt.scatter(x0 - h,
                    evalf(x0 - h),
                    facecolor='w',
                    edgecolor='k',
                    zorder=10)
        plt.scatter(x0 - 2 * h,
                    evalf(x0 - 2 * h),
                    facecolor='w',
                    edgecolor='k',
                    zorder=10)
        plt.plot(xl, lf, lw=ancho_linea, label="f' = Forward")
        plt.plot(xl, lb, lw=ancho_linea, label="f' = Backward")
        plt.plot(xl, lc, lw=ancho_linea, label="f' = Centered")

    elif aprox == 'Forward':
        plt.scatter(x0 + h,
                    evalf(x0 + h),
                    facecolor='w',
                    edgecolor='k',
                    zorder=10)
        plt.plot(xl, lf, lw=ancho_linea, label="f' = Forward")

    elif aprox == 'Backward':
        plt.scatter(x0 - h,
                    evalf(x0 - h),
                    facecolor='w',
                    edgecolor='k',
                    zorder=10)
        plt.plot(xl, lb, lw=ancho_linea, label="f' = Backward")

    elif aprox == 'Centered':
        plt.scatter(x0 + h,
                    evalf(x0 + h),
                    facecolor='w',
                    edgecolor='k',
                    zorder=10)
        plt.scatter(x0 - h,
                    evalf(x0 - h),
                    facecolor='w',
                    edgecolor='k',
                    zorder=10)
        plt.plot(xl, lc, lw=ancho_linea, label="f' = Centered")

    plt.legend(loc=(-1.0, 0.5))

    ax2 = plt.subplot(1, 2, 2)
    plt.plot(xv, yp, '--', lw=3, color='k', label="f'= {}".format(fp))

    if aprox == 'All':
        plt.plot(xv, forwardFD(evalf, xv, h), lw=ancho_linea)
        plt.plot(xv, backwardFD(evalf, xv, h), lw=ancho_linea)
        plt.plot(xv, centeredFD(evalf, xv, h), lw=ancho_linea)
    elif aprox == 'Forward':
        plt.plot(xv, forwardFD(evalf, xv, h), lw=ancho_linea)
    elif aprox == 'Backward':
        plt.plot(xv, backwardFD(evalf, xv, h), lw=ancho_linea)
    elif aprox == 'Centered':
        plt.plot(xv, centeredFD(evalf, xv, h), lw=ancho_linea)

    plt.legend()

    plt.show()
    return [ef, eb, ec]
Esempio n. 43
0
def jacobian(functions, variables, constants):
    symbols = dict((v, Symbol("x[%d]" % i)) for (i, v) in enumerate(variables))
    f = Matrix([parse_func(expr, symbols, constants) for expr in functions])
    x = Matrix(list(symbols.values()))
    return lambdify("x", f), lambdify("x", f.jacobian(x))
Esempio n. 44
0
    def normal_lines(self, p, prec=None):
        """Normal lines between `p` and the ellipse.

        Parameters
        ==========

        p : Point

        Returns
        =======

        normal_lines : list with 1, 2 or 4 Lines

        Examples
        ========

        >>> from sympy import Line, Point, Ellipse
        >>> e = Ellipse((0, 0), 2, 3)
        >>> c = e.center
        >>> e.normal_lines(c + Point(1, 0))
        [Line(Point(0, 0), Point(1, 0))]
        >>> e.normal_lines(c)
        [Line(Point(0, 0), Point(0, 1)), Line(Point(0, 0), Point(1, 0))]

        Off-axis points require the solution of a quartic equation. This
        often leads to very large expressions that may be of little practical
        use. An approximate solution of `prec` digits can be obtained by
        passing in the desired value:

        >>> e.normal_lines((3, 3), prec=2)
        [Line(Point(-38/47, -85/31), Point(9/47, -21/17)),
        Line(Point(19/13, -43/21), Point(32/13, -8/3))]

        Whereas the above solution has an operation count of 12, the exact
        solution has an operation count of 2020.
        """
        p = Point(p)

        # XXX change True to something like self.angle == 0 if the arbitrarily
        # rotated ellipse is introduced.
        # https://github.com/sympy/sympy/issues/2815)
        if True:
            rv = []
            if p.x == self.center.x:
                rv.append(Line(self.center, slope=oo))
            if p.y == self.center.y:
                rv.append(Line(self.center, slope=0))
            if rv:
                # at these special orientations of p either 1 or 2 normals
                # exist and we are done
                return rv

        # find the 4 normal points and construct lines through them with
        # the corresponding slope
        x, y = Dummy('x', real=True), Dummy('y', real=True)
        eq = self.equation(x, y)
        dydx = idiff(eq, y, x)
        norm = -1 / dydx
        slope = Line(p, (x, y)).slope
        seq = slope - norm
        points = []
        if prec is not None:
            yis = solve(seq, y)[0]
            xeq = eq.subs(y, yis).as_numer_denom()[0].expand()
            try:
                iv = list(zip(*Poly(xeq).intervals()))[0]
                # bisection is safest here since other methods may miss root
                xsol = [
                    S(nroot(lambdify(x, xeq), i, solver="anderson"))
                    for i in iv
                ]
                points = [
                    Point(i,
                          solve(eq.subs(x, i), y)[0]).n(prec) for i in xsol
                ]
            except PolynomialError:
                pass
        if not points:
            points = [Point(*s) for s in solve((seq, eq), (x, y))]
            # complicated expressions may not be decidably real so evaluate to
            # check whether they are real or not
            points = [
                i.n(prec) if prec is not None else i for i in points if all(
                    j.n(2).is_real for j in i.args)
            ]
        slopes = [norm.subs(zip((x, y), pt.args)) for pt in points]
        if prec is not None:
            slopes = [
                i.n(prec) if i not in (-oo, oo, zoo) else i for i in slopes
            ]
        return [Line(pt, slope=s) for pt, s in zip(points, slopes)]
Esempio n. 45
0
    time_derivative(eta_sol, N) + 4 * eta_sol * (eta_sol - 1) *
    (eta_sol - 0.5) - divergence(kappa * gradient(eta_sol, N), N))

parameters = ((kappa, params['kappa']), (A1, 0.0075), (B1, 8.0 * pi),
              (A2, 0.03), (B2, 22.0 * pi), (C2, 0.0625 * pi))

# substitute coefficient values

subs = [sub.subs(parameters) for sub in (eq_sol, eta_sol)]

# generate FiPy lambda functions

from sympy.utilities.lambdify import lambdify, lambdastr

(eq_fp, eta_fp) = [
    lambdify((N[0], N[1], t), sub, modules=fp.numerix) for sub in subs
]
kappa_fp = float(kappa.subs(parameters))

# Can't pickle lambda functions

(eq_str, eta_str) = [lambdastr((N[0], N[1], t), sub) for sub in subs]

data.categories["eq"] = eq_str
data.categories["eta"] = eta_str
data.categories["kappa"] = kappa_fp

# initialize and store variables

totaltime = params['totaltime']
dt = float(params['dt'])
Esempio n. 46
0
    def optimize(self, ip):
        ''' Optimizes a series of instructions starting from ip to a
            single lambda function.
        '''
        # symbolic registers
        sreg = sympy.symbols(', '.join(
            ['r[%d]' % n for n in range(self.nregs)]))

        # values of symbolic regs
        sregv = list(sreg)

        ip_start = ip
        bbl = 0

        while True:
            # create symbolic representation of instruction
            op, args = self.program[ip]
            s = self.ins2sym((op, args), 'sregv')
            bbl += 1

            if DEBUG:
                print('%s %s' % (op.__name__, args))
                print(s)

            # execute symbolic representation of op
            #print('-------')
            #print(s)
            #print(args[2], sregv)
            #print(sregv[3])
            exec(s)

            # convert bool to int
            #if op.__name__.startswith('eq') or op.__name__.startswith('gt'):
            #if sregv[args[2]] == sympy.true:
            #sregv[args[2]] = 1
            #elif sregv[args[2]] == sympy.false:
            #sregv[args[2]] = 0

            # increment symbolic ip
            sregv[self.ip] += 1

            # increment optimizer ip & continue
            if args[2] != self.ip:
                ip += 1
                continue

            # ip was written to - attempt chaining
            # covers cases we have observed in the input
            if op.__name__ == 'seti':
                ip = args[0] + 1
                continue
            elif op.__name__ == 'addi' and args[0] == self.ip:
                ip += args[1] + 1
                continue
            else:
                sregv = [sympy.expand(sr) for sr in sregv]
                ip_str = '{0:2d} {0:2d}'.format(ip_start, ip)
                print('B',
                      ip_str,
                      self.ins2sym((op, args), 'r'),
                      file=sys.stderr)
                print('C', ip_str, sregv, file=sys.stderr)
                break

        self.opt[ip_start] = (lambdify(sreg, sregv, ('math')), bbl)
        return self.opt[ip_start]
Esempio n. 47
0
    def _generate_features(self, df, new_feat_cols):
        """
        Generate additional features based on the feature formulas for all data points in the df.
        Only works after the model was fitted.

        Inputs:
            - df: pandas dataframe with original features
            - new_feat_cols: names of new features that should be generated (keys of self.feature_formulas_)
        Returns:
            - df: dataframe with the additional feature columns added
        """
        check_is_fitted(self, ["feature_formulas_"])
        if not new_feat_cols:
            return df
        if not new_feat_cols[0] in self.feature_formulas_:
            raise RuntimeError(
                "[AutoFeat] First call fit or fit_transform to generate the features!"
            )
        if self.verbose:
            print("[AutoFeat] Computing %i new features." % len(new_feat_cols))
        # generate all good feature; unscaled this time
        feat_array = np.zeros((len(df), len(new_feat_cols)))
        for i, expr in enumerate(new_feat_cols):
            if self.verbose:
                print("[AutoFeat] %5i/%5i new features" %
                      (i, len(new_feat_cols)),
                      end="\r")
            if expr not in self.feature_functions_:
                # generate a substitution expression based on all the original symbols of the original features
                # for the given generated feature in good cols
                # since sympy can handle only up to 32 original features in ufunctify, we need to check which features
                # to consider here, therefore perform some crude check to limit the number of features used
                cols = [
                    c for i, c in enumerate(self.feateng_cols_)
                    if colnames2symbols(c, i) in expr
                ]
                if not cols:
                    # this can happen if no features were selected and the expr is "E" (i.e. the constant e)
                    f = None
                    f_jit = None
                else:
                    try:
                        f = lambdify([self.feature_formulas_[c] for c in cols],
                                     self.feature_formulas_[expr])
                        f_jit = nb.njit(f)
                    except Exception:
                        print(
                            "[AutoFeat] Error while processing expression: %r"
                            % expr)
                        raise
                self.feature_functions_[expr] = (cols, f, f_jit)
            else:
                cols, f, f_jit = self.feature_functions_[expr]
            if f is not None:
                # only generate features for completely not-nan rows
                not_na_idx = df[cols].notna().all(axis=1)
                try:
                    try:
                        feat = f_jit(*(df[c].to_numpy(dtype=float)[not_na_idx]
                                       for c in cols))
                    except nb.TypingError:
                        # lambified abs fn with non trivial inputs doesn't jit compile with numba, yet
                        # fallback on the non jitted version of the function
                        feat = f(*(df[c].to_numpy(dtype=float)[not_na_idx]
                                   for c in cols))
                        # henceforth, always use the non jitted version of the function
                        self.feature_functions_[expr] = (cols, f, f)
                    feat_array[not_na_idx, i] = feat
                    feat_array[~not_na_idx, i] = np.nan
                except RuntimeWarning:
                    print(
                        "[AutoFeat] WARNING: Problem while evaluating expression: %r with columns %r"
                        % (expr, cols),
                        " - is the data in a different range then when calling .fit()? Are maybe some values 0 that shouldn't be?"
                    )
                    raise
        if self.verbose:
            print("[AutoFeat] %5i/%5i new features ...done." %
                  (len(new_feat_cols), len(new_feat_cols)))
        df = df.join(
            pd.DataFrame(feat_array, columns=new_feat_cols, index=df.index))
        return df
Esempio n. 48
0
 def calculate_arc_length(self):
     self.sp_func["arc"] = sp.integrate(self.sp_func["speed"],
                                        self.sp_func["t"])
     self.np_func["arc"] = lambdify(self.sp_func["t"], self.sp_func["arc"],
                                    'numpy')
     self.np_array["arc"] = self.np_func["arc"](self.np_array["t"])
Esempio n. 49
0

# l<n, |m|<=l
n = 3
l = 1
m = 0

print('generating triplets')
R = np.linspace(0, 20, 20)
T = np.linspace(0, np.pi, 10)
P = np.linspace(0, 2 * np.pi, 20)
R, T, P = np.meshgrid(R, T, P)

print('generating orbital')

Psi = abs(lambdify(
    (Orb.r, Orb.theta, Orb.phi), Orb.RealOrbital.orbital(n, l, m).evalf(), 'numpy')(R, T, P))

Psi = normalize(Psi)

print('orbital generated')

print('generating points')
x0, y0, z0 = Orb.SphToCart(R, T, P)
print('points generated')

fig = plt.figure()
ax0 = fig.add_subplot(111, projection='3d')

print('plotting')

print('generating colors')
Esempio n. 50
0
def Homotopy_Continuation(t, input_variables, input_functions, number_of_steps = 5, expanded_functions = None, expansion_variables = None,\
                          matrix_A = A, det_matrix = det_4by4_matrix, inverse_matrix = inverse_4by4_matrix, remainder_tolerance = 1e-2, check_determinant_H = 1e-6, \
                          newton_ratio_accuracy = 1e-10, max_newton_step = 5, debug = False, \
                          Newtons_method = True, save_path = False, file_name = 'Homotopy_Roots'):
    
    """
    Perfroms the Homotopy Continuation to determine the roots of a given function F, within a certain accuracy
    using the RK4 method during the predictor step and either Newton's method of Minuit for the root-finding step. 
    
    Parameters:
        t : Just given as a variable, the time step.
        input_variables : Symbols to use as variables. Must be given as an array or list. Length determines the
                            the number of dimensions to consider.
                          Example: [x,y] for 2 dimension, where the symbols used must first be imported above.
                          Must not contain t.
        input_functions : Function to be determined. Should be given as a list or array of variables.
                          Example: F = [x**2 , y**2]
        number_of_steps : Number of steps for the Homotopy Continuation. Default : 5
        expanded_functions : expansion into complex, Ex: [a + 1j*b, c + 1j*d]
                            Variables must first be imported above, and cannot contain those in input_variables or t
                            Only needed when Minuit is used
        expansion_variables = Array of variables for expansion to complex numbers, Ex for 2D : [a,b,c,d]
                            Only needed when Minuit is used
        remainder_tolerance : Tolerance for roots to be considered, how far is the function from zero.
        check_determinant_H : check that determinant is not below this tolerance
        newton_ratio_accuracy : Convergence criteria for Newton's
        max_newton_step = Max number of steps for Newton's method
        Newtons_method : Default True else use Minuit
        save_path : Tracks and saves how roots evolve
        file_name : Save roots in file
    """
    time_start = time.time()
    
    #convert F to a function
    F = lambdify([input_variables], input_functions)
    
    #store the least accurate root
    max_remainder_value = 0
    
    #count the number of roots found
    number_of_count = 0
    
    #step size
    delta_t = 1/number_of_steps
    
    #determine the number of dimensions considered
    dimension = len(input_variables)
    
    #generate gamma
    gamma = Gamma_Generator()
    
    #determine roots of easy polynomial
    G_roots = G_Roots(dimension)

    #construct homotopy
    H = Homotopy(t, G(input_variables), F(input_variables), gamma)
    
    #first derivative of H wrt to all the x variables
    derivative_H_wrt_x = sy.Matrix([[H[i].diff(input_variables[j]) for j in range(len(input_variables))] for i in range(len(input_variables))])
    print(len(derivative_H_wrt_x))
    print('here')
    
    
    if dimension < 4:
        time1 = time.time()
        determinant_H = derivative_H_wrt_x.det(method='lu')
        print('Cal: {}'.format(determinant_H))
    
        #invert the matrix of the derivatives of H wrt to x variables
        inverse_derivative_H_wrt_x = derivative_H_wrt_x.inv(method = 'LU')
        print('inv:{}'.format(inverse_derivative_H_wrt_x))
        time2 = time.time()
        print('Time for calculation : {}'.format(time2 - time1))
    
    else:

        time3 = time.time()
        determinant_H = det_matrix.subs(zip(list(matrix_A), list(derivative_H_wrt_x)))

        inverse_derivative_H_wrt_x = inverse_matrix.subs(list(zip(matrix_A, derivative_H_wrt_x)))
    

        time4 = time.time()
        print('Time for sub : {}'.format(time4 - time3))
        
    #check the determinant does not go to zero so can invert    
    if determinant_H == 0:
        raise TypeError('1. The determinant of H is zero!')
        
    print('reA H')
    
    #function of determinant H
    determinant_H_func = lambdify((t, input_variables), determinant_H)

    #derivative of H with respect to t
    derivative_H_wrt_t = sy.Matrix([H[i].diff(t) for i in range(len(input_variables))])
    
    print('halp')
    #differentiate of x wrt to t
    x_derivative_t = -inverse_derivative_H_wrt_x*derivative_H_wrt_t
    x_derivative_t_func = lambdify((t, input_variables), [x_derivative_t[i] for i in range(len(x_derivative_t))])
    x_derivative_t_func_1d = lambdify((t,input_variables), H[0].diff(t)/H[0].diff(x))
    
    #determine H/H' to use in Newton's method
    H_over_derivative_H_wrt_x = inverse_derivative_H_wrt_x*sy.Matrix(H)
    H_over_derivative_H_wrt_x_func = lambdify((t, input_variables), [H_over_derivative_H_wrt_x[i] for i in range(len(H_over_derivative_H_wrt_x))])
    
    #track paths of roots
    paths = []
    
    #track roots 
    solutions = []
    
    #track accuracy of each root
    accuracies = []
    print('reached here')
    #run for all roots in the starting system
    for x_old in G_roots:
        
        #path of each root
        trace = []
        
        #root number being found
        number_of_count += 1
        
        #set homotopy to inital system
        t_new = 0
        
        #convert 1D to an array
        if dimension == 1:
                x_old = np.array([x_old])
                
        #run for all steps starting at t=0 ending at t=1
        while round(t_new,5) < 1:
            trace.append(x_old)
            t_old = t_new
            
            #increment time by step size
            t_new += delta_t
            
            if dimension == 1:
                
                #perform RK4 for 1 D
                predictor = spi.solve_ivp(x_derivative_t_func_1d, (t_old, t_new), x_old)
                predicted_solution = np.array([predictor.y[-1][-1]])
                
            if dimension != 1:
                
                #check determinant to make sure does not go to zero
                if abs(determinant_H_func(t_new, x_old)) < check_determinant_H:
                    raise TypeError('2. The determinant of H is zero!')
                
                #perform RK4 method for n dimensions
                predictor = spi.solve_ivp(x_derivative_t_func, (t_old, t_new), x_old)
                predicted_solution = predictor.y[:,-1]   

            x_old = predicted_solution
            
            #newton's method
            
            #track how root changes and the number of steps used
            ratio = np.full(dimension, 1)
            number_of_newton_steps = 0
            change_in_x = np.full(dimension, newton_ratio_accuracy)
                
            if Newtons_method is True:
                method_used = 'Newton-Raphson with ' + str(max_newton_step) + ' steps.'
                
                #track amount of time newton uses for debugging
                time_newtons_start = time.time()
                
                #convergence criteria for step size in Newton's Method
                while max(ratio) > newton_ratio_accuracy and number_of_newton_steps < max_newton_step:
                    
                    if debug: print("Before Newton", x_old)
                    
                    #check determinant to ensure can invert
                    if dimension != 1:
                        if abs(determinant_H_func(t_new, x_old)) < check_determinant_H:
                            raise TypeError('3. The determinant of H is zero!')
                    
                    #find new position of root
                    x_old_intermediate = x_old - H_over_derivative_H_wrt_x_func(t_new, x_old)
                    change_in_x_old = change_in_x
                    change_in_x = abs(x_old_intermediate - x_old)
                    
                    #calculate change in position of root
                    ratio = [change_in_x[j]/(change_in_x_old[j] + 1e-10) for j in range(dimension)]
                    x_old = x_old_intermediate
                    number_of_newton_steps += 1
                    
                    time_newtons_end = time.time()
                    
                    if debug: print("After Newton", x_old)
                    
                if debug:
                    print('Time for Newton: {}'.format(time_newtons_end - time_newtons_start))
                    
            #Minuit
            else:
                method_used = 'Minuit'
                
                #Minuit only runs for more than 1 dimension
                if dimension == 1:
                    raise TypeError('Minuit only runs for more than 1 dimension!')
                
                #track time for debugging
                time_minuit_start = time.time()
                
                #substitute time t at each step into Homotopy equation
                H_at_fixed_t = Homotopy(t_new, G(expanded_functions), F(expanded_functions), gamma)
               
                if debug: print("Homotopy at current step: ", H_at_fixed_t)
                
                #split real and imaginary and sum absolute value of expressions
                H_im_real = sum([abs(sy.re(i_re)) for i_re in H_at_fixed_t] + [abs(sy.im(i_im)) for i_im in H_at_fixed_t])
                
                if debug: print("Homotopy Absolute value at current step: ", H_im_real)
                
                #convert into function
                H_im_real_func = lambdify([expansion_variables], H_im_real)

                x_old_re_im = []

                #split x_old to real and imaginary
                for i in range(dimension):
                    x_old_re_im.append(np.real(x_old[i]))
                    x_old_re_im.append(np.imag(x_old[i]))
                
                #convert variables to strings for input into Minuit
                string_variables = [str(j) for j in expansion_variables]
                
                #call iminuit function
                if debug: print("Before Minuit we start at", x_old_re_im)
                    
                printlevel = 10 if debug else 0
                
                #find roots using Minuit
                m = im.Minuit.from_array_func(H_im_real_func, x_old_re_im, forced_parameters= string_variables,print_level=printlevel)
                m.migrad(resume=False)
                x_old_im_re_vals = m.values
                
                #reconstruct roots from real and imaginary parts
                x_old = [x_old_im_re_vals[j] + 1j*x_old_im_re_vals[j+1] for j in range(0, 2*dimension, 2)]
                
                if debug: print("After Minuit we got", x_old)
                time_minuit_end = time.time()
                
                if debug:
                    print('Time for Minuit: {}'.format(time_minuit_end - time_minuit_start))
                    
            trace.append(x_old)    
            
        #check root is found by ensuring roots found is within the tolerance
        if dimension == 1 :
            remainder = list(map(abs, F([x_old])))
        remainder = list(map(abs, F(x_old))) 
        
        if max(remainder) < remainder_tolerance:
            #make root real if imaginary part is below the zero tolerance
            x_old = [x_old[i].real if abs(x_old[i].imag) < check_determinant_H else x_old[i] for i in range(len(x_old))]
            
            #store the maximum remainder
            max_rem = max(remainder)
            if max_remainder_value < max_rem:
                max_remainder_value = max_rem

            solutions.append(x_old)
            
            #if paths are wanted
            if save_path is True:
                paths.append(trace)
            accuracies.append(remainder)

    time_end = time.time()
    
    if save_path is False:
        paths = np.full(len(solutions),'-')
    
    #save information into csv file
    other_info = ['Function Used'] + input_functions + [''] + ['Time Taken'] + [time_end - time_start] + [''] + \
    ['Root Finding Method Used'] + [method_used] + [''] + ['Worst Accuracy'] + [max_remainder_value] + \
    [''] + ['Number of Homotopy Steps'] + [number_of_steps] 
    
    len_solutions = len(solutions)
    total_length = max(len(other_info), len_solutions)
    
    other_info = other_info + list(np.full(total_length - len(other_info), ''))
    solutions = solutions + list(np.full(total_length - len_solutions, ''))
    accuracies = accuracies + list(np.full(total_length - len_solutions, ''))
    paths = list(paths) + list(np.full(total_length - len_solutions, ''))
    df = pd.DataFrame({'Roots' : solutions, 'Accuracy' : accuracies, 'Paths' : paths, 'Other Info' : other_info})
    df.to_csv(file_name + '.csv', index=True)
    
    return solutions, paths
Esempio n. 51
0
var = (x_pre, y_pre, x_new, y_new, p_norm, a1, b1, c1, a2, b2, c2, t, s)

f = Matrix([
    a1 * a1 + b1 * b1 + c1 * c1 * p_norm + 2 *
    (a1 * c1 * x_pre + b1 * c1 * y_pre) - 1, a2 * a2 + b2 * b2 +
    c2 * c2 * p_norm + 2 * (a2 * c2 * x_pre + b2 * c2 * y_pre) - 1,
    a1 * a2 + b1 * b2 + c1 * c2 * p_norm + x_pre * (a1 * c2 + c1 * a2) +
    y_pre * (b1 * c2 + c1 * b2), s * s + t * t - 1,
    s * (a1 + c1 * x_pre - 1) + t * (b1 + c1 * y_pre),
    s * (a2 + c2 * x_pre) + t * (b2 + c2 * y_pre - 1),
    a1 * x_pre + b1 * y_pre + c1 * p_norm - x_new,
    a2 * x_pre + b2 * y_pre + c2 * p_norm - y_new
])

func = sp.Matrix.norm(f)
lam_f = lambdify(var, func, 'numpy')


def lam(x_pre, y_pre, x_new, y_new, p_norm):
    return lambda a1,b1,c1,a2,b2,c2,t,s: \
        lam_f(x_pre,y_pre,x_new,y_new,p_norm,a1,b1,c1,a2,b2,c2,t,s)


arr_init = np.array([1, 0, 0, 0, 1, 0, 1, 1])
print("lambda: ready")

######## Graph Drawing ########
root = Tk()
w = Canvas(root, width=_width, height=_height, bg='White')
w.pack()
circles = []
Esempio n. 52
0
def createMMSSourceFunctionsRadHydro(rho,
                                     u,
                                     E,
                                     psim,
                                     psip,
                                     sigma_s_value,
                                     sigma_a_value,
                                     gamma_value,
                                     cv_value,
                                     alpha_value,
                                     display_equations=False):

    # declare symbolic variables
    x, t, alpha = symbols('x t alpha')
    sigs, siga, sigt = symbols('sigma_s sigma_a sigma_t')
    gamma, cv, c, a = symbols('gamma c_v c a')

    # compute other thermodynamic quantities based on ideal gas EOS
    e = E / rho - u * u / 2
    p = rho * e * (gamma - 1)
    T = e / cv
    rhou = rho * u

    # compute other radiation quantities
    phi = psim + psip
    Er = phi / c
    Fr = (psip - psim) / sqrt(3)
    Fr0 = Fr - sympify('4/3') * Er * u
    Q0 = siga * a * c * T**4 - sigt * u / c * Fr0
    Q1 = sympify('4/3') * sigt * Er * u
    Qm = Q0 - sympify('3/sqrt(3)') * Q1
    Qp = Q0 + sympify('3/sqrt(3)') * Q1

    # temporal derivatives
    drhodt = diff(rho, t)
    drhoudt = diff(rhou, t)
    dEdt = diff(E, t)
    dpsimdt = diff(psim, t)
    dpsipdt = diff(psip, t)

    # spatial derivatives
    drhoudx = diff(rhou, x)
    drhouudx = diff(rhou * u, x)
    dpdx = diff(p, x)
    dEfluxdx = diff((E + p) * u, x)
    dpsimdx = diff(psim, x)
    dpsipdx = diff(psip, x)

    # compute sources
    Qrho = drhodt + drhoudx
    Qu = drhoudt + drhouudx + dpdx - sigt / c * Fr0
    QE = dEdt + dEfluxdx + siga * c * (a * T**4 - Er) - sigt * u / c * Fr0
    Qpsim = dpsimdt / c - dpsimdx / sqrt(
        3) + sigt * psim - sigs / 2 * phi - Qm / 2
    Qpsip = dpsipdt / c + dpsipdx / sqrt(
        3) + sigt * psip - sigs / 2 * phi - Qp / 2

    # display equations
    if display_equations:

        # initialize printing to use prettiest format available (e.g., LaTeX, Unicode)
        init_printing()

        # create an equation and then display it
        eq = Eq(symbols('rho'), rho)
        display(eq)
        eq = Eq(symbols('u'), u)
        display(eq)
        eq = Eq(symbols('E'), E)
        display(eq)
        eq = Eq(symbols('e'), simplify(e))
        display(eq)
        eq = Eq(symbols('T'), T)
        display(eq)
        eq = Eq(symbols('p'), p)
        display(eq)
        eq = Eq(symbols('Psi^-'), psim)
        display(eq)
        eq = Eq(symbols('Psi^+'), psip)
        display(eq)
        eq = Eq(symbols('E_r'), Er)
        display(eq)
        eq = Eq(symbols('F_r'), Fr)
        display(eq)
        eq = Eq(symbols('Q_rho'), Qrho)
        display(eq)
        eq = Eq(symbols('Q_u'), Qu)
        display(eq)
        eq = Eq(symbols('Q_E'), QE)
        display(eq)
        eq = Eq(symbols('Q_-'), Qpsim)
        display(eq)
        eq = Eq(symbols('Q_+'), Qpsip)
        display(eq)

    # substitute for all symbols except x and t
    substitutions = dict()
    substitutions['alpha'] = alpha_value
    substitutions['a'] = GC.RAD_CONSTANT
    substitutions['c'] = GC.SPD_OF_LGT
    substitutions['c_v'] = cv_value
    substitutions['gamma'] = gamma_value
    substitutions['sigma_s'] = sigma_s_value
    substitutions['sigma_a'] = sigma_a_value
    sigma_t_value = sigma_s_value + sigma_a_value
    substitutions['sigma_t'] = sigma_t_value

    # make substitutions
    Qrho_sub = Qrho.subs(substitutions)
    Qu_sub = Qu.subs(substitutions)
    QE_sub = QE.subs(substitutions)
    Qpsim_sub = Qpsim.subs(substitutions)
    Qpsip_sub = Qpsip.subs(substitutions)

    # create MMS source functions
    rho_f = lambdify((symbols('x'), symbols('t')), Qrho_sub, "numpy")
    u_f = lambdify((symbols('x'), symbols('t')), Qu_sub, "numpy")
    E_f = lambdify((symbols('x'), symbols('t')), QE_sub, "numpy")
    psim_f = lambdify((symbols('x'), symbols('t')), Qpsim_sub, "numpy")
    psip_f = lambdify((symbols('x'), symbols('t')), Qpsip_sub, "numpy")

    return (rho_f, u_f, E_f, psim_f, psip_f)
Esempio n. 53
0
def test_hypot():
    if not np:
        skip("NumPy not installed")
    assert abs(lambdify((a, b), hypot(a, b), 'numpy')(3, 4) - 5) < 1e-16
Esempio n. 54
0
    zmin, zmax = 0, 10
    x0 = 3
    start_fsolve = ymin
    posun_z = 0
    delkax = 2
    delkay = 2
    tecna_rovina_kreslit = False
    bez_znacek = False

fig = plt.figure()
ax = fig.gca(projection='3d')

# vypocet gradientu a tecne roviny
from sympy.abc import x, y
from sympy.utilities.lambdify import lambdify, implemented_function
gradfx = lambdify((x, y), f(x, y).diff(x))
gradfy = lambdify((x, y), f(x, y).diff(y))
if lambdifyf:
    f = lambdify((x, y), f(x, y), 'numpy')

# dopocitani bodu na vrstevnici
from scipy import *
from scipy import optimize
g = lambda y: f(x0, y)
try:
    y0 = optimize.fsolve(g, start_fsolve)[0]
except:
    print "nenalezeno y0"
    y0 = 0

Esempio n. 55
0
def test_log10():
    if not np:
        skip("NumPy not installed")
    assert abs(lambdify((a,), log10(a), 'numpy')(100) - 2) < 1e-16
def test_codegen_extra():
    if not tf:
        skip("TensorFlow not installed")

    graph = tf.Graph()
    with graph.as_default():
        session = tf.compat.v1.Session()

        M = MatrixSymbol("M", 2, 2)
        N = MatrixSymbol("N", 2, 2)
        P = MatrixSymbol("P", 2, 2)
        Q = MatrixSymbol("Q", 2, 2)
        ma = tf.constant([[1, 2], [3, 4]])
        mb = tf.constant([[1, -2], [-1, 3]])
        mc = tf.constant([[2, 0], [1, 2]])
        md = tf.constant([[1, -1], [4, 7]])

        cg = CodegenArrayTensorProduct(M, N)
        assert tensorflow_code(cg) == \
            'tensorflow.linalg.einsum("ab,cd", M, N)'
        f = lambdify((M, N), cg, 'tensorflow')
        y = session.run(f(ma, mb))
        c = session.run(tf.einsum("ij,kl", ma, mb))
        assert (y == c).all()

        cg = CodegenArrayElementwiseAdd(M, N)
        assert tensorflow_code(cg) == 'tensorflow.math.add(M, N)'
        f = lambdify((M, N), cg, 'tensorflow')
        y = session.run(f(ma, mb))
        c = session.run(ma + mb)
        assert (y == c).all()

        cg = CodegenArrayElementwiseAdd(M, N, P)
        assert tensorflow_code(cg) == \
            'tensorflow.math.add(tensorflow.math.add(M, N), P)'
        f = lambdify((M, N, P), cg, 'tensorflow')
        y = session.run(f(ma, mb, mc))
        c = session.run(ma + mb + mc)
        assert (y == c).all()

        cg = CodegenArrayElementwiseAdd(M, N, P, Q)
        assert tensorflow_code(cg) == \
            'tensorflow.math.add(' \
                'tensorflow.math.add(tensorflow.math.add(M, N), P), Q)'
        f = lambdify((M, N, P, Q), cg, 'tensorflow')
        y = session.run(f(ma, mb, mc, md))
        c = session.run(ma + mb + mc + md)
        assert (y == c).all()

        cg = CodegenArrayPermuteDims(M, [1, 0])
        assert tensorflow_code(cg) == 'tensorflow.transpose(M, [1, 0])'
        f = lambdify((M, ), cg, 'tensorflow')
        y = session.run(f(ma))
        c = session.run(tf.transpose(ma))
        assert (y == c).all()

        cg = CodegenArrayPermuteDims(CodegenArrayTensorProduct(M, N),
                                     [1, 2, 3, 0])
        assert tensorflow_code(cg) == \
            'tensorflow.transpose(' \
                'tensorflow.linalg.einsum("ab,cd", M, N), [1, 2, 3, 0])'
        f = lambdify((M, N), cg, 'tensorflow')
        y = session.run(f(ma, mb))
        c = session.run(tf.transpose(tf.einsum("ab,cd", ma, mb), [1, 2, 3, 0]))
        assert (y == c).all()

        cg = CodegenArrayDiagonal(CodegenArrayTensorProduct(M, N), (1, 2))
        assert tensorflow_code(cg) == \
            'tensorflow.linalg.einsum("ab,bc->acb", M, N)'
        f = lambdify((M, N), cg, 'tensorflow')
        y = session.run(f(ma, mb))
        c = session.run(tf.einsum("ab,bc->acb", ma, mb))
        assert (y == c).all()
Esempio n. 57
0
    def compileExpr(self,
                    inputSymb,
                    inputExpr,
                    backend=None,
                    compileType=False):
        '''
        Compiles the expression given the symbols.  Determines the backend
        if required.

        Parameters
        ----------
        inputSymb: list
            the set of symbols for the input expression
        inputExpr: expr
            expression in sympy
        backend: optional
            the backend we want to use to compile
        compileType: optional
            defaults to False.  If True, return an extra output that informs
            the end user of the method used to compile the equation, can be
            one of (np, mpmath, sympy)

        Returns
        -------
        Compiled function taking arguments of the input symbols
        '''
        if backend is None:
            backend = self._backend

        # unless specified, we are always going to use np and forget
        # about the floating point importance
        compiledFunc = None
        compileTypeChosen = None
        try:
            if backend == 'f2py':
                compiledFunc = autowrap(expr=inputExpr,
                                        args=inputSymb,
                                        backend='f2py')
                compileTypeChosen = 'np'
            elif backend == 'lambda':
                compiledFunc = lambdify(expr=inputExpr,
                                        args=inputSymb,
                                        modules='numpy')
                compileTypeChosen = 'np'
            elif backend.lower() in ('cython', 'np'):
                # note that we have another test layer because of the
                # bug previously mentioned in __init__ of this class
                try:
                    compiledFunc = autowrap(expr=inputExpr,
                                            args=inputSymb,
                                            backend='Cython')
                    compileTypeChosen = 'np'
                except:
                    # although we don't think it is possible given the checks
                    # previously performed, we should still try it
                    try:
                        compiledFunc = autowrap(expr=inputExpr,
                                                args=inputSymb,
                                                backend='f2py')
                        compileTypeChosen = 'np'
                    except:
                        compiledFunc = lambdify(expr=inputExpr,
                                                args=inputSymb,
                                                modules='numpy')
                        compileTypeChosen = 'np'
            else:
                raise ExpressionErrror("The problem is too tough")
        except:
            try:
                compiledFunc = lambdify(expr=inputExpr,
                                        args=inputSymb,
                                        modules='mpmath')
                compileTypeChosen = 'mpmath'
            except:
                compiledFunc = lambdify(expr=inputExpr,
                                        args=inputSymb,
                                        modules='sympy')
                compileTypeChosen = 'sympy'

        logging.debug('Compiled expression as {}'.format(compileTypeChosen))
        if compileType:
            return compiledFunc, compileTypeChosen
        else:
            return compiledFunc
Esempio n. 58
0
 def _basis_elem(l, m, x, y, z):
     calculation = SH._basis_elem_sympy(l, m)
     func = lambdify([SH.x, SH.y, SH.z], calculation)
     return func(x, y, z)
Esempio n. 59
0
def test_expm1():
    if not np:
        skip("NumPy not installed")

    f = lambdify((a,), expm1(a), 'numpy')
    assert abs(f(1e-10) - 1e-10 - 5e-21) < 1e-22
Esempio n. 60
0
def test_log1p():
    if not np:
        skip("NumPy not installed")

    f = lambdify((a,), log1p(a), 'numpy')
    assert abs(f(1e-99) - 1e-99) < 1e-100