def json_decoder(dct): if '__type__' in dct: t = dct['__type__'] if t == json_sym_matrix: return sp.Matrix(dct['data']) # nested_list_to_sym(dct['data']) elif t == json_sym_expr: try: return sp.sympify(dct['data'].encode('utf-8')) if isinstance( dct['data'], unicode) else sp.sympify(dct['data']) except NameError as e: raise Exception( 'NameError Occured while trying to sympify string {}. Error: {}\n{}' .format(repr(dct['data']), str(e), traceback.format_exc())) elif t[:8] == '<class \'' and t[-2:] == '\'>': t = t[8:-2] if t not in class_registry: class_registry[t] = import_class(t) t = class_registry[t] if not issubclass(t, JSONSerializable): raise Exception( 'Can not decode JSON object tagged with type "{}". The type is not a subtype of JSONSerializable' .format(t)) try: if hasattr(t, 'json_factory'): return t.json_factory( **{k: v for k, v in dct.items() if k != '__type__'}) return t(**{k: v for k, v in dct.items() if k != '__type__'}) except TypeError as e: raise TypeError( 'Error occurred while instantiating an object of type "{}":\n {}' .format(t.__name__, e)) return dct
def ParamPlot2D(self, funcs, rng, color='blue', legend="", thickness=1): """ Appends a parametric curve to the Graphics object. The parameters are as follows: - ``funcs``: the tupleof functions to be plotted, - ``rng``: a triple of the form `(t, a, b)`, where `t` is the `funcs`'s independents variable, over the range `[a, b]`, - ``color``: the color of the current curve, - ``legend``: the text for the legend of the current crve. """ if self.PlotType == '': self.PlotType = '2D' elif self.PlotType != '2D': raise Exception("Cannot combine 2d and 3d plots") if self.Env == 'numeric': f_0 = funcs[0] f_1 = funcs[1] elif self.Env == 'sympy': from sympy import lambdify f_0 = lambdify(rng[0], funcs[0], "numpy") f_1 = lambdify(rng[0], funcs[1], "numpy") elif self.Env == 'sage': from sage.all import fast_callable f_0 = fast_callable(funcs[0], vars=[rng[0]]) f_1 = fast_callable(funcs[1], vars=[rng[0]]) elif self.Env == 'symengine': from symengine import sympify from sympy import lambdify t_f0 = sympify(funcs[0]) t_f1 = sympify(funcs[1]) f_0 = lambdify((xrng[0], yrng[0]), t_f0, "numpy") f_1 = lambdify((xrng[0], yrng[0]), t_f1, "numpy") else: raise Exception( "The function type is not recognized. Only 'numeric', 'sympy' and 'sage' are accepted.") # if self.X == []: stp_lngt = float(rng[2] - rng[1]) / self.NumPoints line_points = [rng[1] + i * stp_lngt for i in range(self.NumPoints + 1)] TempX = [f_0(t) for t in line_points] self.X.append(TempX) if self.xmin is None: self.xmin = min(TempX) self.xmax = max(TempX) else: self.xmin = min(min(TempX), self.xmin) self.xmax = max(max(TempX), self.xmax) TempY = [f_1(t) for t in line_points] if self.ymin is None: self.ymin = min(TempY) self.ymax = max(TempY) else: self.ymin = min(min(TempY), self.ymin) self.ymax = max(max(TempY), self.ymax) self.Y.append(TempY) self.color.append(color) self.legend.append(legend) self.thickness.append(thickness) self.PlotCount += 1
def _build_constraint_functions(variables, constraints, include_hess=False, parameters=None, cse=True): if parameters is None: parameters = [] else: parameters = [wrap_symbol_symengine(p) for p in parameters] variables = tuple(variables) wrt = variables parameters = tuple(parameters) constraint__func, jacobian_func, hessian_func = None, None, None inp = sympify(variables + parameters) graph = sympify(constraints) constraint_func = lambdify(inp, [graph], backend='llvm', cse=cse) grad_graphs = list(list(c.diff(w) for w in wrt) for c in graph) jacobian_func = lambdify(inp, grad_graphs, backend='llvm', cse=cse) if include_hess: hess_graphs = list( list(list(g.diff(w) for w in wrt) for g in c) for c in grad_graphs) hessian_func = lambdify(inp, hess_graphs, backend='llvm', cse=cse) return ConstraintFunctions(cons_func=constraint_func, cons_jac=jacobian_func, cons_hess=hessian_func)
def test_conv1b(): x = sympy.Symbol("x") assert sympify(x) == Symbol("x") assert sympify(x) != Symbol("y") x = sympy.Symbol("y") assert sympify(x) != Symbol("x") assert sympify(x) == Symbol("y")
def test_sets(): x = Integer(2) y = Integer(3) x1 = sympy.Integer(2) y1 = sympy.Integer(3) assert Interval(x, y) == Interval(x1, y1) assert Interval(x1, y) == Interval(x1, y1) assert Interval(x, y)._sympy_() == sympy.Interval(x1, y1) assert sympify(sympy.Interval(x1, y1)) == Interval(x, y) assert sympify(sympy.EmptySet()) == EmptySet() assert sympy.EmptySet() == EmptySet()._sympy_() assert FiniteSet(x, y) == FiniteSet(x1, y1) assert FiniteSet(x1, y) == FiniteSet(x1, y1) assert FiniteSet(x, y)._sympy_() == sympy.FiniteSet(x1, y1) assert sympify(sympy.FiniteSet(x1, y1)) == FiniteSet(x, y) x = Interval(1, 2) y = Interval(2, 3) x1 = sympy.Interval(1, 2) y1 = sympy.Interval(2, 3) assert Union(x, y) == Union(x1, y1) assert Union(x1, y) == Union(x1, y1) assert Union(x, y)._sympy_() == sympy.Union(x1, y1) assert sympify(sympy.Union(x1, y1)) == Union(x, y) assert Complement(x, y) == Complement(x1, y1) assert Complement(x1, y) == Complement(x1, y1) assert Complement(x, y)._sympy_() == sympy.Complement(x1, y1) assert sympify(sympy.Complement(x1, y1)) == Complement(x, y)
def test_conv6b(): x = sympy.Symbol("x") y = sympy.Symbol("y") assert sympify(x / 3) == Symbol("x") / 3 assert sympify(3 * x) == 3 * Symbol("x") assert sympify(3 + x) == 3 + Symbol("x") assert sympify(3 - x) == 3 - Symbol("x") assert sympify(x / y) == Symbol("x") / Symbol("y")
def test_conv2b(): x = sympy.Symbol("x") y = sympy.Symbol("y") z = sympy.Symbol("z") e = x * y assert sympify(e) == Symbol("x") * Symbol("y") e = x * y * z assert sympify(e) == Symbol("x") * Symbol("y") * Symbol("z")
def test_conv9b(): x = Symbol("x") y = Symbol("y") assert sympify(sympy.I) == I assert sympify(2*sympy.I+3) == 2*I+3 assert sympify(2*sympy.I/5+sympy.S(3)/5) == 2*I/5+Integer(3)/5 assert sympify(sympy.Symbol("x")*sympy.I + 3) == x*I+3 assert sympify(sympy.Symbol("x") + sympy.I*sympy.Symbol("y")) == x+I*y
def test_conv6b(): x = sympy.Symbol("x") y = sympy.Symbol("y") assert sympify(x/3) == Symbol("x") / 3 assert sympify(3*x) == 3*Symbol("x") assert sympify(3+x) == 3+Symbol("x") assert sympify(3-x) == 3-Symbol("x") assert sympify(x/y) == Symbol("x") / Symbol("y")
def test_conv4b(): x = sympy.Symbol("x") y = sympy.Symbol("y") z = sympy.Symbol("z") e = x**y assert sympify(e) == Symbol("x")**Symbol("y") e = (x + y)**z assert sympify(e) == (Symbol("x") + Symbol("y"))**Symbol("z")
def test_conv3b(): x = sympy.Symbol("x") y = sympy.Symbol("y") z = sympy.Symbol("z") e = x + y assert sympify(e) == Symbol("x") + Symbol("y") e = x + y + z assert sympify(e) == Symbol("x") + Symbol("y") + Symbol("z")
def test_conv2b(): x = sympy.Symbol("x") y = sympy.Symbol("y") z = sympy.Symbol("z") e = x*y assert sympify(e) == Symbol("x")*Symbol("y") e = x*y*z assert sympify(e) == Symbol("x")*Symbol("y")*Symbol("z")
def test_conv3b(): x = sympy.Symbol("x") y = sympy.Symbol("y") z = sympy.Symbol("z") e = x+y assert sympify(e) == Symbol("x")+Symbol("y") e = x+y+z assert sympify(e) == Symbol("x")+Symbol("y")+Symbol("z")
def test_conv4b(): x = sympy.Symbol("x") y = sympy.Symbol("y") z = sympy.Symbol("z") e = x**y assert sympify(e) == Symbol("x")**Symbol("y") e = (x+y)**z assert sympify(e) == (Symbol("x")+Symbol("y"))**Symbol("z")
def build_constraint_functions(variables, constraints, parameters=None, func_options=None, jac_options=None, hess_options=None): """Build callables functions for the constraints, constraint Jacobian, and constraint Hessian. Parameters ---------- variables : List[sympy.core.symbol.Symbol] Free variables in the sympy_graph. By convention these are usually all instances of StateVariables. constraints : List[sympy.core.expr.Expr] List of SymPy expression to compile parameters : Optional[List[sympy.core.symbol.Symbol]] Free variables in the sympy_graph. These are typically external parameters that are controlled by the user. func_options : None, optional Options to pass to ``lambdify`` when compiling the function. jac_options : Optional[Dict[str, str]] Options to pass to ``lambdify`` when compiling the Jacobian. hess_options : Optional[Dict[str, str]] Options to pass to ``lambdify`` when compiling Hessian. Returns ------- ConstraintFunctions Notes ----- Default options for compiling the function, gradient and Hessian are defined by ``_get_lambdify_options``. """ if parameters is None: parameters = [] else: parameters = [wrap_symbol_symengine(p) for p in parameters] variables = tuple(variables) wrt = variables parameters = tuple(parameters) constraint_func, jacobian_func, hessian_func = None, None, None inp = sympify(variables + parameters) graph = sympify(constraints) constraint_func = lambdify(inp, [graph], **_get_lambidfy_options(func_options)) grad_graphs = list(list(c.diff(w) for w in wrt) for c in graph) jacobian_func = lambdify(inp, grad_graphs, **_get_lambidfy_options(jac_options)) hess_graphs = list( list(list(g.diff(w) for w in wrt) for g in c) for c in grad_graphs) hessian_func = lambdify(inp, hess_graphs, **_get_lambidfy_options(hess_options)) return ConstraintFunctions(cons_func=constraint_func, cons_jac=jacobian_func, cons_hess=hessian_func)
def __setstate__(self, state): if state["type"] == "symengine": self._symbol_expr = symengine.sympify(state["expr"]) self._parameter_symbols = {k: symengine.sympify(v) for k, v in state["symbols"].items()} self._parameters = set(self._parameter_symbols) else: self._symbol_expr = state["expr"] self._parameter_symbols = state["symbols"] self._parameters = set(self._parameter_symbols) self._names = state["names"]
def test_zeta(): x = Symbol("x") y = Symbol("y") e1 = sympy.zeta(sympy.Symbol("x")) e2 = zeta(x) assert sympify(e1) == e2 assert e2._sympy_() == e1 e1 = sympy.zeta(sympy.Symbol("x"), sympy.Symbol("y")) e2 = zeta(x, y) assert sympify(e1) == e2 assert e2._sympy_() == e1
def __init__(self, expr: Union[str, int, "Polynomial"] = 0) -> None: """Construct a polynomial.""" if isinstance(expr, str): p = symengine.sympify(expr.lstrip("+")) # symengine/symengine.py#331 self._raw = symengine.expand(p) elif isinstance(expr, int): self._raw = symengine.sympify(expr) elif isinstance(expr, Polynomial): self._raw = expr._raw else: raise ValueError(f"unexpected expr: {expr}")
def test_exp(): x = Symbol("x") e1 = sympy.exp(sympy.Symbol("x")) e2 = exp(x) assert sympify(e1) == e2 assert e1 == e2._sympy_() e1 = sympy.exp(sympy.Symbol("x")).diff(sympy.Symbol("x")) e2 = exp(x).diff(x) assert sympify(e1) == e2 assert e1 == e2._sympy_()
def build_constraint_functions(variables, constraints, parameters=None, func_options=None, jac_options=None, hess_options=None): """Build callables functions for the constraints, constraint Jacobian, and constraint Hessian. Parameters ---------- variables : List[symengine.Symbol] Free variables in the symengine_graph. By convention these are usually all instances of StateVariables. constraints : List[symengine.Basic] List of SymEngine expression to compile parameters : Optional[List[symengine.Symbol]] Free variables in the symengine_graph. These are typically external parameters that are controlled by the user. func_options : None, optional Options to pass to ``lambdify`` when compiling the function. jac_options : Optional[Dict[str, str]] Options to pass to ``lambdify`` when compiling the Jacobian. hess_options : Optional[Dict[str, str]] Options to pass to ``lambdify`` when compiling Hessian. Returns ------- ConstraintFunctions Notes ----- Default options for compiling the function, gradient and Hessian are defined by ``_get_lambdify_options``. """ if parameters is None: parameters = [] else: parameters = [wrap_symbol(p) for p in parameters] variables = tuple(variables) wrt = variables parameters = tuple(parameters) constraint_func, jacobian_func, hessian_func = None, None, None # Replace complex infinity (zoo) with real infinity because SymEngine # cannot lambdify complex infinity. We also replace in the derivatives in # case some differentiation would produce a complex infinity. The # replacement is assumed to be cheap enough that it's safer to replace the # complex values and pay the minor time penalty. inp = sympify(variables + parameters) graph = sympify([f.xreplace({zoo: oo}) for f in constraints]) constraint_func = lambdify(inp, [graph], **_get_lambidfy_options(func_options)) grad_graphs = list(list(c.diff(w).xreplace({zoo: oo}) for w in wrt) for c in graph) jacobian_func = lambdify(inp, grad_graphs, **_get_lambidfy_options(jac_options)) hess_graphs = list(list(list(g.diff(w).xreplace({zoo: oo}) for w in wrt) for g in c) for c in grad_graphs) hessian_func = lambdify(inp, hess_graphs, **_get_lambidfy_options(hess_options)) return ConstraintFunctions(cons_func=constraint_func, cons_jac=jacobian_func, cons_hess=hessian_func)
def test_sympify1(): assert sympify(1) == Integer(1) assert sympify(2) != Integer(1) assert sympify(-5) == Integer(-5) assert sympify(Integer(3)) == Integer(3) assert sympify(('0', '0')) == (0, 0) assert sympify(['0', '0']) == [0, 0] assert sympify("3+5") == Integer(8) assert true == sympify(True) assert false == sympify(False)
def test_conv10b(): A = sympy.Matrix([[sympy.Symbol("x"), sympy.Symbol("y")], [sympy.Symbol("z"), sympy.Symbol("t")]]) assert sympify(A) == densematrix(2, 2, [Symbol("x"), Symbol("y"), Symbol("z"), Symbol("t")]) B = sympy.Matrix([[1, 2], [3, 4]]) assert sympify(B) == densematrix(2, 2, [Integer(1), Integer(2), Integer(3), Integer(4)]) C = sympy.Matrix([[7, sympy.Symbol("y")], [sympy.Function("g")(sympy.Symbol("z")), 3 + 2*sympy.I]]) assert sympify(C) == densematrix(2, 2, [Integer(7), Symbol("y"), function_symbol("g", Symbol("z")), 3 + 2*I])
def test_log(): x = Symbol("x") x1 = sympy.Symbol("x") assert log(x) == log(x1) assert log(x)._sympy_() == sympy.log(x1) assert sympify(sympy.log(x1)) == log(x) y = Symbol("y") y1 = sympy.Symbol("y") assert log(x, y) == log(x, y1) assert log(x1, y) == log(x1, y1) assert log(x, y)._sympy_() == sympy.log(x1, y1) assert sympify(sympy.log(x1, y1)) == log(x, y)
def test_conv11(): x = sympy.Symbol("x") y = sympy.Symbol("y") x1 = Symbol("x") y1 = Symbol("y") e1 = sympy.Subs(sympy.Derivative(sympy.Function("f")(x, y), x), [x, y], [y, y]) e2 = Subs(Derivative(function_symbol("f", x1, y1), [x1]), [x1, y1], [y1, y1]) e3 = Subs(Derivative(function_symbol("f", x1, y1), [x1]), [y1, x1], [x1, y1]) assert sympify(e1) == e2 assert sympify(e1) != e3 assert e2._sympy_() == e1 assert e3._sympy_() != e1
def evaluate_expression(model, expression): """Evaluate expression using model Calculate the value of expression for each data record. The expression can contain dataset columns, variables in model and population parameters. If the model has parameter estimates these will be used. Initial estimates will be used for non-estimated parameters. Parameters ---------- expression : str or sympy expression Expression to evaluate Returns ------- pd.Series A series of one evaluated value for each data record """ expression = sympy.sympify(expression) full_expr = model.statements.full_expression_from_odes(expression) pe = model.modelfit_results.parameter_estimates inits = model.parameters.inits expr = full_expr.subs(dict(pe)).subs(inits) data = model.dataset expr = symengine.sympify(expr) def func(row): subs = expr.subs(dict(row)) return np.float64(subs.evalf()) df = data.apply(func, axis=1) return df
def solve_angle(is_OOP, fkt, start_paras, Bounds, angle, B): # Minimize Angles Theta, Phi, ThetaB # start_paras for the moment these are constant: [m.pi/2, m.pi, m.pi/2] # start_paras = [m.pi/2, m.pi, m.pi/2] # --------------------------------------Finding Global Minimum (Mathematica approach)--------------------------------------------- # Extremly slow, slower than using a global solver in minimize function '''MIN = [] RESULT = [] for a in np.arange(-1,1,m.pi/8): for b in np.arange(-1,1,m.pi/8): for c in np.arange(-1,1,m.pi/8): start_Paras = [a,b,c] result = minimize(F_fkt, start_Paras, args=(B,phiB,fkt) ,method = 'L-BFGS-B', bounds=Bounds) MIN.append([result.fun,result.x[0],result.x[1],result.x[2]]) MIN = np.asarray(MIN) for index,value in enumerate(MIN[:,0]): if value == min(MIN[:,0]): print(index, "Found!") print(MIN[index]) #RESULT.append([MIN[:,1],MIN[:,2],MIN[:,3]]) print(RESULT,'Global Minimum')''' # After evaluating some minima: Global Minimum search was everytime equivalent to local minima search (sometimes modulo 2*PI). This equivalence must not be true in every case!!! # ---------------------------------------------------------------------------------------------------------------------------------- args = (B, angle, sympify(fkt), is_OOP) result = basinhopping(F_fkt, start_paras,T=1, stepsize=m.pi / 8, niter=10, minimizer_kwargs={'args': args, 'bounds': Bounds}) # Global minimiser searching around starting point for 10 steps with stepwidth pi/8 return result.x[0], result.x[1], result.x[2]
def normal(cls, name, level, mean, variance): """Create a normally distributed random variable Parameters ---------- name : str Name of the random variable level : str Name of the variability level mean : expression or number Mean of the random variable variance : expression or number Variance of the random variable Example ------- >>> from pharmpy import RandomVariable, Parameter >>> omega = Parameter('OMEGA_CL', 0.1) >>> rv = RandomVariable.normal("IIV_CL", "IIV", 0, omega.symbol) >>> rv IIV_CL ~ 𝒩 (0, OMEGA_CL) """ rv = cls(name, level) rv._mean = sympy.Matrix([sympy.sympify(mean)]) rv._variance = sympy.Matrix([sympy.sympify(variance)]) if rv._variance.is_positive_semidefinite is False: raise ValueError(f"Mean cannot be {mean} must be positive") rv._symengine_variance = symengine.sympify(rv._variance) return rv
def _read_parameter_expression(file_obj): param_expr_raw = struct.unpack(PARAMETER_EXPR_PACK, file_obj.read(PARAMETER_EXPR_SIZE)) map_elements = param_expr_raw[0] from sympy.parsing.sympy_parser import parse_expr if HAS_SYMENGINE: expr = symengine.sympify( parse_expr(file_obj.read(param_expr_raw[1]).decode("utf8"))) else: expr = parse_expr(file_obj.read(param_expr_raw[1]).decode("utf8")) symbol_map = {} for _ in range(map_elements): elem_raw = file_obj.read(PARAM_EXPR_MAP_ELEM_SIZE) elem = struct.unpack(PARAM_EXPR_MAP_ELEM_PACK, elem_raw) param = _read_parameter(file_obj) elem_type = elem[0].decode("utf8") elem_data = file_obj.read(elem[1]) if elem_type == "f": value = struct.unpack("!d", elem_data) elif elem_type == "i": value = struct.unpack("!q", elem_data) elif elem_type == "c": value = complex(*struct.unpack(COMPLEX_PACK, elem_data)) elif elem_type == "p": value = param._symbol_expr elif elem_type == "e": value = _read_parameter_expression(io.BytesIO(elem_data)) else: raise TypeError("Invalid parameter expression map type: %s" % elem_type) symbol_map[param] = value return ParameterExpression(symbol_map, expr)
def test_kronecker_delta(): x = Symbol("x") y = Symbol("y") e1 = sympy.KroneckerDelta(sympy.Symbol("x"), sympy.Symbol("y")) e2 = KroneckerDelta(x, y) assert sympify(e1) == e2 assert e2._sympy_() == e1
def test_beta(): x = Symbol("x") y = Symbol("y") e1 = sympy.beta(sympy.Symbol("y"), sympy.Symbol("x")) e2 = beta(y, x) assert sympify(e1) == e2 assert e2._sympy_() == e1
def test_conv10b(): A = sympy.Matrix([[sympy.Symbol("x"), sympy.Symbol("y")], [sympy.Symbol("z"), sympy.Symbol("t")]]) assert sympify(A) == DenseMatrix(2, 2, [Symbol("x"), Symbol("y"), Symbol("z"), Symbol("t")]) B = sympy.Matrix([[1, 2], [3, 4]]) assert sympify(B) == DenseMatrix(2, 2, [Integer(1), Integer(2), Integer(3), Integer(4)]) C = sympy.Matrix([[7, sympy.Symbol("y")], [sympy.Function("g")(sympy.Symbol("z")), 3 + 2*sympy.I]]) assert sympify(C) == DenseMatrix(2, 2, [Integer(7), Symbol("y"), function_symbol("g", Symbol("z")), 3 + 2*I])
def test_polygamma(): x = Symbol("x") y = Symbol("y") e1 = sympy.polygamma(sympy.Symbol("x"), sympy.Symbol("y")) e2 = polygamma(x, y) assert sympify(e1) == e2 assert e2._sympy_() == e1
def test_levi_civita(): x = Symbol("x") y = Symbol("y") z = Symbol("z") e1 = sympy.LeviCivita(sympy.Symbol("x"), sympy.Symbol("y"), sympy.Symbol("z")) e2 = LeviCivita(x, y, z) assert sympify(e1) == e2 assert e2._sympy_() == e1
def test_conv11(): x = sympy.Symbol("x") y = sympy.Symbol("y") x1 = Symbol("x") y1 = Symbol("y") f = sympy.Function("f") f1 = Function("f") e1 = diff(f(2 * x, y), x) e2 = diff(f1(2 * x1, y1), x1) e3 = diff(f1(2 * x1, y1), y1) assert sympify(e1) == e2 assert sympify(e1) != e3 assert e2._sympy_() == e1 assert e3._sympy_() != e1
def test_abs(): x = Symbol("x") e1 = abs(sympy.Symbol("x")) e2 = abs(x) assert sympify(e1) == e2 assert e1 == e2._sympy_() e1 = abs(2 * sympy.Symbol("x")) e2 = 2 * abs(x) assert sympify(e1) == e2 assert e1 == e2._sympy_() y = Symbol("y") e1 = abs(sympy.Symbol("y") * sympy.Symbol("x")) e2 = abs(y * x) assert sympify(e1) == e2 assert e1 == e2._sympy_()
def test_abs(): x = Symbol("x") e1 = abs(sympy.Symbol("x")) e2 = abs(x) assert sympify(e1) == e2 assert e1 == e2._sympy_() e1 = abs(2*sympy.Symbol("x")) e2 = 2*abs(x) assert sympify(e1) == e2 assert e1 == e2._sympy_() y = Symbol("y") e1 = abs(sympy.Symbol("y")*sympy.Symbol("x")) e2 = abs(y*x) assert sympify(e1) == e2 assert e1 == e2._sympy_()
def conditional(trigger,threshold,untriggered_value,triggered_value,sharpness=None): if sharpness is None: if sympify(threshold).is_number and threshold: sharpness = SHARPN_COEFF*abs(threshold) else: sharpness = SHARPN_COEFF return untriggered_value + sigmoid((trigger-threshold)*sharpness)*(triggered_value-untriggered_value)
def _dumps_symbolic_expr(expr): from sympy import srepr, sympify if expr is None: return b"" expr_bytes = srepr(sympify(expr)).encode(common.ENCODE) return zlib.compress(expr_bytes)
def _build_constraint_functions(variables, constraints, include_hess=False, parameters=None, cse=True): if parameters is None: parameters = [] else: parameters = [wrap_symbol_symengine(p) for p in parameters] variables = tuple(variables) wrt = variables parameters = tuple(parameters) constraint__func, jacobian_func, hessian_func = None, None, None inp = sympify(variables + parameters) graph = sympify(constraints) constraint_func = lambdify(inp, [graph], backend='llvm', cse=cse) grad_graphs = list(list(c.diff(w) for w in wrt) for c in graph) jacobian_func = lambdify(inp, grad_graphs, backend='llvm', cse=cse) if include_hess: hess_graphs = list(list(list(g.diff(w) for w in wrt) for g in c) for c in grad_graphs) hessian_func = lambdify(inp, hess_graphs, backend='llvm', cse=cse) return ConstraintFunctions(cons_func=constraint_func, cons_jac=jacobian_func, cons_hess=hessian_func)
def wrap_symbol_symengine(obj): from symengine import Symbol, sympify from sympy import Symbol as Symbol_sympy if isinstance(obj, Symbol): return obj elif isinstance(obj, Symbol_sympy): return sympify(obj) else: return Symbol(obj)
def test_conv12b(): x = sympy.Symbol("x") y = sympy.Symbol("y") assert sympify(sympy.sinh(x/3)) == sinh(Symbol("x") / 3) assert sympify(sympy.cosh(x/3)) == cosh(Symbol("x") / 3) assert sympify(sympy.tanh(x/3)) == tanh(Symbol("x") / 3) assert sympify(sympy.coth(x/3)) == coth(Symbol("x") / 3) assert sympify(sympy.asinh(x/3)) == asinh(Symbol("x") / 3) assert sympify(sympy.acosh(x/3)) == acosh(Symbol("x") / 3) assert sympify(sympy.atanh(x/3)) == atanh(Symbol("x") / 3) assert sympify(sympy.acoth(x/3)) == acoth(Symbol("x") / 3)
def test_tuples_lists(): x = sympy.Symbol("x") y = sympy.Symbol("y") z = sympy.Symbol("z") l = [x, y, z, x*y, z**y] t = (x, y, z, x*y, z**y) x = Symbol("x") y = Symbol("y") z = Symbol("z") l2 = [x, y, z, x*y, z**y] t2 = (x, y, z, x*y, z**y) assert sympify(l) == l2 assert sympify(t) == t2 assert sympify(l) != t2 assert sympify(t) != l2 assert l == l2 assert t == t2 assert l != t2 assert t != l2
def build_functions(sympy_graph, variables, parameters=None, wrt=None, include_obj=True, include_grad=False, include_hess=False, cse=True): if wrt is None: wrt = sympify(tuple(variables)) if parameters is None: parameters = [] else: parameters = [wrap_symbol_symengine(p) for p in parameters] variables = tuple(variables) parameters = tuple(parameters) func, grad, hess = None, None, None inp = sympify(variables + parameters) graph = sympify(sympy_graph) # TODO: did not replace zoo with oo if include_obj: func = lambdify(inp, [graph], backend='llvm', cse=cse) if include_grad or include_hess: grad_graphs = list(graph.diff(w) for w in wrt) if include_grad: grad = lambdify(inp, grad_graphs, backend='llvm', cse=cse) if include_hess: hess_graphs = list(list(g.diff(w) for w in wrt) for g in grad_graphs) hess = lambdify(inp, hess_graphs, backend='llvm', cse=cse) return BuildFunctionsResult(func=func, grad=grad, hess=hess)
def Plot2D(self, func, xrng, color='blue', legend="", thickness=1): """ Appends a curve to the Graphics object. The parameters are as follows: - `func`: the function to be plotted, - `xrng`: a triple of the form `(x, a, b)`, where `x` is the `func`'s independents variable, over the range `[a, b]`, - `color`: the color of the current curve, - `legend`: the text for the legend of the current crve. """ if self.PlotType == '': self.PlotType = '2D' elif self.PlotType != '2D': raise Exception("Cannot combine 2d and 3d plots") if self.Env == 'numeric': f_ = func elif self.Env == 'sympy': from sympy import lambdify f_ = lambdify(xrng[0], func, "numpy") elif self.Env == 'sage': from sage.all import fast_callable f_ = fast_callable(func, vars=[xrng[0]]) elif self.Env == 'symengine': from symengine import sympify from sympy import lambdify t_func = sympify(func) f_ = lambdify(xrng[0], t_func, "numpy") else: raise Exception( "The function type is not recognized. Only 'numeric', 'sympy' and 'sage' are accepted.") # if self.X == []: stp_lngt = float(xrng[2] - xrng[1]) / self.NumPoints self.X.append( [xrng[1] + i * stp_lngt for i in range(self.NumPoints + 1)]) self.xmin = xrng[1] self.xmax = xrng[2] TempY = [f_(x) for x in self.X[-1]] if self.ymin is None: self.ymin = min(TempY) self.ymax = max(TempY) else: self.ymin = min(min(TempY), self.ymin) self.ymax = max(max(TempY), self.ymax) self.Y.append(TempY) self.color.append(color) self.legend.append(legend) self.thickness.append(thickness) self.PlotCount += 1
def Plot3D(self, func, xrng, yrng): """ Sets a surface to the Graphics object. The parameters are as follows: - ``func``: the function to be plotted, - ``xrng``: a triple of the form `(x, a, b)`, where `x` is the first `func`s independents variable, over the range `[a, b]`, - ``yrng``: a triple of the form `(y, c, d)`, where `x` is the second `func`'s independents variable, over the range `[c, d]`. """ import numpy as np if self.PlotType == '': self.PlotType = '3D' elif self.PlotType != '3D': raise Exception("Cannot combine 2d and 3d plots") if self.Env == 'numeric': f_ = func elif self.Env == 'sympy': from sympy import lambdify f_ = lambdify((xrng[0], yrng[0]), func, "numpy") elif self.Env == 'sage': from sage.all import fast_callable f_ = fast_callable(func, vars=[xrng[0], yrng[0]]) elif self.Env == 'symengine': from symengine import sympify from sympy import lambdify t_func = sympify(func) f_ = lambdify((xrng[0], yrng[0]), t_func, "numpy") else: raise Exception( "The function type is not recognized. Only 'numeric', 'sympy' and 'sage' are accepted.") # self.f_ = f_ x_stp_lngt = float(xrng[2] - xrng[1]) / self.NumPoints y_stp_lngt = float(yrng[2] - yrng[1]) / self.NumPoints if self.X == []: self.X = [xrng[1] + i * x_stp_lngt for i in range(self.NumPoints + 1)] self.xmin = xrng[1] self.xmax = xrng[2] self.Y = [yrng[1] + i * y_stp_lngt for i in range(self.NumPoints + 1)] self.ymin = yrng[1] self.ymax = yrng[2] X = np.array(self.X) Y = np.array(self.Y) self.X, self.Y = np.meshgrid(X, Y) self.Z = f_(self.X, self.Y) self.intX, self.intY = np.mgrid[xrng[1]:xrng[ 2]:x_stp_lngt, yrng[1]:yrng[2]:y_stp_lngt] self.intZ = f_(self.intX, self.intY)
def test_conv8b(): e1 = sympy.Function("f")(sympy.Symbol("x")) e2 = sympy.Function("g")(sympy.Symbol("x"), sympy.Symbol("y")) assert sympify(e1) == function_symbol("f", Symbol("x")) assert sympify(e2) != function_symbol("f", Symbol("x")) assert sympify(e2) == function_symbol("g", Symbol("x"), Symbol("y")) e3 = sympy.Function("q")(sympy.Symbol("t")) assert sympify(e3) == function_symbol("q", Symbol("t")) assert sympify(e3) != function_symbol("f", Symbol("t")) assert sympify(e3) != function_symbol("q", Symbol("t"), Symbol("t"))
def test_pynumber(): a = sympy.FF(7)(3) b = sympify(a) assert isinstance(b, PyNumber) a = a + 1 b = b + 1 assert isinstance(b, PyNumber) assert b == a # Check equality via SymEngine assert a == b # Check equality via SymPy a = 1 - a b = 1 - b assert isinstance(b, PyNumber) assert b == a # Check equality via SymEngine assert a == b # Check equality via SymPy a = 2 * a b = 2 * b assert isinstance(b, PyNumber) assert b == a # Check equality via SymEngine assert a == b # Check equality via SymPy a = 2 / a b = 2 / b assert isinstance(b, PyNumber) assert b == a # Check equality via SymEngine assert a == b # Check equality via SymPy x = Symbol("x") b = x * sympy.FF(7)(3) assert isinstance(b, Mul) b = b / x assert isinstance(b, PyNumber)
def generate_f_C(self, simplify=None, do_cse=False, chunk_size=100): """ translates the derivative to C code using SymEngine’s `C-code printer <https://github.com/symengine/symengine/pull/1054>`_. Parameters ---------- simplify : boolean or None Whether the derivative should be `simplified <http://docs.sympy.org/dev/modules/simplify/simplify.html>`_ (with `ratio=1.0`) before translating to C code. The main reason why you could want to enable this is if you expect your derivative not to be optimised and not be so large that simplifying takes a considerable amount of time. If `None`, this will be automatically disabled for `n>10`. do_cse : boolean Whether SymPy’s `common-subexpression detection <http://docs.sympy.org/dev/modules/rewriting.html#module-sympy.simplify.cse_main>`_ should be applied before translating to C code. It is almost always better to let the compiler do this (unless you want to set the compiler optimisation to `-O2` or lower): For simple differential equations this should not make any difference to the compiler’s optimisations. For large ones, it may make a difference but also take long. As this requires all entries of `f` at once, it may void advantages gained from using generator functions as an input. Also, this feature uses SymPy and not SymEngine. chunk_size : integer If the number of instructions in the final C code exceeds this number, it will be split into chunks of this size. See `Handling very large differential equations <http://jitcde-common.readthedocs.io/#handling-very-large-differential-equations>`_ on why this is useful and how to best choose this value. If smaller than 1, no chunking will happen. """ self._generate_helpers_C() # working copy f_sym_wc = (entry.subs(self.general_subs) for entry in self.f_sym()) if simplify is None: simplify = self.n<=10 if simplify: f_sym_wc = (entry.simplify(ratio=1) for entry in f_sym_wc) arguments = self._default_arguments() if self.helpers: arguments.append(("general_helper","double const *__restrict const")) if do_cse: import sympy get_helper = sympy.Function("get_f_helper") set_helper = symengine.Function("set_f_helper") _cse = sympy.cse( sympy.Matrix(sympy.sympify(list(f_sym_wc))), symbols = (get_helper(i) for i in count()) ) more_helpers = symengine.sympify(_cse[0]) f_sym_wc = symengine.sympify(_cse[1][0]) if more_helpers: arguments.append(("f_helper","double *__restrict const")) self.render_and_write_code( (set_helper(i,helper[1]) for i,helper in enumerate(more_helpers)), name = "f_helpers", chunk_size = chunk_size, arguments = arguments, omp = False, ) self._number_of_f_helpers = len(more_helpers) set_dy = symengine.Function("set_dy") self.render_and_write_code( (set_dy(i,entry) for i,entry in enumerate(f_sym_wc)), name = "f", chunk_size = chunk_size, arguments = arguments+[("dY", "PyArrayObject *__restrict const")] ) self._f_C_source = True
def test_mpc(): if have_mpc: a = ComplexMPC('1', '2', 100) b = sympy.Float(1, 29) + sympy.Float(2, 29) * sympy.I assert sympify(b) == a assert b == a._sympy_()
def test_mpfr(): if have_mpfr: a = RealMPFR('100', 100) b = sympy.Float('100', 29) assert sympify(b) == a assert b == a._sympy_()
def test_constants(): assert sympify(sympy.E) == E assert sympy.E == E._sympy_() assert sympify(sympy.pi) == pi assert sympy.pi == pi._sympy_()
def test_gamma(): x = Symbol("x") e1 = sympy.gamma(sympy.Symbol("x")) e2 = gamma(x) assert sympify(e1) == e2 assert e1 == e2._sympy_()
def test_conv5b(): x = sympy.Integer(5) y = sympy.Integer(6) assert sympify(x) == Integer(5) assert sympify(x/y) == Integer(5) / Integer(6)
def PlugPoints(self): """ Internal use: plug in collocation points to elliminate independent variables and keep the coefficients. """ # Plug in the collocation points to form the algebraic equations numeric_eqs = [] for p in self.Points: chg = {self.Vars[i]: p[i] for i in range(self.num_vars)} for eq in self.REq: tp1 = type(eq) Teq = eq.subs(chg) tp2 = type(Teq) if (tp1 == tp2) and (Teq not in numeric_eqs): numeric_eqs.append(Teq) if len(numeric_eqs) >= len(self.SymCF): break if len(numeric_eqs) >= len(self.SymCF): break if len(numeric_eqs) != len(self.SymCF): raise Exception( "Number of points and equations are not equal! Check the conditions.") if self.Verbose: print "Solving the system of equations numerically to extract coefficients ..." # Solve the algebraic equations if self.Solver == 'sage': if self.Env != 'sage': raise Exception( "Sage solver is not available in selected symbolic environment.") sols = solve(numeric_eqs, self.SymCF, solution_dict=True) sols = sols[0] return sols elif self.Solver in ['scipy']: from scipy import optimize as opt from random import uniform if self.Env == 'sympy': from sympy import lambdify f_ = [lambdify(self.SymCF, (eq.lhs - eq.rhs), "numpy") for eq in numeric_eqs] def f(x): z = tuple(float(x.item(i)) for i in range(len(self.SymCF))) return [fn(*z) for fn in f_] elif self.Env == 'symengine': from symengine import sympify from sympy import lambdify t_eqs = [sympify(eq) for eq in numeric_eqs] f_ = [lambdify(self.SymCF, eq, "numpy") for eq in t_eqs] def f(x): z = tuple(float(x.item(i)) for i in range(len(self.SymCF))) return [fn(*z) for fn in f_] elif self.Env == 'sage': def f(x): chng = {} U = self.SymCF n_var = len(U) chng = {U[i]: float(x.item(i)) for i in range(n_var)} EQs_ = [] for eq in numeric_eqs: teq = eq.lhs() - eq.rhs() EQs_.append(teq.subs(chng).n()) return EQs_ nvars = len(self.SymCF) if self.Solver == 'scipy': if self.InitPoint != []: init_point = tuple(self.InitPoint) else: init_point = tuple( uniform(-self.init_guess_bnd, self.init_guess_bnd) for _ in range(nvars)) sol = opt.root(f, init_point, method=self.SolverOption) if sol.success: sols = {self.SymCF[i]: list(sol.x)[i] for i in range(nvars)} self.Success = True else: sols = {} self.Success = False if self.Verbose: print sol.message return sols
def test_conv7b(): x = sympy.Symbol("x") y = sympy.Symbol("y") assert sympify(sympy.sin(x/3)) == sin(Symbol("x") / 3) assert sympify(sympy.sin(x/3)) != cos(Symbol("x") / 3) assert sympify(sympy.cos(x/3)) == cos(Symbol("x") / 3)
def generate_jac_C(self, do_cse=False, chunk_size=100, sparse=True): """ translates the symbolic Jacobian to C code using SymEngine’s `C-code printer <https://github.com/symengine/symengine/pull/1054>`_. If the symbolic Jacobian has not been generated, it generates it by calling `generate_jac_sym`. Parameters ---------- do_cse : boolean Whether SymPy’s `common-subexpression detection <http://docs.sympy.org/dev/modules/rewriting.html#module-sympy.simplify.cse_main>`_ should be applied before translating to C code. It is almost always better to let the compiler do this (unless you want to set the compiler optimisation to `-O2` or lower): For simple differential equations this should not make any difference to the compiler’s optimisations. For large ones, it may make a difference but also take long. As this requires the entire Jacobian at once, it may void advantages gained from using generator functions as an input. Also, this feature uses SymPy and not SymEngine. chunk_size : integer If the number of instructions in the final C code exceeds this number, it will be split into chunks of this size. See `Handling very large differential equations <http://jitcde-common.readthedocs.io/#handling-very-large-differential-equations>`_ on why this is useful and how to best choose this value. If smaller than 1, no chunking will happen. sparse : boolean Whether a sparse Jacobian should be assumed for optimisation. Note that this does not mean that the Jacobian is stored, parsed or handled as a sparse matrix. This kind of optimisation would require `ode` or `solve_ivp` to be able to handle sparse matrices without structure in the sparseness. """ self._generate_helpers_C() # working copy jac_sym_wc = ( (entry.subs(self.general_subs) for entry in line) for line in self.jac_sym ) self.sparse_jac = sparse arguments = self._default_arguments() if self.helpers: arguments.append(("general_helper","double const *__restrict const")) if do_cse: import sympy get_helper = sympy.Function("get_jac_helper") set_helper = symengine.Function("set_jac_helper") jac_sym_wc = sympy.Matrix([ [ sympy.sympify(entry) for entry in line ] for line in jac_sym_wc ]) _cse = sympy.cse( sympy.sympify(jac_sym_wc), symbols = (get_helper(i) for i in count()) ) more_helpers = symengine.sympify(_cse[0]) jac_sym_wc = symengine.sympify(_cse[1][0].tolist()) if more_helpers: arguments.append(("jac_helper","double *__restrict const")) self.render_and_write_code( (set_helper(i, helper[1]) for i,helper in enumerate(more_helpers)), name = "jac_helpers", chunk_size = chunk_size, arguments = arguments, omp = False ) self._number_of_jac_helpers = len(more_helpers) set_dfdy = symengine.Function("set_dfdy") self.render_and_write_code( ( set_dfdy(i,j,entry) for i,line in enumerate(jac_sym_wc) for j,entry in enumerate(line) if ( (entry != 0) or not self.sparse_jac ) ), name = "jac", chunk_size = chunk_size, arguments = arguments+[("dfdY", "PyArrayObject *__restrict const")] ) self._jac_C_source = True