Coverage for /usr/lib/python3/dist-packages/sympy/printing/jscode.py: 27%

124 statements  

« prev     ^ index     » next       coverage.py v7.9.1, created at 2025-06-14 15:55 +0200

1""" 

2Javascript code printer 

3 

4The JavascriptCodePrinter converts single SymPy expressions into single 

5Javascript expressions, using the functions defined in the Javascript 

6Math object where possible. 

7 

8""" 

9 

10from __future__ import annotations 

11from typing import Any 

12 

13from sympy.core import S 

14from sympy.core.numbers import equal_valued 

15from sympy.printing.codeprinter import CodePrinter 

16from sympy.printing.precedence import precedence, PRECEDENCE 

17 

18 

19# dictionary mapping SymPy function to (argument_conditions, Javascript_function). 

20# Used in JavascriptCodePrinter._print_Function(self) 

21known_functions = { 

22 'Abs': 'Math.abs', 

23 'acos': 'Math.acos', 

24 'acosh': 'Math.acosh', 

25 'asin': 'Math.asin', 

26 'asinh': 'Math.asinh', 

27 'atan': 'Math.atan', 

28 'atan2': 'Math.atan2', 

29 'atanh': 'Math.atanh', 

30 'ceiling': 'Math.ceil', 

31 'cos': 'Math.cos', 

32 'cosh': 'Math.cosh', 

33 'exp': 'Math.exp', 

34 'floor': 'Math.floor', 

35 'log': 'Math.log', 

36 'Max': 'Math.max', 

37 'Min': 'Math.min', 

38 'sign': 'Math.sign', 

39 'sin': 'Math.sin', 

40 'sinh': 'Math.sinh', 

41 'tan': 'Math.tan', 

42 'tanh': 'Math.tanh', 

43} 

44 

45 

46class JavascriptCodePrinter(CodePrinter): 

47 """"A Printer to convert Python expressions to strings of JavaScript code 

48 """ 

49 printmethod = '_javascript' 

50 language = 'JavaScript' 

51 

52 _default_settings: dict[str, Any] = { 

53 'order': None, 

54 'full_prec': 'auto', 

55 'precision': 17, 

56 'user_functions': {}, 

57 'human': True, 

58 'allow_unknown_functions': False, 

59 'contract': True, 

60 } 

61 

62 def __init__(self, settings={}): 

63 CodePrinter.__init__(self, settings) 

64 self.known_functions = dict(known_functions) 

65 userfuncs = settings.get('user_functions', {}) 

66 self.known_functions.update(userfuncs) 

67 

68 def _rate_index_position(self, p): 

69 return p*5 

70 

71 def _get_statement(self, codestring): 

72 return "%s;" % codestring 

73 

74 def _get_comment(self, text): 

75 return "// {}".format(text) 

76 

77 def _declare_number_const(self, name, value): 

78 return "var {} = {};".format(name, value.evalf(self._settings['precision'])) 

79 

80 def _format_code(self, lines): 

81 return self.indent_code(lines) 

82 

83 def _traverse_matrix_indices(self, mat): 

84 rows, cols = mat.shape 

85 return ((i, j) for i in range(rows) for j in range(cols)) 

86 

87 def _get_loop_opening_ending(self, indices): 

88 open_lines = [] 

89 close_lines = [] 

90 loopstart = "for (var %(varble)s=%(start)s; %(varble)s<%(end)s; %(varble)s++){" 

91 for i in indices: 

92 # Javascript arrays start at 0 and end at dimension-1 

93 open_lines.append(loopstart % { 

94 'varble': self._print(i.label), 

95 'start': self._print(i.lower), 

96 'end': self._print(i.upper + 1)}) 

97 close_lines.append("}") 

98 return open_lines, close_lines 

99 

100 def _print_Pow(self, expr): 

101 PREC = precedence(expr) 

102 if equal_valued(expr.exp, -1): 

103 return '1/%s' % (self.parenthesize(expr.base, PREC)) 

104 elif equal_valued(expr.exp, 0.5): 

105 return 'Math.sqrt(%s)' % self._print(expr.base) 

106 elif expr.exp == S.One/3: 

107 return 'Math.cbrt(%s)' % self._print(expr.base) 

108 else: 

109 return 'Math.pow(%s, %s)' % (self._print(expr.base), 

110 self._print(expr.exp)) 

111 

112 def _print_Rational(self, expr): 

113 p, q = int(expr.p), int(expr.q) 

114 return '%d/%d' % (p, q) 

115 

116 def _print_Mod(self, expr): 

117 num, den = expr.args 

118 PREC = precedence(expr) 

