| 1 |
import itertools |
| 2 |
|
| 3 |
from brian2.codegen.cpp_prefs import C99Check |
| 4 |
from brian2.core.functions import DEFAULT_FUNCTIONS, Function |
| 5 |
from brian2.core.variables import ( |
| 6 |
AuxiliaryVariable, |
| 7 |
Constant, |
| 8 |
DynamicArrayVariable, |
| 9 |
Subexpression, |
| 10 |
Variable, |
| 11 |
get_dtype_str, |
| 12 |
) |
| 13 |
from brian2.devices.device import all_devices |
| 14 |
from brian2.parsing.bast import brian_dtype_from_dtype |
| 15 |
from brian2.parsing.rendering import NodeRenderer |
| 16 |
from brian2.utils.stringtools import deindent, indent, word_substitute |
| 17 |
|
| 18 |
from .base import CodeGenerator |
| 19 |
|
| 20 |
__all__ = ["CythonCodeGenerator"] |
| 21 |
|
| 22 |
|
| 23 |
# fmt: off |
| 24 |
data_type_conversion_table = [ |
| 25 |
# canonical C++ Numpy |
| 26 |
('float32', 'float', 'float32'), |
| 27 |
('float64', 'double', 'float64'), |
| 28 |
('int32', 'int32_t', 'int32'), |
| 29 |
('int64', 'int64_t', 'int64'), |
| 30 |
('bool', 'bool', 'bool'), |
| 31 |
('uint8', 'char', 'uint8'), |
| 32 |
('uint64', 'uint64_t', 'uint64'), |
| 33 |
] |
| 34 |
# fmt: on |
| 35 |
|
| 36 |
cpp_dtype = {canonical: cpp for canonical, cpp, np in data_type_conversion_table} |
| 37 |
numpy_dtype = {canonical: np for canonical, cpp, np in data_type_conversion_table} |
| 38 |
|
| 39 |
|
| 40 |
def get_cpp_dtype(obj): |
| 41 |
return cpp_dtype[get_dtype_str(obj)] |
| 42 |
|
| 43 |
|
| 44 |
def get_numpy_dtype(obj): |
| 45 |
return numpy_dtype[get_dtype_str(obj)] |
| 46 |
|
| 47 |
|
| 48 |
def get_dynamic_array_cpp_type(var): |
| 49 |
"""Get the full templated C++ type for a DynamicArrayVariable""" |
| 50 |
cpp_dtype = get_cpp_dtype(var.dtype) # e.g., 'double', 'int32_t', 'float' |
| 51 |
|
| 52 |
# Special handling for bool - use char instead |
| 53 |
if get_dtype_str(var.dtype) == "bool": |
| 54 |
cpp_dtype = "char" |
| 55 |
|
| 56 |
if var.ndim == 1: |
| 57 |
return f"DynamicArray1DCpp[{cpp_dtype}]" # Returns "DynamicArray1DCpp[double]" |
| 58 |
elif var.ndim == 2: |
| 59 |
return f"DynamicArray2DCpp[{cpp_dtype}]" # Returns "DynamicArray2DCpp[double]" |
| 60 |
else: |
| 61 |
raise ValueError( |
| 62 |
f"Unsupported dynamic array dimension: {var.ndim}. Only 1D and 2D arrays are supported." |
| 63 |
) |
| 64 |
|
| 65 |
|
| 66 |
def get_capsule_type(var): |
| 67 |
"""Get the capsule type name for PyCapsule_GetPointer""" |
| 68 |
if var.ndim == 1: |
| 69 |
return "DynamicArray1D" |
| 70 |
elif var.ndim == 2: |
| 71 |
return "DynamicArray2D" |
| 72 |
else: |
| 73 |
raise ValueError( |
| 74 |
f"Unsupported dynamic array dimension: {var.ndim}. Only 1D and 2D arrays are supported." |
| 75 |
) |
| 76 |
|
| 77 |
|
| 78 |
class CythonNodeRenderer(NodeRenderer): |
| 79 |
def render_NameConstant(self, node): |
| 80 |
return {True: "1", False: "0"}.get(node.value, node.value) |
| 81 |
|
| 82 |
def render_Name(self, node): |
| 83 |
return {"True": "1", "False": "0"}.get(node.id, node.id) |
| 84 |
|
| 85 |
def render_BinOp(self, node): |
| 86 |
if node.op.__class__.__name__ == "Mod": |
| 87 |
left = self.render_node(node.left) |
| 88 |
right = self.render_node(node.right) |
| 89 |
return f"((({left})%({right}))+({right}))%({right})" |
| 90 |
else: |
| 91 |
return super().render_BinOp(node) |
| 92 |
|
| 93 |
|
| 94 |
class CythonCodeGenerator(CodeGenerator): |
| 95 |
""" |
| 96 |
Cython code generator |
| 97 |
""" |
| 98 |
|
| 99 |
class_name = "cython" |
| 100 |
|
| 101 |
def __init__(self, *args, **kwds): |
| 102 |
self.temporary_vars = set() |
| 103 |
super().__init__(*args, **kwds) |
| 104 |
|
| 105 |
def translate_expression(self, expr): |
| 106 |
expr = word_substitute(expr, self.func_name_replacements) |
| 107 |
return ( |
| 108 |
CythonNodeRenderer(auto_vectorise=self.auto_vectorise) |
| 109 |
.render_expr(expr, self.variables) |
| 110 |
.strip() |
| 111 |
) |
| 112 |
|
| 113 |
def translate_statement(self, statement): |
| 114 |
var, op, expr, comment = ( |
| 115 |
statement.var, |
| 116 |
statement.op, |
| 117 |
statement.expr, |
| 118 |
statement.comment, |
| 119 |
) |
| 120 |
if op == ":=": # make no distinction in Cython (declaration are done elsewhere) |
| 121 |
op = "=" |
| 122 |
# For Cython we replace complex expressions involving boolean variables into a sequence of |
| 123 |
# if/then expressions with simpler expressions. This is provided by the optimise_statements |
| 124 |
# function. |
| 125 |
if ( |
| 126 |
statement.used_boolean_variables is not None |
| 127 |
and len(statement.used_boolean_variables) |
| 128 |
# todo: improve dtype analysis so that this isn't necessary |
| 129 |
and brian_dtype_from_dtype(statement.dtype) == "float" |
| 130 |
): |
| 131 |
used_boolvars = statement.used_boolean_variables |
| 132 |
bool_simp = statement.boolean_simplified_expressions |
| 133 |
codelines = [] |
| 134 |
firstline = True |
| 135 |
# bool assigns is a sequence of (var, value) pairs giving the conditions under |
| 136 |
# which the simplified expression simp_expr holds |
| 137 |
for bool_assigns, simp_expr in bool_simp.items(): |
| 138 |
# generate a boolean expression like ``var1 and var2 and not var3`` |
| 139 |
atomics = [] |
| 140 |
for boolvar, boolval in bool_assigns: |
| 141 |
if boolval: |
| 142 |
atomics.append(boolvar) |
| 143 |
else: |
| 144 |
atomics.append(f"not {boolvar}") |
| 145 |
# use if/else/elif correctly |
| 146 |
if firstline: |
| 147 |
line = f"if {' and '.join(atomics)}:" |
| 148 |
else: |
| 149 |
if len(used_boolvars) > 1: |
| 150 |
line = f"elif {' and '.join(atomics)}:" |
| 151 |
else: |
| 152 |
line = "else:" |
| 153 |
line += "\n " |
| 154 |
line += f"{var} {op} {self.translate_expression(simp_expr)}" |
| 155 |
codelines.append(line) |
| 156 |
firstline = False |
| 157 |
code = "\n".join(codelines) |
| 158 |
else: |
| 159 |
code = f"{var} {op} {self.translate_expression(expr)}" |
| 160 |
if len(comment): |
| 161 |
code += f" # {comment}" |
| 162 |
return code |
| 163 |
|
| 164 |
def translate_one_statement_sequence(self, statements, scalar=False): |
| 165 |
# Note that we do not call this function from |
| 166 |
# `translate_statement_sequence` (which has been overwritten) |
| 167 |
# It is nevertheless implemented, so that it can be called explicitly |
| 168 |
# (e.g. from the GSL code generation) |
| 169 |
read, write, indices, conditional_write_vars = self.arrays_helper(statements) |
| 170 |
lines = [] |
| 171 |
# index and read arrays (index arrays first) |
| 172 |
lines += self.translate_to_read_arrays(read, indices) |
| 173 |
# the actual code |
| 174 |
lines += self.translate_to_statements(statements, conditional_write_vars) |
| 175 |
# write arrays |
| 176 |
lines += self.translate_to_write_arrays(write) |
| 177 |
|
| 178 |
return lines |
| 179 |
|
| 180 |
def translate_to_read_arrays(self, read, indices): |
| 181 |
lines = [] |
| 182 |
for varname in itertools.chain(sorted(indices), sorted(read)): |
| 183 |
var = self.variables[varname] |
| 184 |
index = self.variable_indices[varname] |
| 185 |
arrayname = self.get_array_name(var) |
| 186 |
line = f"{varname} = {arrayname}[{index}]" |
| 187 |
lines.append(line) |
| 188 |
return lines |
| 189 |
|
| 190 |
def translate_to_statements(self, statements, conditional_write_vars): |
| 191 |
lines = [] |
| 192 |
for stmt in statements: |
| 193 |
if stmt.op == ":=" and stmt.var not in self.variables: |
| 194 |
self.temporary_vars.add((stmt.var, stmt.dtype)) |
| 195 |
line = self.translate_statement(stmt) |
| 196 |
if stmt.var in conditional_write_vars: |
| 197 |
condvar = conditional_write_vars[stmt.var] |
| 198 |
lines.append(f"if {condvar}:") |
| 199 |
lines.append(indent(line)) |
| 200 |
else: |
| 201 |
lines.append(line) |
| 202 |
return lines |
| 203 |
|
| 204 |
def translate_to_write_arrays(self, write): |
| 205 |
lines = [] |
| 206 |
for varname in sorted(write): |
| 207 |
index_var = self.variable_indices[varname] |
| 208 |
var = self.variables[varname] |
| 209 |
line = ( |
| 210 |
f"{self.get_array_name(var, self.variables)}[{index_var}] = {varname}" |
| 211 |
) |
| 212 |
|
| 213 |
lines.append(line) |
| 214 |
return lines |
| 215 |
|
| 216 |
def translate_statement_sequence(self, sc_statements, ve_statements): |
| 217 |
# This function is overwritten, since we do not want to completely |
| 218 |
# separate the code generation for scalar and vector code |
| 219 |
|
| 220 |
assert set(sc_statements.keys()) == set(ve_statements.keys()) |
| 221 |
|
| 222 |
sc_code = {} |
| 223 |
ve_code = {} |
| 224 |
|
| 225 |
for block_name in sc_statements: |
| 226 |
sc_block = sc_statements[block_name] |
| 227 |
ve_block = ve_statements[block_name] |
| 228 |
(sc_read, sc_write, sc_indices, sc_cond_write) = self.arrays_helper( |
| 229 |
sc_block |
| 230 |
) |
| 231 |
(ve_read, ve_write, ve_indices, ve_cond_write) = self.arrays_helper( |
| 232 |
ve_block |
| 233 |
) |
| 234 |
# We want to read all scalar variables that are needed in the |
| 235 |
# vector code already in the scalar code, if they are not written |
| 236 |
for varname in set(ve_read): |
| 237 |
var = self.variables[varname] |
| 238 |
if var.scalar and varname not in ve_write: |
| 239 |
sc_read.add(varname) |
| 240 |
ve_read.remove(varname) |
| 241 |
|
| 242 |
for code, stmts, read, write, indices, cond_write in [ |
| 243 |
(sc_code, sc_block, sc_read, sc_write, sc_indices, sc_cond_write), |
| 244 |
(ve_code, ve_block, ve_read, ve_write, ve_indices, ve_cond_write), |
| 245 |
]: |
| 246 |
lines = [] |
| 247 |
# index and read arrays (index arrays first) |
| 248 |
lines += self.translate_to_read_arrays(read, indices) |
| 249 |
# the actual code |
| 250 |
lines += self.translate_to_statements(stmts, cond_write) |
| 251 |
# write arrays |
| 252 |
lines += self.translate_to_write_arrays(write) |
| 253 |
code[block_name] = "\n".join(lines) |
| 254 |
|
| 255 |
kwds = self.determine_keywords() |
| 256 |
return sc_code, ve_code, kwds |
| 257 |
|
| 258 |
def _add_user_function(self, varname, var, added): |
| 259 |
user_functions = [] |
| 260 |
load_namespace = [] |
| 261 |
support_code = [] |
| 262 |
impl = var.implementations[self.codeobj_class] |
| 263 |
if (impl.name, var) in added: |
| 264 |
return # nothing to do |
| 265 |
else: |
| 266 |
added.add((impl.name, var)) |
| 267 |
func_code = impl.get_code(self.owner) |
| 268 |
# Implementation can be None if the function is already |
| 269 |
# available in Cython (possibly under a different name) |
| 270 |
if func_code is not None: |
| 271 |
if isinstance(func_code, str): |
| 272 |
# Function is provided as Cython code |
| 273 |
# To make namespace variables available to functions, we |
| 274 |
# create global variables and assign to them in the main |
| 275 |
# code |
| 276 |
user_functions.append((varname, var)) |
| 277 |
func_namespace = impl.get_namespace(self.owner) or {} |
| 278 |
for ns_key, ns_value in func_namespace.items(): |
| 279 |
load_namespace.append(f"# namespace for function {varname}") |
| 280 |
if hasattr(ns_value, "dtype"): |
| 281 |
if ns_value.shape == (): |
| 282 |
raise NotImplementedError( |
| 283 |
"Directly replace scalar values in the function " |
| 284 |
"instead of providing them via the namespace" |
| 285 |
) |
| 286 |
newlines = [ |
| 287 |
"global _namespace{var_name}", |
| 288 |
"global _namespace_num{var_name}", |
| 289 |
( |
| 290 |
"cdef _numpy.ndarray[{cpp_dtype}, ndim=1, mode='c']" |
| 291 |
" _buf_{var_name} = _namespace['{var_name}']" |
| 292 |
), |
| 293 |
( |
| 294 |
"_namespace{var_name} = <{cpp_dtype} *>" |
| 295 |
" _buf_{var_name}.data" |
| 296 |
), |
| 297 |
"_namespace_num{var_name} = len(_namespace['{var_name}'])", |
| 298 |
] |
| 299 |
support_code.append( |
| 300 |
f"cdef {get_cpp_dtype(ns_value.dtype)} *_namespace{ns_key}" |
| 301 |
) |
| 302 |
|
| 303 |
else: # e.g. a function |
| 304 |
newlines = ["_namespace{var_name} = namespace['{var_name}']"] |
| 305 |
for line in newlines: |
| 306 |
load_namespace.append( |
| 307 |
line.format( |
| 308 |
cpp_dtype=get_cpp_dtype(ns_value.dtype), |
| 309 |
numpy_dtype=get_numpy_dtype(ns_value.dtype), |
| 310 |
var_name=ns_key, |
| 311 |
) |
| 312 |
) |
| 313 |
# Rename references to any dependencies if necessary |
| 314 |
for dep_name, dep in impl.dependencies.items(): |
| 315 |
dep_impl = dep.implementations[self.codeobj_class] |
| 316 |
dep_impl_name = dep_impl.name |
| 317 |
if dep_impl_name is None: |
| 318 |
dep_impl_name = dep.pyfunc.__name__ |
| 319 |
if dep_name != dep_impl_name: |
| 320 |
func_code = word_substitute( |
| 321 |
func_code, {dep_name: dep_impl_name} |
| 322 |
) |
| 323 |
support_code.append(deindent(func_code)) |
| 324 |
elif callable(func_code): |
| 325 |
self.variables[varname] = func_code |
| 326 |
line = f'{varname} = _namespace["{varname}"]' |
| 327 |
load_namespace.append(line) |
| 328 |
else: |
| 329 |
raise TypeError( |
| 330 |
"Provided function implementation for function " |
| 331 |
f"'{varname}' is neither a string nor callable (is " |
| 332 |
f"type {type(func_code)} instead)." |
| 333 |
) |
| 334 |
|
| 335 |
dep_support_code = [] |
| 336 |
dep_load_namespace = [] |
| 337 |
dep_user_functions = [] |
| 338 |
if impl.dependencies is not None: |
| 339 |
for dep_name, dep in impl.dependencies.items(): |
| 340 |
if dep_name not in self.variables: |
| 341 |
self.variables[dep_name] = dep |
| 342 |
user_func = self._add_user_function(dep_name, dep, added) |
| 343 |
if user_func is not None: |
| 344 |
sc, ln, uf = user_func |
| 345 |
dep_support_code.extend(sc) |
| 346 |
dep_load_namespace.extend(ln) |
| 347 |
dep_user_functions.extend(uf) |
| 348 |
|
| 349 |
return ( |
| 350 |
support_code + dep_support_code, |
| 351 |
dep_load_namespace + load_namespace, |
| 352 |
dep_user_functions + user_functions, |
| 353 |
) |
| 354 |
|
| 355 |
def determine_keywords(self): |
| 356 |
from brian2.devices.device import get_device |
| 357 |
|
| 358 |
device = get_device() |
| 359 |
# load variables from namespace |
| 360 |
load_namespace = [] |
| 361 |
support_code = [] |
| 362 |
handled_pointers = set() |
| 363 |
user_functions = [] |
| 364 |
added = set() |
| 365 |
for varname, var in sorted(self.variables.items()): |
| 366 |
if isinstance(var, Variable) and not isinstance( |
| 367 |
var, (Subexpression, AuxiliaryVariable) |
| 368 |
): |
| 369 |
load_namespace.append(f'_var_{varname} = _namespace["_var_{varname}"]') |
| 370 |
if isinstance(var, AuxiliaryVariable): |
| 371 |
line = f"cdef {get_cpp_dtype(var.dtype)} {varname}" |
| 372 |
load_namespace.append(line) |
| 373 |
elif isinstance(var, Subexpression): |
| 374 |
dtype = get_cpp_dtype(var.dtype) |
| 375 |
line = f"cdef {dtype} {varname}" |
| 376 |
load_namespace.append(line) |
| 377 |
elif isinstance(var, Constant): |
| 378 |
dtype_name = get_cpp_dtype(var.value) |
| 379 |
line = f'cdef {dtype_name} {varname} = _namespace["{varname}"]' |
| 380 |
load_namespace.append(line) |
| 381 |
elif isinstance(var, Variable): |
| 382 |
if var.dynamic: |
| 383 |
if isinstance(var, DynamicArrayVariable): |
| 384 |
# Uses direct C++ pointers for fast access, avoiding Python overhead. |
| 385 |
# We define unique names for the array object, its pointer, and the capsule. |
| 386 |
dyn_array_name = self.get_array_name(var, access_data=False) |
| 387 |
|
| 388 |
if dyn_array_name in handled_pointers: |
| 389 |
continue |
| 390 |
|
| 391 |
capsule_name = f"{dyn_array_name}_capsule" |
| 392 |
|
| 393 |
# Get the C++ type for accurate casting (e.g., "DynamicArray1DCpp[double]"). |
| 394 |
cpp_type = get_dynamic_array_cpp_type(var) |
| 395 |
|
| 396 |
# Generate Cython code to retrieve the C++ pointer from the capsule. |
| 397 |
# This is a two-step process in Cython: |
| 398 |
# 1. Look up the capsule object in the provided namespace. |
| 399 |
# 2. Unwrap the raw C++ pointer from the capsule for direct C++ object access. |
| 400 |
load_namespace.append( |
| 401 |
f'cdef object {capsule_name} = _namespace["{capsule_name}"]' |
| 402 |
) |
| 403 |
load_namespace.append( |
| 404 |
f"cdef {cpp_type}* {dyn_array_name}_ptr = " |
| 405 |
f'<{cpp_type}*>PyCapsule_GetPointer({capsule_name}, "{get_capsule_type(var)}")' |
| 406 |
) |
| 407 |
handled_pointers.add(dyn_array_name) |
| 408 |
else: |
| 409 |
pointer_name = self.get_array_name(var, False) |
| 410 |
load_namespace.append( |
| 411 |
f'{pointer_name} = _namespace["{pointer_name}"]' |
| 412 |
) |
| 413 |
|
| 414 |
# This is the "true" array name, not the restricted pointer. |
| 415 |
array_name = device.get_array_name(var) |
| 416 |
pointer_name = self.get_array_name(var) |
| 417 |
dyn_array_name = self.get_array_name(var, access_data=False) |
| 418 |
if pointer_name in handled_pointers: |
| 419 |
continue |
| 420 |
if isinstance(var, DynamicArrayVariable): |
| 421 |
# For Dynamic Arrays, we get the data pointer directly from the C++ object |
| 422 |
# The C++ DynamicArray class handles bool types correctly when we provide |
| 423 |
# them as char (unlike non-dynamic arrays which require special Cython buffer handling). |
| 424 |
cpp_dtype = get_cpp_dtype(var.dtype) |
| 425 |
if get_dtype_str(var.dtype) == "bool": |
| 426 |
# Use char for boolean dynamic arrays |
| 427 |
cpp_dtype = "char" |
| 428 |
|
| 429 |
newlines = [ |
| 430 |
( |
| 431 |
f"cdef {cpp_dtype}* {array_name} = <{cpp_dtype}*>" |
| 432 |
f" {dyn_array_name}_ptr.get_data_ptr()" |
| 433 |
) |
| 434 |
] |
| 435 |
else: |
| 436 |
if get_dtype_str(var.dtype) == "bool": |
| 437 |
newlines = [ |
| 438 |
( |
| 439 |
"cdef _numpy.ndarray[char, ndim=1, mode='c', cast=True]" |
| 440 |
" _buf_{array_name} = _namespace['{array_name}']" |
| 441 |
), |
| 442 |
( |
| 443 |
"cdef {cpp_dtype} * {array_name} = <{cpp_dtype} *>" |
| 444 |
" _buf_{array_name}.data" |
| 445 |
), |
| 446 |
] |
| 447 |
else: |
| 448 |
newlines = [ |
| 449 |
( |
| 450 |
"cdef _numpy.ndarray[{cpp_dtype}, ndim=1, mode='c']" |
| 451 |
" _buf_{array_name} = _namespace['{array_name}']" |
| 452 |
), |
| 453 |
( |
| 454 |
"cdef {cpp_dtype} * {array_name} = <{cpp_dtype} *>" |
| 455 |
" _buf_{array_name}.data" |
| 456 |
), |
| 457 |
] |
| 458 |
|
| 459 |
if not var.scalar: |
| 460 |
newlines += [ |
| 461 |
"cdef size_t _num{array_name} = len(_namespace['{array_name}'])" |
| 462 |
] |
| 463 |
|
| 464 |
if var.scalar and var.constant: |
| 465 |
newlines += ['cdef {cpp_dtype} {varname} = _namespace["{varname}"]'] |
| 466 |
else: |
| 467 |
newlines += ["cdef {cpp_dtype} {varname}"] |
| 468 |
|
| 469 |
for line in newlines: |
| 470 |
line = line.format( |
| 471 |
cpp_dtype=get_cpp_dtype(var.dtype), |
| 472 |
numpy_dtype=get_numpy_dtype(var.dtype), |
| 473 |
pointer_name=pointer_name, |
| 474 |
array_name=array_name, |
| 475 |
dyn_array_name=dyn_array_name, |
| 476 |
varname=varname, |
| 477 |
) |
| 478 |
load_namespace.append(line) |
| 479 |
handled_pointers.add(pointer_name) |
| 480 |
|
| 481 |
elif isinstance(var, Function): |
| 482 |
user_func = self._add_user_function(varname, var, added) |
| 483 |
if user_func is not None: |
| 484 |
sc, ln, uf = user_func |
| 485 |
support_code.extend(sc) |
| 486 |
load_namespace.extend(ln) |
| 487 |
user_functions.extend(uf) |
| 488 |
else: |
| 489 |
# fallback to Python object |
| 490 |
load_namespace.append(f'{varname} = _namespace["{varname}"]') |
| 491 |
|
| 492 |
for varname, dtype in sorted(self.temporary_vars): |
| 493 |
cpp_dtype = get_cpp_dtype(dtype) |
| 494 |
line = f"cdef {cpp_dtype} {varname}" |
| 495 |
load_namespace.append(line) |
| 496 |
|
| 497 |
return { |
| 498 |
"load_namespace": "\n".join(load_namespace), |
| 499 |
"support_code_lines": support_code, |
| 500 |
} |
| 501 |
|
| 502 |
|
| 503 |
############################################################################### |
| 504 |
# Implement functions |
| 505 |
################################################################################ |
| 506 |
# Functions that exist under the same name in C++ |
| 507 |
for func in [ |
| 508 |
"sin", |
| 509 |
"cos", |
| 510 |
"tan", |
| 511 |
"sinh", |
| 512 |
"cosh", |
| 513 |
"tanh", |
| 514 |
"exp", |
| 515 |
"log", |
| 516 |
"log10", |
| 517 |
"sqrt", |
| 518 |
"ceil", |
| 519 |
"floor", |
| 520 |
"abs", |
| 521 |
]: |
| 522 |
DEFAULT_FUNCTIONS[func].implementations.add_implementation( |
| 523 |
CythonCodeGenerator, code=None |
| 524 |
) |
| 525 |
DEFAULT_FUNCTIONS["expm1"].implementations.add_implementation( |
| 526 |
CythonCodeGenerator, code=None, availability_check=C99Check("expm1") |
| 527 |
) |
| 528 |
DEFAULT_FUNCTIONS["log1p"].implementations.add_implementation( |
| 529 |
CythonCodeGenerator, code=None, availability_check=C99Check("log1p") |
| 530 |
) |
| 531 |
|
| 532 |
# Functions that need a name translation |
| 533 |
for func, func_cpp in [ |
| 534 |
("arcsin", "asin"), |
| 535 |
("arccos", "acos"), |
| 536 |
("arctan", "atan"), |
| 537 |
("int", "int_"), # from stdint_compat.h |
| 538 |
]: |
| 539 |
DEFAULT_FUNCTIONS[func].implementations.add_implementation( |
| 540 |
CythonCodeGenerator, code=None, name=func_cpp |
| 541 |
) |
| 542 |
|
| 543 |
exprel_code = """ |
| 544 |
cdef inline double _exprel(double x) nogil: |
| 545 |
if fabs(x) < 1e-16: |
| 546 |
return 1.0 |
| 547 |
elif x > 717: # near log(DBL_MAX) |
| 548 |
return NPY_INFINITY |
| 549 |
else: |
| 550 |
return expm1(x) / x |
| 551 |
""" |
| 552 |
DEFAULT_FUNCTIONS["exprel"].implementations.add_implementation( |
| 553 |
CythonCodeGenerator, |
| 554 |
code=exprel_code, |
| 555 |
name="_exprel", |
| 556 |
availability_check=C99Check("exprel"), |
| 557 |
) |
| 558 |
_BUFFER_SIZE = 20000 |
| 559 |
|
| 560 |
rand_code = """ |
| 561 |
cdef double _rand(int _idx): |
| 562 |
cdef double **buffer_pointer = <double**>_namespace_rand_buffer |
| 563 |
cdef double *buffer = buffer_pointer[0] |
| 564 |
cdef _numpy.ndarray _new_rand |
| 565 |
|
| 566 |
if(_namespace_rand_buffer_index[0] == 0): |
| 567 |
if buffer != NULL: |
| 568 |
free(buffer) |
| 569 |
_new_rand = _numpy.random.rand(_BUFFER_SIZE) |
| 570 |
buffer = <double *>_numpy.PyArray_DATA(_new_rand) |
| 571 |
PyArray_CLEARFLAGS(<_numpy.PyArrayObject*>_new_rand, _numpy.NPY_ARRAY_OWNDATA) |
| 572 |
buffer_pointer[0] = buffer |
| 573 |
|
| 574 |
cdef double val = buffer[_namespace_rand_buffer_index[0]] |
| 575 |
_namespace_rand_buffer_index[0] += 1 |
| 576 |
if _namespace_rand_buffer_index[0] == _BUFFER_SIZE: |
| 577 |
_namespace_rand_buffer_index[0] = 0 |
| 578 |
return val |
| 579 |
""".replace("_BUFFER_SIZE", str(_BUFFER_SIZE)) |
| 580 |
|
| 581 |
randn_code = rand_code.replace("rand", "randn").replace("randnom", "random") |
| 582 |
|
| 583 |
poisson_code = """ |
| 584 |
cdef double _loggam(double x): |
| 585 |
cdef double x0, x2, xp, gl, gl0 |
| 586 |
cdef int32_t k, n |
| 587 |
|
| 588 |
cdef double a[10] |
| 589 |
a[:] = [8.333333333333333e-02, -2.777777777777778e-03, |
| 590 |
7.936507936507937e-04, -5.952380952380952e-04, |
| 591 |
8.417508417508418e-04, -1.917526917526918e-03, |
| 592 |
6.410256410256410e-03, -2.955065359477124e-02, |
| 593 |
1.796443723688307e-01, -1.39243221690590e+00] |
| 594 |
x0 = x |
| 595 |
n = 0 |
| 596 |
if (x == 1.0) or (x == 2.0): |
| 597 |
return 0.0 |
| 598 |
elif x <= 7.0: |
| 599 |
n = <int32_t>(7 - x) |
| 600 |
x0 = x + n |
| 601 |
x2 = 1.0 / (x0 * x0) |
| 602 |
xp = 2 * M_PI |
| 603 |
gl0 = a[9] |
| 604 |
for k in range(8, -1, -1): |
| 605 |
gl0 *= x2 |
| 606 |
gl0 += a[k] |
| 607 |
gl = gl0 / x0 + 0.5 * log(xp) + (x0 - 0.5) * log(x0) - x0 |
| 608 |
if x <= 7.0: |
| 609 |
for k in range(1, n+1): |
| 610 |
gl -= log(x0 - 1.0) |
| 611 |
x0 -= 1.0 |
| 612 |
return gl |
| 613 |
|
| 614 |
|
| 615 |
cdef int32_t _poisson_mult(double lam, int _vectorisation_idx): |
| 616 |
cdef int32_t X |
| 617 |
cdef double prod, U, enlam |
| 618 |
|
| 619 |
enlam = exp(-lam) |
| 620 |
X = 0 |
| 621 |
prod = 1.0 |
| 622 |
while True: |
| 623 |
U = _rand(_vectorisation_idx) |
| 624 |
prod *= U |
| 625 |
if (prod > enlam): |
| 626 |
X += 1 |
| 627 |
else: |
| 628 |
return X |
| 629 |
|
| 630 |
cdef int32_t _poisson_ptrs(double lam, int _vectorisation_idx): |
| 631 |
cdef int32_t k |
| 632 |
cdef double U, V, slam, loglam, a, b, invalpha, vr, us |
| 633 |
|
| 634 |
slam = sqrt(lam) |
| 635 |
loglam = log(lam) |
| 636 |
b = 0.931 + 2.53 * slam |
| 637 |
a = -0.059 + 0.02483 * b |
| 638 |
invalpha = 1.1239 + 1.1328 / (b - 3.4) |
| 639 |
vr = 0.9277 - 3.6224 / (b - 2) |
| 640 |
|
| 641 |
while True: |
| 642 |
U = _rand(_vectorisation_idx) - 0.5 |
| 643 |
V = _rand(_vectorisation_idx) |
| 644 |
us = 0.5 - abs(U) |
| 645 |
k = <int32_t>floor((2 * a / us + b) * U + lam + 0.43) |
| 646 |
if (us >= 0.07) and (V <= vr): |
| 647 |
return k |
| 648 |
if ((k < 0) or ((us < 0.013) and (V > us))): |
| 649 |
continue |
| 650 |
if ((log(V) + log(invalpha) - log(a / (us * us) + b)) <= |
| 651 |
(-lam + k * loglam - _loggam(k + 1))): |
| 652 |
return k |
| 653 |
|
| 654 |
cdef int32_t _poisson(double lam, int32_t _idx): |
| 655 |
if lam >= 10: |
| 656 |
return _poisson_ptrs(lam, _idx) |
| 657 |
elif lam == 0: |
| 658 |
return 0 |
| 659 |
else: |
| 660 |
return _poisson_mult(lam, _idx) |
| 661 |
""" |
| 662 |
|
| 663 |
device = all_devices["runtime"] |
| 664 |
DEFAULT_FUNCTIONS["rand"].implementations.add_implementation( |
| 665 |
CythonCodeGenerator, |
| 666 |
code=rand_code, |
| 667 |
name="_rand", |
| 668 |
namespace={ |
| 669 |
"_rand_buffer": device.rand_buffer, |
| 670 |
"_rand_buffer_index": device.rand_buffer_index, |
| 671 |
}, |
| 672 |
) |
| 673 |
|
| 674 |
DEFAULT_FUNCTIONS["randn"].implementations.add_implementation( |
| 675 |
CythonCodeGenerator, |
| 676 |
code=randn_code, |
| 677 |
name="_randn", |
| 678 |
namespace={ |
| 679 |
"_randn_buffer": device.randn_buffer, |
| 680 |
"_randn_buffer_index": device.randn_buffer_index, |
| 681 |
}, |
| 682 |
) |
| 683 |
DEFAULT_FUNCTIONS["poisson"].implementations.add_implementation( |
| 684 |
CythonCodeGenerator, |
| 685 |
code=poisson_code, |
| 686 |
name="_poisson", |
| 687 |
dependencies={"_rand": DEFAULT_FUNCTIONS["rand"]}, |
| 688 |
) |
| 689 |
|
| 690 |
sign_code = """ |
| 691 |
ctypedef fused _to_sign: |
| 692 |
char |
| 693 |
short |
| 694 |
int |
| 695 |
long |
| 696 |
float |
| 697 |
double |
| 698 |
|
| 699 |
cdef int _sign(_to_sign x): |
| 700 |
return (0 < x) - (x < 0) |
| 701 |
""" |
| 702 |
DEFAULT_FUNCTIONS["sign"].implementations.add_implementation( |
| 703 |
CythonCodeGenerator, code=sign_code, name="_sign" |
| 704 |
) |
| 705 |
|
| 706 |
clip_code = """ |
| 707 |
ctypedef fused _to_clip: |
| 708 |
char |
| 709 |
short |
| 710 |
int |
| 711 |
long |
| 712 |
float |
| 713 |
double |
| 714 |
|
| 715 |
cdef _to_clip _clip(_to_clip x, double low, double high): |
| 716 |
if x < low: |
| 717 |
return <_to_clip?>low |
| 718 |
if x > high: |
| 719 |
return <_to_clip?>high |
| 720 |
return x |
| 721 |
""" |
| 722 |
DEFAULT_FUNCTIONS["clip"].implementations.add_implementation( |
| 723 |
CythonCodeGenerator, code=clip_code, name="_clip" |
| 724 |
) |
| 725 |
|
| 726 |
timestep_code = """ |
| 727 |
cdef int64_t _timestep(double t, double dt): |
| 728 |
return <int64_t>((t + 1e-3*dt)/dt) |
| 729 |
""" |
| 730 |
DEFAULT_FUNCTIONS["timestep"].implementations.add_implementation( |
| 731 |
CythonCodeGenerator, code=timestep_code, name="_timestep" |
| 732 |
) |