本文整理汇总了Python中sympy.printing.ccode函数的典型用法代码示例。如果您正苦于以下问题:Python ccode函数的具体用法?Python ccode怎么用?Python ccode使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ccode函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: genEval
def genEval(self):
text = " bool evaluate(\n"
args=[]
for name,v in self.variables:
if v.is_Matrix:
args.append(" const Eigen::MatrixXd & %s" % name)
else:
args.append(" double %s" % name)
args.append(" bool evalF=true,bool evalJ=true")
text += ",\n".join(args) + ") {\n"
text += " if (evalF) {\n"
(interm, expr) = cse(self.function,numbered_symbols("__x"));
for dummy,exp in interm:
text += " double %s = %s;\n" % (str(dummy),ccode(exp))
for i in range(self.function.rows):
text += " F(%d) = %s;\n" % (i,ccode(expr[0][i]))
text += " }\n"
text += " if (evalJ) {\n"
(interm, expr) = cse(self.J,numbered_symbols("__x"));
for dummy,exp in interm:
text += " double %s = %s;\n" % (str(dummy),ccode(exp))
for i in range(self.J.rows):
for j in range(self.J.cols):
text += " J(%d,%d) = %s;\n" % (i,j,ccode(expr[0][i,j]))
text += " }\n"
text += " return true;\n"
text += " }\n"
return text
示例2: __init__
def __init__(self, symbsol, V, kappa=1):
x, y, t = smp.symbols('x[0], x[1], t')
rhs = symbsol.diff(t) \
+ (kappa * (symbsol.diff(x))).diff(x) \
+ (kappa * (symbsol.diff(y))).diff(y)
from sympy.printing import ccode
self.sol = Expression(ccode(symbsol), t=0.0)
self.rhs = Expression(ccode(rhs), t=0.0)
self.V = V
v = TestFunction(V)
u = TrialFunction(V)
# Assemble system
M = assemble(inner(u, v)*dx)
A = assemble(kappa * inner(grad(u), grad(v)) * dx)
# Convert DOLFIN representation to numpy arrays
rows, cols, values = M.data()
self.M = sps.csr_matrix((values, cols, rows))
"""csr matrix for the mass"""
rows, cols, values = A.data()
self.A = sps.csr_matrix((values, cols, rows))
"""csr matrix representing the weak discrete
:math:`-\\nabla \\cdot (\\kappa \\nabla )` operator"""
# treatment of the boundary values
nv = self.A.shape[0]
auxu = np.zeros((nv,1))
self.bcinds = []
self.bc = DirichletBC(self.V, self.sol, 'on_boundary')
self.bcdict = self.bc.get_boundary_values()
auxu[self.bcdict.keys(),0] = self.bcdict.values()
self.bcinds.extend(self.bcdict.keys())
self.rhsbc = - self.A*auxu
# indices of the innernodes
self.invinds = np.setdiff1d(range(nv),self.bcinds).astype(np.int32)
# condense the coeff mats to the inner nodes
self.M = self.M[self.invinds,:][:,self.invinds]
self.A = self.A[self.invinds,:][:,self.invinds]
self.rhsbc = self.rhsbc[self.invinds,:]
self.bcvals = auxu[self.bcinds]
示例3: rhs_xml
def rhs_xml(self):
rhs = self.expand_integer_powers(self.rhs)
s = ccode(rhs, user_functions=self._random_map)
s = self.strip_L_from_rationals(s)
s = self._ccode_print_warn_re.sub('', s)
s = self._multiple_whitespace_re.sub(' ', s)
return s
示例4: assign_str
def assign_str(self, lhs, rhs):
rhs = Expression.expand_integer_powers(rhs)
nmodl_str = ccode(rhs, user_functions=Expression._cfunc_map,
assign_to=lhs)
nmodl_str = Expression.strip_L_from_rationals(nmodl_str)
nmodl_str = nmodl_str.replace(';', '')
return nmodl_str
示例5: extraToFile
def extraToFile(self, path):
raw = """double %sOrbitals::get_dell_alpha_phi(const Walker* walker, int qnum, int i){
double dphi;
__code__
return dphi;
}""" % self.name
shell = """if (qnum == _q_) {
__necessities__
//__simple__
dphi = __expr__
} else """
Z = Symbol('Z', positive=True, real=True)
code = " "
for i in range(self.maxImplemented/2):
psi = self.orbitals[i]
qNums = self.stateMap[i]
genFac = self.genericFactor(qNums, basic=False)
kdiff = diff(psi, k).factor(genFac)/psi*Z
simple = self.makeReadable(str(kdiff))
nec, necList = self.getNecessities(kdiff)
expr = printing.ccode(kdiff) + ";"
expr = self.replaceCCode(expr, necList)
#hack to get the right indent
nec = "\n".join([" "*4 + nec_i for nec_i in nec.split("\n")])
subCode = shell
subCode = subCode.replace("\n\n __necessities__", nec)\
.replace("__expr__", expr)\
.replace("__simple__", simple)\
.replace("_q_", str(i))
code += subCode
code = code.strip("else ")
ccode = raw.replace("__code__", code)
with open(pjoin(path, "%sOrbitalsAlphaDeriv.cpp" % self.name), 'w') as f:
f.write(ccode)
f.close()
示例6: getNecessities
def getNecessities(self, expr):
s = printing.ccode(expr)
nec = []
necS = ""
necS2 = ""
for i, x in enumerate(self.xi):
l = len(regxp.findall("pow\(%s\, \d+\)" % x, s))
if regxp.findall("[^\w]?%s[^\w]" % x, s):
nec.append(x)
necS += " %s = walker->r(i, %d);\n" % (x, i)
if l > 0:
x2 = x + "2"
nec.append(x2)
necS2 += " %s = %s*%s;\n" % (x2, x, x)
necS = ("%s\n%s" % (necS, necS2)).strip("\n")
#Manually add the lineshifts so that if no nec, then no lineshift
if necS:
necS = "\n\n" + necS
return necS, nec
示例7: renderModelMethodImplementation
def renderModelMethodImplementation(self):
if self.expression is not None:
implementation = ccode(self.expression)
else:
implementation = "ASSERT(False)"
return render('model_methodImplementation.cc', dict(evalClassName=self.d['evalClassName'],
myMethod=self.d['myKeyMethod'],
myMethodDeclarationArgs=self.d['myMethodDeclarationArgs'],
myMethodImplementation=implementation))
示例8: test_ccode_boolean
def test_ccode_boolean():
assert ccode(x&y) == "x&&y"
assert ccode(x|y) == "x||y"
assert ccode(~x) == "!x"
assert ccode(x&y&z) == "x&&y&&z"
assert ccode(x|y|z) == "x||y||z"
assert ccode((x&y)|z) == "x&&y||z"
assert ccode((x|y)&z) == "(x||y)&&z"
示例9: GenCode
def GenCode(exp):
# From http://docs.sympy.org/dev/modules/utilities/codegen.html
[(c_name, c_code), (h_name, c_header)] = codegen(
("exp", exp), "C", "test", header=False, empty=False)
print("c_code = %s" % c_code)
print("ccode = %s" % ccode(exp))
#!!!! TODO TODO TODO: we should check if we have symbolic denominator and generate code that takes care to check if the denominator is 0 and if so to abort the compuatation
return None
示例10: _str_scal_func_update
def _str_scal_func_update(method, name, objlabel):
expr = getattr(method, name + '_expr')
update_h = '\nvoid {0}_update();'.format(name)
update_cpp = '\nvoid {0}::{1}_update()'.format(objlabel, name) + '{'
symbs = expr.free_symbols
if any(symb in method.args for symb in symbs):
c = ccode(expr, dereference=dereference(method))
update_cpp += '\n_{0} = {1};'.format(name, c)
update_cpp += '\n};'
return update_h, update_cpp
示例11: _str_scal_func_init_data
def _str_scal_func_init_data(method, name):
expr = getattr(method, name + '_expr')
init_data = '{1} {0}_data = '.format(name, CONFIG_CPP['float'])
symbs = expr.free_symbols
if any(symb in method.args for symb in symbs):
init_data += "0.;"
else:
c = ccode(expr, dereference=dereference(method))
init_data += '{};'.format(c)
return init_data
示例12: _str_mat_func_update
def _str_mat_func_update(method, name, objlabel):
mat = types.matrix_types[0](getattr(method, name + '_expr'))
update_h = '\nvoid {0}_update();'.format(name)
update_cpp = '\nvoid {0}::{1}_update()'.format(objlabel, name) + '{'
for m, n, expr in mat.row_list():
symbs = expr.free_symbols
if any(symb in method.args() for symb in symbs):
c = ccode(expr, dereference=dereference(method))
update_cpp += '\n_{0}({1}, {2}) = {3};'.format(name, m, n, c)
update_cpp += '\n};'
return update_h, update_cpp
示例13: test_ccode_Piecewise
def test_ccode_Piecewise():
p = ccode(Piecewise((x,x<1),(x**2,True)))
s = \
"""\
if (x < 1) {
x
}
else {
pow(x,2)
}\
"""
assert p == s
示例14: _call_printer
def _call_printer(self, routine):
code_lines = []
# Compose a list of symbols to be dereferenced in the function
# body. These are the arguments that were passed by a reference
# pointer, excluding arrays.
dereference = []
for arg in routine.arguments:
if isinstance(arg, ResultBase) and not arg.dimensions:
dereference.append(arg.name)
return_val = None
for result in routine.result_variables:
if isinstance(result, Result):
assign_to = routine.name + "_result"
t = result.get_datatype('c')
code_lines.append("{0} {1};\n".format(t, str(assign_to)))
return_val = assign_to
else:
assign_to = result.result_var
try:
# order='none' is an optimization not in upstream
constants, not_c, c_expr = ccode(result.expr, human=False,
assign_to=assign_to, dereference=dereference, order='none')
except AssignmentError:
assign_to = result.result_var
code_lines.append(
"%s %s;\n" % (result.get_datatype('c'), str(assign_to)))
constants, not_c, c_expr = ccode(result.expr, human=False,
assign_to=assign_to, dereference=dereference, order='none')
for name, value in sorted(constants, key=str):
code_lines.append("double const %s = %s;\n" % (name, value))
code_lines.append("%s\n" % c_expr)
if return_val:
code_lines.append(" return %s;\n" % return_val)
return code_lines
示例15: genEval
def genEval(self):
text = " bool evaluate(\n"
args=[]
for name,v,lD in self.variables:
if isinstance(v, Matrix):
args.append(" const Eigen::Matrix<double, %d, 1> & %s" % (v.rows, name))
else:
args.append(" double %s" % name)
args.append(" Eigen::Matrix<double, %d, 1> * F" % self.function.rows)
for name,v,localDim in self.variables:
if isinstance(v, Matrix):
args.append(" Eigen::Matrix<double, %d, %d> * J%s" % (self.J.rows, localDim, name))
else:
args.append(" Eigen::Matrix<double, %d, 1> * J%s" % (self.J.rows, name))
text += ",\n".join(args) + ") {\n"
text += " if (F) {\n"
(interm, expr) = cse(self.function,numbered_symbols("__x"));
for dummy,exp in interm:
text += " double %s = %s;\n" % (str(dummy),ccode(exp))
for i in range(self.function.rows):
text += " (*F)(%d) = %s;\n" % (i,ccode(expr[0][i]))
text += " }\n"
text += " if (%s) {\n" % " && ".join([ "J" + name for name,v,lD in self.variables ])
(interm, expr) = cse(self.J,numbered_symbols("__x"));
for dummy,exp in interm:
text += " double %s = %s;\n" % (str(dummy),ccode(exp))
colBase = 0;
for name,v,localDim in self.variables:
for i in range(self.J.rows):
for j in range(0, localDim):
text += " (*J%s)(%d,%d) = %s;\n" % (name, i,j,ccode(expr[0][i,colBase + j]))
colBase+=localDim
text += " }\n"
text += " return true;\n"
text += " }\n"
return text