def test_using(): v = Type('std::vector') u1 = using(v) assert cxxcode(u1) == 'using std::vector' u2 = using(v, 'vec') assert cxxcode(u2) == 'using vec = std::vector'
def test_using(): v = Type("std::vector") u1 = using(v) assert cxxcode(u1) == "using std::vector" u2 = using(v, "vec") assert cxxcode(u2) == "using vec = std::vector"
def get_formulas(self, isprint=0): if isprint: for i in range(0, self.nc): print(f'kappa_{i+1} = {cxxcode(self.kappax[i])} \n') kappaxcc = {} for i in range(0, self.nc): kappaxcc[i] = cxxcode(self.kappax[i]) return kappaxcc
def c_gradient(self, pattern="dvdq[{}] = {};"): """ @returns Gradient in very particlar C format """ lines = [ pattern.format(i, cxxcode(g)) for i, g in enumerate(self._sympy_gradient) ] joined = "\n".join(lines) return self.names_to_array(joined)
def make_jac_function(self, m): func_declaration = 'void Models::jac_#IDX#(const ublas_vec_t & y , ublas_mat_t &J , const double &/* t*/ , ublas_vec_t &dfdt, std::vector <double> &part_params)' func_declaration = func_declaration.replace('#IDX#', str(m.idx)) cpp_out = func_declaration + '\n{\n' # Unpack parameters cpp_out += '\t//Unpack parameters\n' param_template = '\tconst double #P# = part_params[#IDX#];\n' for idx, param in enumerate(m.params_list): cpp_out += param_template.replace('#P#', param).replace('#IDX#', str(idx)) cpp_out += '\n' i, j = np.shape(m.jac) jac_template = '\tJ( #IDX_I# , #IDX_J# ) = #EQ#;\n' for idx_i in range(i): for idx_j in range(j): sympy_jac_eq = cxxcode(sympy.sympify(m.jac[idx_i, idx_j])) jac_str = jac_template.replace('#EQ#', sympy_jac_eq).replace('#IDX_I#', str(idx_i)).replace('#IDX_J#', str(idx_j)) # Replace species with vector indexes for idx_z, species in enumerate(m.species_list): vec_index = 'y[' + str(idx_z) + ']' # jac_str = jac_str.replace(species, vec_index) pat = '\\b(?:[^*A-Z\d\D]|(' + species + '))\\b' # Pattern essential to replace only species, not ends of parameters jac_str = re.sub(pat, vec_index, jac_str, flags=re.I) cpp_out += jac_str cpp_out += '\n' for idx in range(i): cpp_out += '\tdfdt[' + str(idx) + '] = 0.0;\n' cpp_out += '\n}\n' return cpp_out
def make_model_function(self, m): func_declaration = 'void Models::model_#IDX#(const ublas_vec_t &y , ublas_vec_t &dydt , double t, std::vector <double> &part_params)' func_declaration = func_declaration.replace('#IDX#', str(m.idx)) cpp_out = func_declaration + '\n{\n' # Unpack parameters cpp_out += '\t//Unpack parameters\n' param_template = '\tconst double #P# = part_params[#IDX#];\n' for idx, param in enumerate(m.params_list): cpp_out += param_template.replace('#P#', param).replace('#IDX#', str(idx)) cpp_out += '\n' # Make comment of species order cpp_out += '\t//Species order is: ' for species in m.species_list: cpp_out += species + ' ' cpp_out += '\n' # Unpack differential equations diff_eq_template = '\tdydt[#IDX#] = #EQ#;\n' for idx, eq in enumerate(m.diff_eqs): sympy_cpp_eq = cxxcode(sympy.sympify(m.diff_eqs[eq])) cpp_eq_str = diff_eq_template.replace('#EQ#', sympy_cpp_eq).replace('#IDX#', str(idx)) # Replace species with vector indexes for idx_z, species in enumerate(m.species_list): vec_index = 'y[' + str(idx_z) + ']' # cpp_eq_str = cpp_eq_str.replace(species, vec_index) pat = '\\b(?:[^*A-Z\d\D]|('+species+'))\\b' # Pattern essential to replace only species, not ends of parameters cpp_eq_str = re.sub(pat, vec_index, cpp_eq_str, flags=re.I) cpp_out += cpp_eq_str cpp_out += '\n}\n' return cpp_out
def test_cxxcode(): assert sorted(cxxcode(sqrt(x) * 0.5).split("*")) == sorted(["0.5", "std::sqrt(x)"])
def jacobian(difvar, diffun, loop): dvl = [x.strip() for x in difvar.split(',')] #print (diffun) new_diffun = [] for fun in diffun: fun = fun.replace('pow', 'Pow') new_diffun.append(fun) diffun = new_diffun dfl = diffun varlen = len(dvl) funlen = len(dfl) mat_y = [[y] for y in dvl] mat_x = [[x] for x in dfl] Y = Matrix(mat_y) X = Matrix(mat_x) jac = X.jacobian(Y) Ljac = jac.tolist() print(Ljac) deleterow = [] deletecol = [] for i in range(varlen): deleteflag = 1 for j in range(varlen): if Ljac[i][j] != 0: deleteflag = 0 if deleteflag == 1: deleterow.append(i) for j in range(varlen): deleteflag = 1 for i in range(varlen): if Ljac[i][j] != 0: deleteflag = 0 if deleteflag == 1: deletecol.append(j) delete_element = [] if len(deletecol) != 0 and len(deleterow) != 0: delete_element = list(set(deletecol).intersection(deleterow)) dvl = JacobianCalc.deletevar(dvl, delete_element) for i in range(len(delete_element)): JacobianCalc.mark(Ljac, delete_element[i], varlen) Ljac = JacobianCalc.removeDelete(Ljac) #print(Ljac) funlen -= len(delete_element) varlen -= len(delete_element) for i in range(funlen): for j in range(varlen): Ljac[i][j] = "Entry" + "=" + cxxcode(Ljac[i][j], standard='C++11') naturestirng = "" naturestirng += str(len(dvl)) naturestirng += '\n' for i in range(len(dvl)): naturestirng += dvl[i] naturestirng += '\n' #nodelist =[] naturestirng += str(funlen * varlen) naturestirng += '\n' for i in range(funlen): for j in range(varlen): naturestirng += Ljac[i][j] naturestirng += '\n' filename = JacobianCalc.current_file_path filename += "/../work-dir/jacobiannature" filename += str(loop + 1) filename += ".txt" savefile = open(filename, 'w') savefile.write(naturestirng) savefile.close() ComputeLDFstring = "" if loop == 0: # ComputeLDFstring += "from math import *\n" # ComputeLDFstring += "import numpy as np\n" # ComputeLDFstring += "import numpy.linalg as la\n" # #ComputeLDFstring += "import matplotlib.pyplot as plt\n" # ComputeLDFstring += "import sys\n" # ComputeLDFstring += "import time\n" # ComputeLDFstring += "from sympy import Derivative\n" # ComputeLDFstring += "def jcalc(listvalue,curstate):\n" # ComputeLDFstring += " ret = []\n" ComputeLDFstring += "#include <vector>\n" ComputeLDFstring += "#include <cmath>\n" # ComputeLDFstring += "using namespace std;\n" ComputeLDFstring += 'extern "C" std::vector<double> jcalc(std::vector<double> listvalue, int curstate)\n' ComputeLDFstring += "{\n" ComputeLDFstring += " std::vector<double> ret;\n" ComputeLDFstring += " if (curstate == " + str(loop + 1) + ")\n" ComputeLDFstring += " {\n" for i in range(len(dvl)): tempstring = " double " + dvl[i] + "= listvalue[" + str( i) + "];\n" ComputeLDFstring += tempstring ComputeLDFstring += " double Entry = 0;\n" for i in range(funlen): for j in range(varlen): tempstring = " " + Ljac[i][j] + ";\n" ComputeLDFstring += tempstring ComputeLDFstring += " ret.push_back(Entry);\n" ComputeLDFstring += " return ret;\n" ComputeLDFstring += " }\n" filename = JacobianCalc.current_file_path filename += "/../work-dir/jaThin.cpp" if loop == 0: savefile = open(filename, 'w') savefile.write(ComputeLDFstring) else: savefile = open(filename, "a") savefile.write(ComputeLDFstring) savefile.close() return delete_element
def test_cxxcode(): assert sorted(cxxcode(sqrt(x) * .5).split('*')) == sorted( ['0.5', 'std::sqrt(x)'])
# # + {"slideshow": {"slide_type": "fragment"}} x = symbols('x') expr = abs(sin(x**2)) expr # + {"slideshow": {"slide_type": "fragment"}} sym.ccode(expr) # + {"slideshow": {"slide_type": "fragment"}} sym.fcode(expr, standard=2003, source_format='free') # + {"slideshow": {"slide_type": "fragment"}} from sympy.printing.cxxcode import cxxcode cxxcode(expr) # + {"slideshow": {"slide_type": "slide"}} sym.tanh(x).rewrite(sym.exp) # + {"slideshow": {"slide_type": "fragment"}} from sympy import sqrt, exp, pi expr = 1/sqrt(2*pi*sigma**2)* exp(-(x-mu)**2/(2*sigma**2)) print(sym.fcode(expr, standard=2003, source_format='free')) # + [markdown] {"slideshow": {"slide_type": "slide"}} # ## Creating a function from a symbolic expression # In SymPy there is a function to create a Python function which evaluates (usually numerically) an expression. SymPy allows the user to define the signature of this function (which is convenient when working with e.g. a numerical solver in ``scipy``). # + {"slideshow": {"slide_type": "fragment"}} from sympy import log
template<> inline void _calculate_b<{0:d},{1:d}>(double* X_0, double* b_H, double* b_ImH, double* b_dH) {{ """.format(nSpace, order)) if nSpace == 3: f.write(""" const double x_0(X_0[0]), y_0(X_0[1]), z_0(X_0[2]); """) if nSpace == 2: f.write(""" const double x_0(X_0[0]), y_0(X_0[1]); """) if nSpace == 1: f.write(""" const double x_0(X_0[0]); """) for i in range(len(b_H)): f.write(" b_H[{0:d}] = {1:s};\n".format(i, cxxcode(b_H[i]))) f.write(" b_ImH[{0:d}] = {1:s};\n".format(i, cxxcode(b_1mH[i]))) f.write(" b_dH[{0:d}] = {1:s};\n".format( i * nSpace, cxxcode(b_dH_x[i]))) if nSpace > 1: f.write(" b_dH[{0:d}] = {1:s};\n".format( i * nSpace + 1, cxxcode(b_dH_y[i]))) if nSpace > 2: f.write(" b_dH[{0:d}] = {1:s};\n".format( i * nSpace + 2, cxxcode(b_dH_z[i]))) f.write(""" } """) f.write("""}//equivalent_polynomials #endif """)
foo_max_3 = -abs(foo_xxx) foo_max_3 = lambdify(x, foo_max_3, 'scipy') foo_max_3 = scipy.optimize.fminbound(foo_max_3, foo_a, foo_b) foo_max_4 = -abs(foo_xxxx) foo_max_4 = lambdify(x, foo_max_4, 'scipy') foo_max_4 = scipy.optimize.fminbound(foo_max_4, foo_a, foo_b) bar_x = f_bar.diff(x) bar_y = f_bar.diff(y) bar_xx = f_bar.diff(x, x) bar_yy = f_bar.diff(y, y) bar_xy = f_bar.diff(x, y) foo = cxxcode(f_foo, standard='C++11') foo_x = cxxcode(foo_x, standard='C++11') foo_xx = cxxcode(foo_xx, standard='C++11') foo_xxx = cxxcode(foo_xxx, standard='C++11') foo_xxxx = cxxcode(foo_xxxx, standard='C++11') bar = cxxcode(f_bar, standard='C++11') bar_x = cxxcode(bar_x, standard='C++11') bar_y = cxxcode(bar_y, standard='C++11') bar_xx = cxxcode(bar_xx, standard='C++11') bar_yy = cxxcode(bar_yy, standard='C++11') bar_xy = cxxcode(bar_xy, standard='C++11') dict_names = { "foo_a": foo_a, "foo_b": foo_b,
def c_potential(self): """ @returns Potential in C format """ return self.names_to_array(cxxcode(self.ginac_potential))
c = symbols('c') r_12 = Function('r_12')(x,y) r_23 = Function('r_23')(x,y) r_31 = Function('r_31')(x,y) r_12 = sqrt((x[0]-x[1])**2 + (y[0]-y[1])**2) r_23 = sqrt((x[1]-x[2])**2 + (y[1]-y[2])**2) r_31 = sqrt((x[2]-x[0])**2 + (y[2]-y[0])**2) V = Function('V')(r_12,r_23,r_31) V = (add function to) init_printing() #Printing partial derivatives #print(simplify(diff(V, x[0]))) for i in range(3): #print((diff(V, x[i]))) #print((diff(V, y[i]))) print(cxxcode(diff(V, x[i]))) print(cxxcode(diff(V, y[i]))) #print(latex((diff(V, x[i])))) #print(latex((diff(V, y[i]))))
frag.diff(theta32,simplify=use_simplify)*(theta32_expr.diff(phi3,simplify=False) + theta32_expr.diff(phi2,simplify=False)) for order in range(1, maxOrder): nDOF1D = order + 1 print("Order ", order) f.write(""" template<> inline void _calculate_b<{0:d}>(double theta01, double theta02, double theta31, double theta32, double phi0, double phi1, double phi2, double phi3, double* b_H, double* b_ImH, double* b_D) {{ """.format(order)) n = 0 for i in range(nDOF1D): for j in range(nDOF1D - i): for k in range(nDOF1D - i - j): f.write(" b_H[{0:d}] = {1:s};\n".format( n, cxxcode(b_H[(i, j, k)]))) f.write(" b_ImH[{0:d}] = {1:s};\n".format( n, cxxcode(b_1mH[(i, j, k)]))) f.write(" b_D[{0:d}] = {1:s};\n".format( n, cxxcode(b_D[(i, j, k)]))) n += 1 f.write(""" } """) f.write("""}//equivalent_polynomials #endif """) f.close()
def print_in_cpp(expr, standard='c++11'): return cxxcode(expr, standard=standard)
def test_cxxcode(): assert sorted(cxxcode(sqrt(x)*.5).split('*')) == sorted(['0.5', 'std::sqrt(x)'])