119 snum, sden = [self.parenthesize(arg, PREC) for arg in expr.args] 

120 # % is remainder (same sign as numerator), not modulo (same sign as 

121 # denominator), in js. Hence, % only works as modulo if both numbers 

122 # have the same sign 

123 if (num.is_nonnegative and den.is_nonnegative or 

124 num.is_nonpositive and den.is_nonpositive): 

125 return f"{snum} % {sden}" 

126 return f"(({snum} % {sden}) + {sden}) % {sden}" 

127 

128 def _print_Relational(self, expr): 

129 lhs_code = self._print(expr.lhs) 

130 rhs_code = self._print(expr.rhs) 

131 op = expr.rel_op 

132 return "{} {} {}".format(lhs_code, op, rhs_code) 

133 

134 def _print_Indexed(self, expr): 

135 # calculate index for 1d array 

136 dims = expr.shape 

137 elem = S.Zero 

138 offset = S.One 

139 for i in reversed(range(expr.rank)): 

140 elem += expr.indices[i]*offset 

141 offset *= dims[i] 

142 return "%s[%s]" % (self._print(expr.base.label), self._print(elem)) 

143 

144 def _print_Idx(self, expr): 

145 return self._print(expr.label) 

146 

147 def _print_Exp1(self, expr): 

148 return "Math.E" 

149 

150 def _print_Pi(self, expr): 

151 return 'Math.PI' 

152 

153 def _print_Infinity(self, expr): 

154 return 'Number.POSITIVE_INFINITY' 

155 

156 def _print_NegativeInfinity(self, expr): 

157 return 'Number.NEGATIVE_INFINITY' 

158 

159 def _print_Piecewise(self, expr): 

160 from sympy.codegen.ast import Assignment 

161 if expr.args[-1].cond != True: 

162 # We need the last conditional to be a True, otherwise the resulting 

163 # function may not return a result. 

164 raise ValueError("All Piecewise expressions must contain an " 

165 "(expr, True) statement to be used as a default " 

166 "condition. Without one, the generated " 

167 "expression may not evaluate to anything under " 

168 "some condition.") 

169 lines = [] 

170 if expr.has(Assignment): 

171 for i, (e, c) in enumerate(expr.args): 

172 if i == 0: 

173 lines.append("if (%s) {" % self._print(c)) 

174 elif i == len(expr.args) - 1 and c == True: 

175 lines.append("else {") 

176 else: 

177 lines.append("else if (%s) {" % self._print(c)) 

178 code0 = self._print(e) 

179 lines.append(code0) 

180 lines.append("}") 

181 return "\n".join(lines) 

182 else: 

183 # The piecewise was used in an expression, need to do inline 

184 # operators. This has the downside that inline operators will 

185 # not work for statements that span multiple lines (Matrix or 

186 # Indexed expressions). 

187 ecpairs = ["((%s) ? (\n%s\n)\n" % (self._print(c), self._print(e)) 

188 for e, c in expr.args[:-1]] 

189 last_line = ": (\n%s\n)" % self._print(expr.args[-1].expr) 

190 return ": ".join(ecpairs) + last_line + " ".join([")"*len(ecpairs)]) 

191 

192 def _print_MatrixElement(self, expr): 

193 return "{}[{}]".format(self.parenthesize(expr.parent, 

194 PRECEDENCE["Atom"], strict=True), 

195 expr.j + expr.i*expr.parent.shape[1]) 

196 

197 def indent_code(self, code): 

198 """Accepts a string of code or a list of code lines""" 

199 

200 if isinstance(code, str): 

201 code_lines = self.indent_code(code.splitlines(True)) 

202 return ''.join(code_lines) 

203 

204 tab = " " 

205 inc_token = ('{', '(', '{\n', '(\n') 

206 dec_token = ('}', ')') 

207 

208 code = [ line.lstrip(' \t') for line in code ] 

209 

210 increase = [ int(any(map(line.endswith, inc_token))) for line in code ] 

211 decrease = [ int(any(map(line.startswith, dec_token))) 

212 for line in code ] 

213 

214 pretty = [] 

215 level = 0 

216 for n, line in enumerate(code): 

217 if line in ('', '\n'): 

218 pretty.append(line) 

219 continue 

220 level -= decrease[n] 

221 pretty.append("%s%s" % (tab*level, line)) 

222 level += increase[n] 

223 return pretty 

224 

225 

226def jscode(expr, assign_to=None, **settings): 

