Debian Codegraph @

brian2/codegen/generators/cpp_generator.py

raw
1 import itertools
2
3 import numpy
4
5 from brian2.codegen.cpp_prefs import C99Check
6 from brian2.core.functions import DEFAULT_FUNCTIONS, Function
7 from brian2.core.preferences import BrianPreference, prefs
8 from brian2.core.variables import ArrayVariable
9 from brian2.parsing.rendering import CPPNodeRenderer
10 from brian2.utils.logger import get_logger
11 from brian2.utils.stringtools import (
12 deindent,
13 stripped_deindented_lines,
14 word_substitute,
15 )
16
17 from .base import CodeGenerator
18
19 logger = get_logger(__name__)
20
21 __all__ = ["CPPCodeGenerator", "c_data_type"]
22
23
24 def c_data_type(dtype):
25 """
26 Gives the C language specifier for numpy data types. For example,
27 ``numpy.int32`` maps to ``int32_t`` in C.
28 """
29 # this handles the case where int is specified, it will be int32 or int64
30 # depending on platform
31 if dtype is int:
32 dtype = numpy.array([1]).dtype.type
33 if dtype is float:
34 dtype = numpy.array([1.0]).dtype.type
35
36 if dtype == numpy.float32:
37 dtype = "float"
38 elif dtype == numpy.float64:
39 dtype = "double"
40 elif dtype == numpy.int8:
41 dtype = "int8_t"
42 elif dtype == numpy.int16:
43 dtype = "int16_t"
44 elif dtype == numpy.int32:
45 dtype = "int32_t"
46 elif dtype == numpy.int64:
47 dtype = "int64_t"
48 elif dtype == numpy.uint16:
49 dtype = "uint16_t"
50 elif dtype == numpy.uint32:
51 dtype = "uint32_t"
52 elif dtype == numpy.uint64:
53 dtype = "uint64_t"
54 elif dtype == numpy.bool_ or dtype is bool:
55 dtype = "char"
56 else:
57 raise ValueError(f"dtype {str(dtype)} not known.")
58 return dtype
59
60
61 # Preferences
62 prefs.register_preferences(
63 "codegen.generators.cpp",
64 "C++ codegen preferences",
65 restrict_keyword=BrianPreference(
66 default="__restrict",
67 docs="""
68 The keyword used for the given compiler to declare pointers as restricted.
69
70 This keyword is different on different compilers, the default works for
71 gcc and MSVS.
72 """,
73 ),
74 flush_denormals=BrianPreference(
75 default=False,
76 docs="""
77 Adds code to flush denormals to zero.
78
79 The code is gcc and architecture specific, so may not compile on all
80 platforms. The code, for reference is::
81
82 #define CSR_FLUSH_TO_ZERO (1 << 15)
83 unsigned csr = __builtin_ia32_stmxcsr();
84 csr |= CSR_FLUSH_TO_ZERO;
85 __builtin_ia32_ldmxcsr(csr);
86
87 Found at `<http://stackoverflow.com/questions/2487653/avoiding-denormal-values-in-c>`_.
88 """,
89 ),
90 )
91
92
93 typestrs = ["int32_t", "int64_t", "float", "double", "long double"]
94 hightype_support_code = "template < typename T1, typename T2 > struct _higher_type;\n"
95 for ix, xtype in enumerate(typestrs):
96 for iy, ytype in enumerate(typestrs):
97 hightype = typestrs[max(ix, iy)]
98 hightype_support_code += f"""
99 template < > struct _higher_type<{xtype},{ytype}> {{ typedef {hightype} type; }};
100 """
101
102 mod_support_code = """
103 // General template, used for floating point types
104 template < typename T1, typename T2 >
105 static inline typename _higher_type<T1,T2>::type
106 _brian_mod(T1 x, T2 y)
107 {
108 return x-y*floor(1.0*x/y);
109 }
110
111 // Specific implementations for integer types
112 // (from Cython, see LICENSE file)
113 template <>
114 inline int32_t _brian_mod(int32_t x, int32_t y)
115 {
116 int32_t r = x % y;
117 r += ((r != 0) & ((r ^ y) < 0)) * y;
118 return r;
119 }
120
121 template <>
122 inline int64_t _brian_mod(int32_t x, int64_t y)
123 {
124 int64_t r = x % y;
125 r += ((r != 0) & ((r ^ y) < 0)) * y;
126 return r;
127 }
128
129 template <>
130 inline int64_t _brian_mod(int64_t x, int32_t y)
131 {
132 int64_t r = x % y;
133 r += ((r != 0) & ((r ^ y) < 0)) * y;
134 return r;
135 }
136
137 template <>
138 inline int64_t _brian_mod(int64_t x, int64_t y)
139 {
140 int64_t r = x % y;
141 r += ((r != 0) & ((r ^ y) < 0)) * y;
142 return r;
143 }
144 """
145
146 floordiv_support_code = """
147 // General implementation, used for floating point types
148 template < typename T1, typename T2 >
149 static inline typename _higher_type<T1,T2>::type
150 _brian_floordiv(T1 x, T2 y)
151 {{
152 return floor(1.0*x/y);
153 }}
154
155 // Specific implementations for integer types
156 // (from Cython, see LICENSE file)
157 template <>
158 inline int32_t _brian_floordiv<int32_t, int32_t>(int32_t a, int32_t b) {
159 int32_t q = a / b;
160 int32_t r = a - q*b;
161 q -= ((r != 0) & ((r ^ b) < 0));
162 return q;
163 }
164 template <>
165 inline int64_t _brian_floordiv<int32_t, int64_t>(int32_t a, int64_t b) {
166 int64_t q = a / b;
167 int64_t r = a - q*b;
168 q -= ((r != 0) & ((r ^ b) < 0));
169 return q;
170 }
171 template <>
172 inline int64_t _brian_floordiv<int64_t, int>(int64_t a, int32_t b) {
173 int64_t q = a / b;
174 int64_t r = a - q*b;
175 q -= ((r != 0) & ((r ^ b) < 0));
176 return q;
177 }
178 template <>
179 inline int64_t _brian_floordiv<int64_t, int64_t>(int64_t a, int64_t b) {
180 int64_t q = a / b;
181 int64_t r = a - q*b;
182 q -= ((r != 0) & ((r ^ b) < 0));
183 return q;
184 }
185 """
186
187 pow_support_code = """
188 #ifdef _MSC_VER
189 #define _brian_pow(x, y) (pow((double)(x), (y)))
190 #else
191 #define _brian_pow(x, y) (pow((x), (y)))
192 #endif
193 """
194
195 _universal_support_code = (
196 hightype_support_code + mod_support_code + floordiv_support_code + pow_support_code
197 )
198
199
200 class CPPCodeGenerator(CodeGenerator):
201 """
202 C++ language
203
204 C++ code templates should provide Jinja2 macros with the following names:
205
206 ``main``
207 The main loop.
208 ``support_code``
209 The support code (function definitions, etc.), compiled in a separate
210 file.
211
212 For user-defined functions, there are two keys to provide:
213
214 ``support_code``
215 The function definition which will be added to the support code.
216 ``hashdefine_code``
217 The ``#define`` code added to the main loop.
218
219 See `TimedArray` for an example of these keys.
220 """
221
222 class_name = "cpp"
223
224 universal_support_code = _universal_support_code
225
226 def __init__(self, *args, **kwds):
227 super().__init__(*args, **kwds)
228 self.c_data_type = c_data_type
229
230 @property
231 def restrict(self):
232 return f"{prefs['codegen.generators.cpp.restrict_keyword']} "
233
234 @property
235 def flush_denormals(self):
236 return prefs["codegen.generators.cpp.flush_denormals"]
237
238 @staticmethod
239 def get_array_name(var, access_data=True):
240 # We have to do the import here to avoid circular import dependencies.
241 from brian2.devices.device import get_device
242
243 device = get_device()
244 if access_data:
245 return f"_ptr{device.get_array_name(var)}"
246 else:
247 return device.get_array_name(var, access_data=False)
248
249 def translate_expression(self, expr):
250 expr = word_substitute(expr, self.func_name_replacements)
251 return (
252 CPPNodeRenderer(auto_vectorise=self.auto_vectorise)
253 .render_expr(expr)
254 .strip()
255 )
256
257 def translate_statement(self, statement):
258 var, op, expr, comment = (
259 statement.var,
260 statement.op,
261 statement.expr,
262 statement.comment,
263 )
264 # For C++ we replace complex expressions involving boolean variables into a sequence of
265 # if/then expressions with simpler expressions. This is provided by the optimise_statements
266 # function.
267 if statement.used_boolean_variables is not None and len(
268 statement.used_boolean_variables
269 ):
270 used_boolvars = statement.used_boolean_variables
271 bool_simp = statement.boolean_simplified_expressions
272 if op == ":=":
273 # we have to declare the variable outside the if/then statement (which
274 # unfortunately means we can't make it const but the optimisation is worth
275 # it anyway).
276 codelines = [f"{self.c_data_type(statement.dtype)} {var};"]
277 op = "="
278 else:
279 codelines = []
280 firstline = True
281 # bool assigns is a sequence of (var, value) pairs giving the conditions under
282 # which the simplified expression simp_expr holds
283 for bool_assigns, simp_expr in bool_simp.items():
284 # generate a boolean expression like ``var1 && var2 && !var3``
285 atomics = []
286 for boolvar, boolval in bool_assigns:
287 if boolval:
288 atomics.append(boolvar)
289 else:
290 atomics.append(f"!{boolvar}")
291 if firstline:
292 line = ""
293 else:
294 line = "else "
295 # only need another if statement when we have more than one boolean variables
296 if firstline or len(used_boolvars) > 1:
297 line += f"if({' && '.join(atomics)})"
298 line += "\n "
299 line += f"{var} {op} {self.translate_expression(simp_expr)};"
300 codelines.append(line)
301 firstline = False
302 code = "\n".join(codelines)
303 else:
304 if op == ":=":
305 decl = f"{self.c_data_type(statement.dtype)} "
306 op = "="
307 if statement.constant:
308 decl = f"const {decl}"
309 else:
310 decl = ""
311 code = f"{decl + var} {op} {self.translate_expression(expr)};"
312 if len(comment):
313 code += f" // {comment}"
314 return code
315
316 def translate_to_read_arrays(self, read, write, indices):
317 lines = []
318 # index and read arrays (index arrays first)
319 for varname in itertools.chain(sorted(indices), sorted(read)):
320 index_var = self.variable_indices[varname]
321 var = self.variables[varname]
322 if varname not in write:
323 line = "const "
324 else:
325 line = ""
326 line = f"{line + self.c_data_type(var.dtype)} {varname} = "
327 line = f"{line + self.get_array_name(var)}[{index_var}];"
328 lines.append(line)
329 return lines
330
331 def translate_to_declarations(self, read, write, indices):
332 lines = []
333 # simply declare variables that will be written but not read
334 for varname in sorted(write):
335 if varname not in read and varname not in indices:
336 var = self.variables[varname]
337 line = f"{self.c_data_type(var.dtype)} {varname};"
338 lines.append(line)
339 return lines
340
341 def translate_to_statements(self, statements, conditional_write_vars):
342 lines = []
343 # the actual code
344 for stmt in statements:
345 line = self.translate_statement(stmt)
346 if stmt.var in conditional_write_vars:
347 condvar = conditional_write_vars[stmt.var]
348 lines.append(f"if({condvar})")
349 lines.append(f" {line}")
350 else:
351 lines.append(line)
352 return lines
353
354 def translate_to_write_arrays(self, write):
355 lines = []
356 # write arrays
357 for varname in sorted(write):
358 index_var = self.variable_indices[varname]
359 var = self.variables[varname]
360 line = f"{self.get_array_name(var)}[{index_var}] = {varname};"
361 lines.append(line)
362 return lines
363
364 def translate_one_statement_sequence(self, statements, scalar=False):
365 # Note that we do not call this function from
366 # `translate_statement_sequence` (which has been overwritten)
367 # It is nevertheless implemented, so that it can be called explicitly
368 # (e.g. from the GSL code generation)
369 read, write, indices, cond_write = self.arrays_helper(statements)
370 lines = []
371 # index and read arrays (index arrays first)
372 lines += self.translate_to_read_arrays(read, write, indices)
373 # simply declare variables that will be written but not read
374 lines += self.translate_to_declarations(read, write, indices)
375 # the actual code
376 lines += self.translate_to_statements(statements, cond_write)
377 # write arrays
378 lines += self.translate_to_write_arrays(write)
379 return stripped_deindented_lines("\n".join(lines))
380
381 def translate_statement_sequence(self, sc_statements, ve_statements):
382 # This function is overwritten, since we do not want to completely
383 # separate the code generation for scalar and vector code
384
385 assert set(sc_statements.keys()) == set(ve_statements.keys())
386
387 kwds = self.determine_keywords()
388
389 sc_code = {}
390 ve_code = {}
391
392 for block_name in sc_statements:
393 sc_block = sc_statements[block_name]
394 ve_block = ve_statements[block_name]
395 (sc_read, sc_write, sc_indices, sc_cond_write) = self.arrays_helper(
396 sc_block
397 )
398 (ve_read, ve_write, ve_indices, ve_cond_write) = self.arrays_helper(
399 ve_block
400 )
401 # We want to read all scalar variables that are needed in the
402 # vector code already in the scalar code, if they are not written
403 for varname in set(ve_read):
404 var = self.variables[varname]
405 if var.scalar and varname not in ve_write:
406 sc_read.add(varname)
407 ve_read.remove(varname)
408
409 for code, stmts, read, write, indices, cond_write in [
410 (sc_code, sc_block, sc_read, sc_write, sc_indices, sc_cond_write),
411 (ve_code, ve_block, ve_read, ve_write, ve_indices, ve_cond_write),
412 ]:
413 lines = []
414 # index and read arrays (index arrays first)
415 lines += self.translate_to_read_arrays(read, write, indices)
416 # simply declare variables that will be written but not read
417 lines += self.translate_to_declarations(read, write, indices)
418 # the actual code
419 lines += self.translate_to_statements(stmts, cond_write)
420 # write arrays
421 lines += self.translate_to_write_arrays(write)
422 code[block_name] = stripped_deindented_lines("\n".join(lines))
423
424 return sc_code, ve_code, kwds
425
426 def denormals_to_zero_code(self):
427 if self.flush_denormals:
428 return """
429 #define CSR_FLUSH_TO_ZERO (1 << 15)
430 unsigned csr = __builtin_ia32_stmxcsr();
431 csr |= CSR_FLUSH_TO_ZERO;
432 __builtin_ia32_ldmxcsr(csr);
433 """
434 else:
435 return ""
436
437 def _add_user_function(self, varname, variable, added):
438 impl = variable.implementations[self.codeobj_class]
439 if (impl.name, variable) in added:
440 return # nothing to do
441 else:
442 added.add((impl.name, variable))
443 support_code = []
444 hash_defines = []
445 pointers = []
446 user_functions = [(varname, variable)]
447 funccode = impl.get_code(self.owner)
448 if isinstance(funccode, str):
449 # Rename references to any dependencies if necessary
450 for dep_name, dep in impl.dependencies.items():
451 dep_impl = dep.implementations[self.codeobj_class]
452 dep_impl_name = dep_impl.name
453 if dep_impl_name is None:
454 dep_impl_name = dep.pyfunc.__name__
455 if dep_name != dep_impl_name:
456 funccode = word_substitute(funccode, {dep_name: dep_impl_name})
457 funccode = {"support_code": funccode}
458 if funccode is not None:
459 # To make namespace variables available to functions, we
460 # create global variables and assign to them in the main
461 # code
462 func_namespace = impl.get_namespace(self.owner) or {}
463 for ns_key, ns_value in func_namespace.items():
464 if hasattr(ns_value, "dtype"):
465 if ns_value.shape == ():
466 raise NotImplementedError(
467 "Directly replace scalar values in the function "
468 "instead of providing them via the namespace"
469 )
470 type_str = f"{self.c_data_type(ns_value.dtype)}*"
471 else: # e.g. a function
472 type_str = "py::object"
473 support_code.append(f"static {type_str} _namespace{ns_key};")
474 pointers.append(f"_namespace{ns_key} = {ns_key};")
475 support_code.append(deindent(funccode.get("support_code", "")))
476 hash_defines.append(deindent(funccode.get("hashdefine_code", "")))
477
478 dep_hash_defines = []
479 dep_pointers = []
480 dep_support_code = []
481 if impl.dependencies is not None:
482 for dep_name, dep in impl.dependencies.items():
483 if dep_name not in self.variables:
484 self.variables[dep_name] = dep
485 dep_impl = dep.implementations[self.codeobj_class]
486 if dep_name != dep_impl.name:
487 self.func_name_replacements[dep_name] = dep_impl.name
488 user_function = self._add_user_function(dep_name, dep, added)
489 if user_function is not None:
490 hd, ps, sc, uf = user_function
491 dep_hash_defines.extend(hd)
492 dep_pointers.extend(ps)
493 dep_support_code.extend(sc)
494 user_functions.extend(uf)
495
496 return (
497 dep_hash_defines + hash_defines,
498 dep_pointers + pointers,
499 dep_support_code + support_code,
500 user_functions,
501 )
502
503 def determine_keywords(self):
504 # set up the restricted pointers, these are used so that the compiler
505 # knows there is no aliasing in the pointers, for optimisation
506 pointers = []
507 # It is possible that several different variable names refer to the
508 # same array. E.g. in gapjunction code, v_pre and v_post refer to the
509 # same array if a group is connected to itself
510 handled_pointers = set()
511 template_kwds = {}
512 # Again, do the import here to avoid a circular dependency.
513 from brian2.devices.device import get_device
514
515 device = get_device()
516 for var in self.variables.values():
517 if isinstance(var, ArrayVariable):
518 # This is the "true" array name, not the restricted pointer.
519 array_name = device.get_array_name(var)
520 pointer_name = self.get_array_name(var)
521 if pointer_name in handled_pointers:
522 continue
523 if getattr(var, "ndim", 1) > 1:
524 continue # multidimensional (dynamic) arrays have to be treated differently
525 restrict = self.restrict
526 # turn off restricted pointers for scalars for safety
527 if var.scalar or var.size == 1:
528 restrict = " "
529 line = (
530 f"{self.c_data_type(var.dtype)}* {restrict} {pointer_name} ="
531 f" {array_name};"
532 )
533 pointers.append(line)
534 handled_pointers.add(pointer_name)
535
536 # set up the functions
537 user_functions = []
538 support_code = []
539 hash_defines = []
540 added = set() # keep track of functions that were added
541 for varname, variable in list(self.variables.items()):
542 if isinstance(variable, Function):
543 user_func = self._add_user_function(varname, variable, added)
544 if user_func is not None:
545 hd, ps, sc, uf = user_func
546 user_functions.extend(uf)
547 support_code.extend(sc)
548 pointers.extend(ps)
549 hash_defines.extend(hd)
550 support_code.append(self.universal_support_code)
551
552 keywords = {
553 "pointers_lines": stripped_deindented_lines("\n".join(pointers)),
554 "support_code_lines": stripped_deindented_lines("\n".join(support_code)),
555 "hashdefine_lines": stripped_deindented_lines("\n".join(hash_defines)),
556 "denormals_code_lines": stripped_deindented_lines(
557 "\n".join(self.denormals_to_zero_code())
558 ),
559 }
560 keywords.update(template_kwds)
561 return keywords
562
563
564 ################################################################################
565 # Implement functions
566 ################################################################################
567 # Functions that exist under the same name in C++
568 for func in [
569 "sin",
570 "cos",
571 "tan",
572 "sinh",
573 "cosh",
574 "tanh",
575 "exp",
576 "log",
577 "log10",
578 "sqrt",
579 "ceil",
580 "floor",
581 ]:
582 DEFAULT_FUNCTIONS[func].implementations.add_implementation(
583 CPPCodeGenerator, code=None
584 )
585 DEFAULT_FUNCTIONS["expm1"].implementations.add_implementation(
586 CPPCodeGenerator, code=None, availability_check=C99Check("expm1")
587 )
588 DEFAULT_FUNCTIONS["log1p"].implementations.add_implementation(
589 CPPCodeGenerator, code=None, availability_check=C99Check("log1p")
590 )
591
592 # Functions that need a name translation
593 for func, func_cpp in [
594 ("arcsin", "asin"),
595 ("arccos", "acos"),
596 ("arctan", "atan"),
597 ("int", "int_"), # from stdint_compat.h
598 ]:
599 DEFAULT_FUNCTIONS[func].implementations.add_implementation(
600 CPPCodeGenerator, code=None, name=func_cpp
601 )
602
603 exprel_code = """
604 static inline double _exprel(double x)
605 {
606 if (fabs(x) < 1e-16)
607 return 1.0;
608 if (x > 717)
609 return INFINITY;
610 return expm1(x)/x;
611 }
612 """
613 DEFAULT_FUNCTIONS["exprel"].implementations.add_implementation(
614 CPPCodeGenerator,
615 code=exprel_code,
616 name="_exprel",
617 availability_check=C99Check("exprel"),
618 )
619
620 abs_code = """
621 #define _brian_abs std::abs
622 """
623 DEFAULT_FUNCTIONS["abs"].implementations.add_implementation(
624 CPPCodeGenerator, code=abs_code, name="_brian_abs"
625 )
626
627 clip_code = """
628 template <typename T>
629 static inline T _clip(const T value, const double a_min, const double a_max)
630 {
631 if (value < a_min)
632 return a_min;
633 if (value > a_max)
634 return a_max;
635 return value;
636 }
637 """
638 DEFAULT_FUNCTIONS["clip"].implementations.add_implementation(
639 CPPCodeGenerator, code=clip_code, name="_clip"
640 )
641
642 sign_code = """
643 template <typename T> static inline int _sign(T val) {
644 return (T(0) < val) - (val < T(0));
645 }
646 """
647 DEFAULT_FUNCTIONS["sign"].implementations.add_implementation(
648 CPPCodeGenerator, code=sign_code, name="_sign"
649 )
650
651 timestep_code = """
652 static inline int64_t _timestep(double t, double dt)
653 {
654 return (int64_t)((t + 1e-3*dt)/dt);
655 }
656 """
657 DEFAULT_FUNCTIONS["timestep"].implementations.add_implementation(
658 CPPCodeGenerator, code=timestep_code, name="_timestep"
659 )
660
661 poisson_code = """
662 double _loggam(double x) {
663 double x0, x2, xp, gl, gl0;
664 int32_t k, n;
665
666 static double a[10] = {8.333333333333333e-02, -2.777777777777778e-03,
667 7.936507936507937e-04, -5.952380952380952e-04,
668 8.417508417508418e-04, -1.917526917526918e-03,
669 6.410256410256410e-03, -2.955065359477124e-02,
670 1.796443723688307e-01, -1.39243221690590e+00};
671 x0 = x;
672 n = 0;
673 if ((x == 1.0) || (x == 2.0))
674 return 0.0;
675 else if (x <= 7.0) {
676 n = (int32_t)(7 - x);
677 x0 = x + n;
678 }
679 x2 = 1.0 / (x0 * x0);
680 xp = 2 * M_PI;
681 gl0 = a[9];
682 for (k=8; k>=0; k--) {
683 gl0 *= x2;
684 gl0 += a[k];
685 }
686 gl = gl0 / x0 + 0.5 * log(xp) + (x0 - 0.5) * log(x0) - x0;
687 if (x <= 7.0) {
688 for (k=1; k<=n; k++) {
689 gl -= log(x0 - 1.0);
690 x0 -= 1.0;
691 }
692 }
693 return gl;
694 }
695
696 int32_t _poisson_mult(double lam, int _vectorisation_idx) {
697 int32_t X;
698 double prod, U, enlam;
699
700 enlam = exp(-lam);
701 X = 0;
702 prod = 1.0;
703 while (1) {
704 U = _rand(_vectorisation_idx);
705 prod *= U;
706 if (prod > enlam)
707 X += 1;
708 else
709 return X;
710 }
711 }
712
713 int32_t _poisson_ptrs(double lam, int _vectorisation_idx) {
714 int32_t k;
715 double U, V, slam, loglam, a, b, invalpha, vr, us;
716
717 slam = sqrt(lam);
718 loglam = log(lam);
719 b = 0.931 + 2.53 * slam;
720 a = -0.059 + 0.02483 * b;
721 invalpha = 1.1239 + 1.1328 / (b - 3.4);
722 vr = 0.9277 - 3.6224 / (b - 2);
723
724 while (1) {
725 U = _rand(_vectorisation_idx) - 0.5;
726 V = _rand(_vectorisation_idx);
727 us = 0.5 - abs(U);
728 k = (int32_t)floor((2 * a / us + b) * U + lam + 0.43);
729 if ((us >= 0.07) && (V <= vr))
730 return k;
731 if ((k < 0) || ((us < 0.013) && (V > us)))
732 continue;
733 if ((log(V) + log(invalpha) - log(a / (us * us) + b)) <=
734 (-lam + k * loglam - _loggam(k + 1)))
735 return k;
736 }
737 }
738 int32_t _poisson(double lam, int32_t _idx) {
739 if (lam >= 10)
740 return _poisson_ptrs(lam, _idx);
741 else if (lam == 0)
742 return 0;
743 else
744 return _poisson_mult(lam, _idx);
745 }
746 """
747
748 DEFAULT_FUNCTIONS["poisson"].implementations.add_implementation(
749 CPPCodeGenerator,
750 code=poisson_code,
751 name="_poisson",
752 dependencies={"_rand": DEFAULT_FUNCTIONS["rand"]},
753 )