227 """Converts an expr to a string of javascript code 

228 

229 Parameters 

230 ========== 

231 

232 expr : Expr 

233 A SymPy expression to be converted. 

234 assign_to : optional 

235 When given, the argument is used as the name of the variable to which 

236 the expression is assigned. Can be a string, ``Symbol``, 

237 ``MatrixSymbol``, or ``Indexed`` type. This is helpful in case of 

238 line-wrapping, or for expressions that generate multi-line statements. 

239 precision : integer, optional 

240 The precision for numbers such as pi [default=15]. 

241 user_functions : dict, optional 

242 A dictionary where keys are ``FunctionClass`` instances and values are 

243 their string representations. Alternatively, the dictionary value can 

244 be a list of tuples i.e. [(argument_test, js_function_string)]. See 

245 below for examples. 

246 human : bool, optional 

247 If True, the result is a single string that may contain some constant 

248 declarations for the number symbols. If False, the same information is 

249 returned in a tuple of (symbols_to_declare, not_supported_functions, 

250 code_text). [default=True]. 

251 contract: bool, optional 

252 If True, ``Indexed`` instances are assumed to obey tensor contraction 

253 rules and the corresponding nested loops over indices are generated. 

254 Setting contract=False will not generate loops, instead the user is 

255 responsible to provide values for the indices in the code. 

256 [default=True]. 

257 

258 Examples 

259 ======== 

260 

261 >>> from sympy import jscode, symbols, Rational, sin, ceiling, Abs 

262 >>> x, tau = symbols("x, tau") 

263 >>> jscode((2*tau)**Rational(7, 2)) 

264 '8*Math.sqrt(2)*Math.pow(tau, 7/2)' 

265 >>> jscode(sin(x), assign_to="s") 

266 's = Math.sin(x);' 

267 

268 Custom printing can be defined for certain types by passing a dictionary of 

269 "type" : "function" to the ``user_functions`` kwarg. Alternatively, the 

270 dictionary value can be a list of tuples i.e. [(argument_test, 

271 js_function_string)]. 

272 

273 >>> custom_functions = { 

274 ... "ceiling": "CEIL", 

275 ... "Abs": [(lambda x: not x.is_integer, "fabs"), 

276 ... (lambda x: x.is_integer, "ABS")] 

277 ... } 

278 >>> jscode(Abs(x) + ceiling(x), user_functions=custom_functions) 

279 'fabs(x) + CEIL(x)' 

280 

281 ``Piecewise`` expressions are converted into conditionals. If an 

282 ``assign_to`` variable is provided an if statement is created, otherwise 

283 the ternary operator is used. Note that if the ``Piecewise`` lacks a 

284 default term, represented by ``(expr, True)`` then an error will be thrown. 

285 This is to prevent generating an expression that may not evaluate to 

286 anything. 

287 

288 >>> from sympy import Piecewise 

289 >>> expr = Piecewise((x + 1, x > 0), (x, True)) 

290 >>> print(jscode(expr, tau)) 

291 if (x > 0) { 

292 tau = x + 1; 

293 } 

294 else { 

295 tau = x; 

296 } 

297 

298 Support for loops is provided through ``Indexed`` types. With 

299 ``contract=True`` these expressions will be turned into loops, whereas 

300 ``contract=False`` will just print the assignment expression that should be 

301 looped over: 

302 

303 >>> from sympy import Eq, IndexedBase, Idx 

304 >>> len_y = 5 

305 >>> y = IndexedBase('y', shape=(len_y,)) 

306 >>> t = IndexedBase('t', shape=(len_y,)) 

307 >>> Dy = IndexedBase('Dy', shape=(len_y-1,)) 

308 >>> i = Idx('i', len_y-1) 

309 >>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i])) 

310 >>> jscode(e.rhs, assign_to=e.lhs, contract=False) 

311 'Dy[i] = (y[i + 1] - y[i])/(t[i + 1] - t[i]);' 

312 

313 Matrices are also supported, but a ``MatrixSymbol`` of the same dimensions 

314 must be provided to ``assign_to``. Note that any expression that can be 

315 generated normally can also exist inside a Matrix: 

316 

317 >>> from sympy import Matrix, MatrixSymbol 

318 >>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)]) 

319 >>> A = MatrixSymbol('A', 3, 1) 

320 >>> print(jscode(mat, A)) 

321 A[0] = Math.pow(x, 2); 

322 if (x > 0) { 

323 A[1] = x + 1; 

324 } 

325 else { 

326 A[1] = x; 

327 } 

328 A[2] = Math.sin(x); 

329 """ 

330 

331 return JavascriptCodePrinter(settings).doprint(expr, assign_to) 

332 

333 

334def print_jscode(expr, **settings): 

335 """Prints the Javascript representation of the given expression. 

336 

337 See jscode for the meaning of the optional arguments. 

338 """ 

339 print(jscode(expr, **settings))