| 1 |
import json |
| 2 |
import os |
| 3 |
import platform |
| 4 |
import socket |
| 5 |
from collections import namedtuple |
| 6 |
|
| 7 |
import numpy as np |
| 8 |
import pytest |
| 9 |
|
| 10 |
from brian2 import _cache_dirs_and_extensions, clear_cache, prefs |
| 11 |
from brian2.codegen.codeobject import CodeObject |
| 12 |
from brian2.codegen.cpp_prefs import compiler_supports_c99, get_compiler_and_args |
| 13 |
from brian2.codegen.generators.cython_generator import CythonNodeRenderer |
| 14 |
from brian2.codegen.optimisation import optimise_statements |
| 15 |
from brian2.codegen.runtime.cython_rt import CythonCodeObject |
| 16 |
from brian2.codegen.statements import Statement |
| 17 |
from brian2.codegen.translation import ( |
| 18 |
analyse_identifiers, |
| 19 |
get_identifiers_recursively, |
| 20 |
make_statements, |
| 21 |
parse_statement, |
| 22 |
) |
| 23 |
from brian2.core.functions import DEFAULT_CONSTANTS, DEFAULT_FUNCTIONS, Function |
| 24 |
from brian2.core.variables import ArrayVariable, Constant, Subexpression, Variable |
| 25 |
from brian2.devices.device import auto_target, device |
| 26 |
from brian2.parsing.rendering import CPPNodeRenderer, NodeRenderer, NumpyNodeRenderer |
| 27 |
from brian2.parsing.sympytools import str_to_sympy, sympy_to_str |
| 28 |
from brian2.units import ms, second |
| 29 |
from brian2.units.fundamentalunits import Unit |
| 30 |
from brian2.utils.logger import catch_logs |
| 31 |
|
| 32 |
FakeGroup = namedtuple("FakeGroup", ["variables"]) |
| 33 |
|
| 34 |
|
| 35 |
@pytest.mark.codegen_independent |
| 36 |
def test_auto_target(): |
| 37 |
# very basic test that the "auto" codegen target is useable |
| 38 |
assert issubclass(auto_target(), CodeObject) |
| 39 |
|
| 40 |
|
| 41 |
@pytest.mark.codegen_independent |
| 42 |
def test_analyse_identifiers(): |
| 43 |
""" |
| 44 |
Test that the analyse_identifiers function works on a simple clear example. |
| 45 |
""" |
| 46 |
code = """ |
| 47 |
a = b+c |
| 48 |
d = e+f |
| 49 |
""" |
| 50 |
known = { |
| 51 |
"b": Variable(name="b"), |
| 52 |
"c": Variable(name="c"), |
| 53 |
"d": Variable(name="d"), |
| 54 |
"g": Variable(name="g"), |
| 55 |
} |
| 56 |
|
| 57 |
defined, used_known, dependent = analyse_identifiers(code, known) |
| 58 |
assert "a" in defined # There might be an additional constant added by the |
| 59 |
# loop-invariant optimisation |
| 60 |
assert used_known == {"b", "c", "d"} |
| 61 |
assert dependent == {"e", "f"} |
| 62 |
|
| 63 |
|
| 64 |
@pytest.mark.codegen_independent |
| 65 |
def test_get_identifiers_recursively(): |
| 66 |
""" |
| 67 |
Test finding identifiers including subexpressions. |
| 68 |
""" |
| 69 |
variables = { |
| 70 |
"sub1": Subexpression( |
| 71 |
name="sub1", |
| 72 |
dtype=np.float32, |
| 73 |
expr="sub2 * z", |
| 74 |
owner=FakeGroup(variables={}), |
| 75 |
device=None, |
| 76 |
), |
| 77 |
"sub2": Subexpression( |
| 78 |
name="sub2", |
| 79 |
dtype=np.float32, |
| 80 |
expr="5 + y", |
| 81 |
owner=FakeGroup(variables={}), |
| 82 |
device=None, |
| 83 |
), |
| 84 |
"x": Variable(name="x"), |
| 85 |
} |
| 86 |
identifiers = get_identifiers_recursively(["_x = sub1 + x"], variables) |
| 87 |
assert identifiers == {"x", "_x", "y", "z", "sub1", "sub2"} |
| 88 |
|
| 89 |
|
| 90 |
@pytest.mark.codegen_independent |
| 91 |
def test_write_to_subexpression(): |
| 92 |
variables = { |
| 93 |
"a": Subexpression( |
| 94 |
name="a", |
| 95 |
dtype=np.float32, |
| 96 |
owner=FakeGroup(variables={}), |
| 97 |
device=None, |
| 98 |
expr="2*z", |
| 99 |
), |
| 100 |
"z": Variable(name="z"), |
| 101 |
} |
| 102 |
|
| 103 |
# Writing to a subexpression is not allowed |
| 104 |
code = "a = z" |
| 105 |
with pytest.raises(SyntaxError): |
| 106 |
make_statements(code, variables, np.float32) |
| 107 |
|
| 108 |
|
| 109 |
@pytest.mark.codegen_independent |
| 110 |
def test_repeated_subexpressions(): |
| 111 |
variables = { |
| 112 |
"a": Subexpression( |
| 113 |
name="a", |
| 114 |
dtype=np.float32, |
| 115 |
owner=FakeGroup(variables={}), |
| 116 |
device=None, |
| 117 |
expr="2*z", |
| 118 |
), |
| 119 |
"x": Variable(name="x"), |
| 120 |
"y": Variable(name="y"), |
| 121 |
"z": Variable(name="z"), |
| 122 |
} |
| 123 |
# subexpression a (referring to z) is used twice, but can be reused the |
| 124 |
# second time (no change to z) |
| 125 |
code = """ |
| 126 |
x = a |
| 127 |
y = a |
| 128 |
""" |
| 129 |
scalar_stmts, vector_stmts = make_statements(code, variables, np.float32) |
| 130 |
assert len(scalar_stmts) == 0 |
| 131 |
assert [stmt.var for stmt in vector_stmts] == ["a", "x", "y"] |
| 132 |
assert vector_stmts[0].constant |
| 133 |
|
| 134 |
code = """ |
| 135 |
x = a |
| 136 |
z *= 2 |
| 137 |
""" |
| 138 |
scalar_stmts, vector_stmts = make_statements(code, variables, np.float32) |
| 139 |
assert len(scalar_stmts) == 0 |
| 140 |
assert [stmt.var for stmt in vector_stmts] == ["a", "x", "z"] |
| 141 |
# Note that we currently do not mark the subexpression as constant in this |
| 142 |
# case, because its use after the "z *=2" line would actually redefine it. |
| 143 |
# Our algorithm is currently not smart enough to detect that it is actually |
| 144 |
# not used afterwards |
| 145 |
|
| 146 |
# a refers to z, therefore we have to redefine a after z changed, and a |
| 147 |
# cannot be constant |
| 148 |
code = """ |
| 149 |
x = a |
| 150 |
z *= 2 |
| 151 |
y = a |
| 152 |
""" |
| 153 |
scalar_stmts, vector_stmts = make_statements(code, variables, np.float32) |
| 154 |
assert len(scalar_stmts) == 0 |
| 155 |
assert [stmt.var for stmt in vector_stmts] == ["a", "x", "z", "a", "y"] |
| 156 |
assert not any(stmt.constant for stmt in vector_stmts) |
| 157 |
|
| 158 |
|
| 159 |
@pytest.mark.codegen_independent |
| 160 |
def test_nested_subexpressions(): |
| 161 |
""" |
| 162 |
This test checks that code translation works with nested subexpressions. |
| 163 |
""" |
| 164 |
code = """ |
| 165 |
x = a + b + c |
| 166 |
c = 1 |
| 167 |
x = a + b + c |
| 168 |
d = 1 |
| 169 |
x = a + b + c |
| 170 |
""" |
| 171 |
variables = { |
| 172 |
"a": Subexpression( |
| 173 |
name="a", |
| 174 |
dtype=np.float32, |
| 175 |
owner=FakeGroup(variables={}), |
| 176 |
device=None, |
| 177 |
expr="b*b+d", |
| 178 |
), |
| 179 |
"b": Subexpression( |
| 180 |
name="b", |
| 181 |
dtype=np.float32, |
| 182 |
owner=FakeGroup(variables={}), |
| 183 |
device=None, |
| 184 |
expr="c*c*c", |
| 185 |
), |
| 186 |
"c": Variable(name="c"), |
| 187 |
"d": Variable(name="d"), |
| 188 |
} |
| 189 |
scalar_stmts, vector_stmts = make_statements(code, variables, np.float32) |
| 190 |
assert len(scalar_stmts) == 0 |
| 191 |
evalorder = "".join(stmt.var for stmt in vector_stmts) |
| 192 |
# This is the order that variables ought to be evaluated in (note that |
| 193 |
# previously this test did not expect the last "b" evaluation, because its |
| 194 |
# value did not change (c was not changed). We have since removed this |
| 195 |
# subexpression caching, because it did not seem to apply in practical |
| 196 |
# use cases) |
| 197 |
assert evalorder == "baxcbaxdbax" |
| 198 |
|
| 199 |
|
| 200 |
@pytest.mark.codegen_independent |
| 201 |
def test_apply_loop_invariant_optimisation(): |
| 202 |
variables = { |
| 203 |
"v": Variable("v", scalar=False), |
| 204 |
"w": Variable("w", scalar=False), |
| 205 |
"dt": Constant("dt", dimensions=second.dim, value=0.1 * ms), |
| 206 |
"tau": Constant("tau", dimensions=second.dim, value=10 * ms), |
| 207 |
"exp": DEFAULT_FUNCTIONS["exp"], |
| 208 |
} |
| 209 |
statements = [ |
| 210 |
Statement("v", "=", "dt*w*exp(-dt/tau)/tau + v*exp(-dt/tau)", "", np.float32), |
| 211 |
Statement("w", "=", "w*exp(-dt/tau)", "", np.float32), |
| 212 |
] |
| 213 |
scalar, vector = optimise_statements([], statements, variables) |
| 214 |
# The optimisation should pull out at least exp(-dt / tau) |
| 215 |
assert len(scalar) >= 1 |
| 216 |
assert np.issubdtype(scalar[0].dtype, np.floating) |
| 217 |
assert scalar[0].var == "_lio_1" |
| 218 |
assert len(vector) == 2 |
| 219 |
assert all("_lio_" in stmt.expr for stmt in vector) |
| 220 |
|
| 221 |
|
| 222 |
@pytest.mark.codegen_independent |
| 223 |
def test_apply_loop_invariant_optimisation_integer(): |
| 224 |
variables = { |
| 225 |
"v": Variable("v", scalar=False), |
| 226 |
"N": Constant("N", 10), |
| 227 |
"b": Variable("b", scalar=True, dtype=int), |
| 228 |
"c": Variable("c", scalar=True, dtype=int), |
| 229 |
"d": Variable("d", scalar=True, dtype=int), |
| 230 |
"y": Variable("y", scalar=True, dtype=float), |
| 231 |
"z": Variable("z", scalar=True, dtype=float), |
| 232 |
"w": Variable("w", scalar=True, dtype=float), |
| 233 |
} |
| 234 |
statements = [ |
| 235 |
Statement("v", "=", "v % (2*3*N)", "", np.float32), |
| 236 |
# integer version doesn't get rewritten but float version does |
| 237 |
Statement("a", ":=", "b//(c//d)", "", int), |
| 238 |
Statement("x", ":=", "y/(z/w)", "", float), |
| 239 |
] |
| 240 |
scalar, vector = optimise_statements([], statements, variables) |
| 241 |
assert len(scalar) == 3 |
| 242 |
assert np.issubdtype(scalar[0].dtype, np.signedinteger) |
| 243 |
assert scalar[0].var == "_lio_1" |
| 244 |
expr = scalar[0].expr.replace(" ", "") |
| 245 |
assert expr == "6*N" or expr == "N*6" |
| 246 |
assert np.issubdtype(scalar[1].dtype, np.signedinteger) |
| 247 |
assert scalar[1].var == "_lio_2" |
| 248 |
expr = scalar[1].expr.replace(" ", "") |
| 249 |
assert expr == "b//(c//d)" |
| 250 |
assert np.issubdtype(scalar[2].dtype, np.floating) |
| 251 |
assert scalar[2].var == "_lio_3" |
| 252 |
expr = scalar[2].expr.replace(" ", "") |
| 253 |
assert expr == "(y*w)/z" or expr == "(w*y)/z" |
| 254 |
|
| 255 |
|
| 256 |
@pytest.mark.codegen_independent |
| 257 |
def test_apply_loop_invariant_optimisation_boolean(): |
| 258 |
variables = { |
| 259 |
"v1": Variable("v1", scalar=False), |
| 260 |
"v2": Variable("v2", scalar=False), |
| 261 |
"N": Constant("N", 10), |
| 262 |
"b": Variable("b", scalar=True, dtype=bool), |
| 263 |
"c": Variable("c", scalar=True, dtype=bool), |
| 264 |
"int": DEFAULT_FUNCTIONS["int"], |
| 265 |
"foo": Function( |
| 266 |
lambda x: None, |
| 267 |
arg_units=[Unit(1)], |
| 268 |
return_unit=Unit(1), |
| 269 |
arg_types=["boolean"], |
| 270 |
return_type="float", |
| 271 |
stateless=False, |
| 272 |
), |
| 273 |
} |
| 274 |
# The calls for "foo" cannot be pulled out, since foo is marked as stateful |
| 275 |
statements = [ |
| 276 |
Statement("v1", "=", "1.0*int(b and c)", "", np.float32), |
| 277 |
Statement("v1", "=", "1.0*foo(b and c)", "", np.float32), |
| 278 |
Statement("v2", "=", "int(not b and True)", "", np.float32), |
| 279 |
Statement("v2", "=", "foo(not b and True)", "", np.float32), |
| 280 |
] |
| 281 |
scalar, vector = optimise_statements([], statements, variables) |
| 282 |
assert len(scalar) == 4 |
| 283 |
assert scalar[0].expr == "1.0 * int(b and c)" |
| 284 |
assert scalar[1].expr == "b and c" |
| 285 |
assert scalar[2].expr == "int((not b) and True)" |
| 286 |
assert scalar[3].expr == "(not b) and True" |
| 287 |
assert len(vector) == 4 |
| 288 |
assert vector[0].expr == "_lio_1" |
| 289 |
assert vector[1].expr == "foo(_lio_2)" |
| 290 |
assert vector[2].expr == "_lio_3" |
| 291 |
assert vector[3].expr == "foo(_lio_4)" |
| 292 |
|
| 293 |
|
| 294 |
@pytest.mark.codegen_independent |
| 295 |
def test_apply_loop_invariant_optimisation_no_optimisation(): |
| 296 |
variables = { |
| 297 |
"v1": Variable("v1", scalar=False), |
| 298 |
"v2": Variable("v2", scalar=False), |
| 299 |
"N": Constant("N", 10), |
| 300 |
"s1": Variable("s1", scalar=True, dtype=float), |
| 301 |
"s2": Variable("s2", scalar=True, dtype=float), |
| 302 |
"rand": DEFAULT_FUNCTIONS["rand"], |
| 303 |
} |
| 304 |
statements = [ |
| 305 |
# This should not be simplified to 0! |
| 306 |
Statement("v1", "=", "rand() - rand()", "", float), |
| 307 |
Statement("v1", "=", "3*rand() - 3*rand()", "", float), |
| 308 |
Statement("v1", "=", "3*rand() - ((1+2)*rand())", "", float), |
| 309 |
# This should not pull out rand()*N |
| 310 |
Statement("v1", "=", "s1*rand()*N", "", float), |
| 311 |
Statement("v1", "=", "s2*rand()*N", "", float), |
| 312 |
# This is not important mathematically, but it would change the numbers |
| 313 |
# that are generated |
| 314 |
Statement("v1", "=", "0*rand()*N", "", float), |
| 315 |
Statement("v1", "=", "0/rand()*N", "", float), |
| 316 |
] |
| 317 |
scalar, vector = optimise_statements([], statements, variables) |
| 318 |
for vs in vector[:3]: |
| 319 |
assert vs.expr.count("rand()") == 2, ( |
| 320 |
f"Expression should still contain two rand() calls, but got {str(vs)}" |
| 321 |
) |
| 322 |
for vs in vector[3:]: |
| 323 |
assert vs.expr.count("rand()") == 1, ( |
| 324 |
f"Expression should still contain a rand() call, but got {str(vs)}" |
| 325 |
) |
| 326 |
|
| 327 |
|
| 328 |
@pytest.mark.codegen_independent |
| 329 |
def test_apply_loop_invariant_optimisation_simplification(): |
| 330 |
variables = { |
| 331 |
"v1": Variable("v1", scalar=False), |
| 332 |
"v2": Variable("v2", scalar=False), |
| 333 |
"i1": Variable("i1", scalar=False, dtype=int), |
| 334 |
"N": Constant("N", 10), |
| 335 |
} |
| 336 |
statements = [ |
| 337 |
# Should be simplified to 0.0 |
| 338 |
Statement("v1", "=", "v1 - v1", "", float), |
| 339 |
Statement("v1", "=", "N*v1 - N*v1", "", float), |
| 340 |
Statement("v1", "=", "v1*N * 0", "", float), |
| 341 |
Statement("v1", "=", "v1 * 0", "", float), |
| 342 |
Statement("v1", "=", "v1 * 0.0", "", float), |
| 343 |
Statement("v1", "=", "0.0 / (v1*N)", "", float), |
| 344 |
# Should be simplified to 0 |
| 345 |
Statement("i1", "=", "i1*N * 0", "", int), |
| 346 |
Statement("i1", "=", "0 * i1", "", int), |
| 347 |
Statement("i1", "=", "0 * i1*N", "", int), |
| 348 |
Statement("i1", "=", "i1 * 0", "", int), |
| 349 |
# Should be simplified to v1*N |
| 350 |
Statement("v2", "=", "0 + v1*N", "", float), |
| 351 |
Statement("v2", "=", "v1*N + 0.0", "", float), |
| 352 |
Statement("v2", "=", "v1*N - 0", "", float), |
| 353 |
Statement("v2", "=", "v1*N - 0.0", "", float), |
| 354 |
Statement("v2", "=", "1 * v1*N", "", float), |
| 355 |
Statement("v2", "=", "1.0 * v1*N", "", float), |
| 356 |
Statement("v2", "=", "v1*N / 1.0", "", float), |
| 357 |
Statement("v2", "=", "v1*N / 1", "", float), |
| 358 |
# Should be simplified to i1 |
| 359 |
Statement("i1", "=", "i1*1", "", int), |
| 360 |
Statement("i1", "=", "i1//1", "", int), |
| 361 |
Statement("i1", "=", "i1+0", "", int), |
| 362 |
Statement("i1", "=", "0+i1", "", int), |
| 363 |
Statement("i1", "=", "i1-0", "", int), |
| 364 |
# Should *not* be simplified (because it would change the type, |
| 365 |
# important for integer division, for example) |
| 366 |
Statement("v1", "=", "i1*1.0", "", float), |
| 367 |
Statement("v1", "=", "1.0*i1", "", float), |
| 368 |
Statement("v1", "=", "i1/1.0", "", float), |
| 369 |
Statement("v1", "=", "i1/1", "", float), |
| 370 |
Statement("v1", "=", "i1+0.0", "", float), |
| 371 |
Statement("v1", "=", "0.0+i1", "", float), |
| 372 |
Statement("v1", "=", "i1-0.0", "", float), |
| 373 |
## Should *not* be simplified, flooring division by 1 changes the value |
| 374 |
Statement("v1", "=", "v2//1.0", "", float), |
| 375 |
Statement("i1", "=", "i1//1.0", "", float), # changes type |
| 376 |
] |
| 377 |
scalar, vector = optimise_statements([], statements, variables) |
| 378 |
assert len(scalar) == 0 |
| 379 |
for s in vector[:6]: |
| 380 |
assert s.expr == "0.0" |
| 381 |
for s in vector[6:10]: |
| 382 |
assert s.expr == "0", s.expr # integer |
| 383 |
for s in vector[10:18]: |
| 384 |
expr = s.expr.replace(" ", "") |
| 385 |
assert expr == "v1*N" or expr == "N*v1" |
| 386 |
for s in vector[18:23]: |
| 387 |
expr = s.expr.replace(" ", "") |
| 388 |
assert expr == "i1" |
| 389 |
for s in vector[23:27]: |
| 390 |
expr = s.expr.replace(" ", "") |
| 391 |
assert expr == "1.0*i1" or expr == "i1*1.0" or expr == "i1/1.0" |
| 392 |
for s in vector[27:30]: |
| 393 |
expr = s.expr.replace(" ", "") |
| 394 |
assert expr == "0.0+i1" or expr == "i1+0.0" |
| 395 |
for s in vector[30:31]: |
| 396 |
expr = s.expr.replace(" ", "") |
| 397 |
assert expr == "v2//1.0" or expr == "v2//1" |
| 398 |
for s in vector[31:]: |
| 399 |
expr = s.expr.replace(" ", "") |
| 400 |
assert expr == "i1//1.0" |
| 401 |
|
| 402 |
|
| 403 |
@pytest.mark.codegen_independent |
| 404 |
def test_apply_loop_invariant_optimisation_constant_evaluation(): |
| 405 |
variables = { |
| 406 |
"v1": Variable("v1", scalar=False), |
| 407 |
"v2": Variable("v2", scalar=False), |
| 408 |
"i1": Variable("i1", scalar=False, dtype=int), |
| 409 |
"N": Constant("N", 10), |
| 410 |
"s1": Variable("s1", scalar=True, dtype=float), |
| 411 |
"s2": Variable("s2", scalar=True, dtype=float), |
| 412 |
"exp": DEFAULT_FUNCTIONS["exp"], |
| 413 |
} |
| 414 |
statements = [ |
| 415 |
Statement("v1", "=", "v1 * (1 + 2 + 3)", "", float), |
| 416 |
Statement("v1", "=", "exp(N)*v1", "", float), |
| 417 |
Statement("v1", "=", "exp(0)*v1", "", float), |
| 418 |
] |
| 419 |
scalar, vector = optimise_statements([], statements, variables) |
| 420 |
# exp(N) should be pulled out of the vector statements, the rest should be |
| 421 |
# evaluated in place |
| 422 |
assert len(scalar) == 1 |
| 423 |
assert scalar[0].expr == "exp(N)" |
| 424 |
assert len(vector) == 3 |
| 425 |
expr = vector[0].expr.replace(" ", "") |
| 426 |
assert expr == "_lio_1*v1" or "v1*_lio_1" |
| 427 |
expr = vector[1].expr.replace(" ", "") |
| 428 |
assert expr == "6.0*v1" or "v1*6.0" |
| 429 |
assert vector[2].expr == "v1" |
| 430 |
|
| 431 |
|
| 432 |
@pytest.mark.codegen_independent |
| 433 |
def test_automatic_augmented_assignments(): |
| 434 |
# We test that statements that could be rewritten as augmented assignments |
| 435 |
# are correctly rewritten (using sympy to test for symbolic equality) |
| 436 |
variables = { |
| 437 |
"x": ArrayVariable("x", owner=None, size=10, device=device), |
| 438 |
"y": ArrayVariable("y", owner=None, size=10, device=device), |
| 439 |
"z": ArrayVariable("y", owner=None, size=10, device=device), |
| 440 |
"b": ArrayVariable("b", owner=None, size=10, dtype=bool, device=device), |
| 441 |
"clip": DEFAULT_FUNCTIONS["clip"], |
| 442 |
"inf": DEFAULT_CONSTANTS["inf"], |
| 443 |
} |
| 444 |
statements = [ |
| 445 |
# examples that should be rewritten |
| 446 |
# Note that using our approach, we will never get -= or /= but always |
| 447 |
# the equivalent += or *= statements |
| 448 |
("x = x + 1.0", "x += 1.0"), |
| 449 |
("x = 2.0 * x", "x *= 2.0"), |
| 450 |
("x = x - 3.0", "x += -3.0"), |
| 451 |
("x = x/2.0", "x *= 0.5"), |
| 452 |
("x = y + (x + 1.0)", "x += y + 1.0"), |
| 453 |
("x = x + x", "x *= 2"), |
| 454 |
("x = x + y + z", "x += y + z"), |
| 455 |
("x = x + y + z", "x += y + z"), |
| 456 |
# examples that should not be rewritten |
| 457 |
("x = 1.0/x", "x = 1.0/x"), |
| 458 |
("x = 1.0", "x = 1.0"), |
| 459 |
("x = 2.0*(x + 1.0)", "x = 2.0*(x + 1.0)"), |
| 460 |
("x = clip(x + y, 0.0, inf)", "x = clip(x + y, 0.0, inf)"), |
| 461 |
("b = b or False", "b = b or False"), |
| 462 |
] |
| 463 |
for orig, rewritten in statements: |
| 464 |
scalar, vector = make_statements(orig, variables, np.float32) |
| 465 |
try: # we augment the assertion error with the original statement |
| 466 |
assert len(scalar) == 0, ( |
| 467 |
f"Did not expect any scalar statements but got {str(scalar)}" |
| 468 |
) |
| 469 |
assert len(vector) == 1, ( |
| 470 |
f"Did expect a single statement but got {str(vector)}" |
| 471 |
) |
| 472 |
statement = vector[0] |
| 473 |
expected_var, expected_op, expected_expr, _ = parse_statement(rewritten) |
| 474 |
assert expected_var == statement.var, ( |
| 475 |
f"expected write to variable {expected_var}, not to {statement.var}" |
| 476 |
) |
| 477 |
assert expected_op == statement.op, ( |
| 478 |
f"expected operation {expected_op}, not {statement.op}" |
| 479 |
) |
| 480 |
# Compare the two expressions using sympy to allow for different order etc. |
| 481 |
sympy_expected = str_to_sympy(expected_expr) |
| 482 |
sympy_actual = str_to_sympy(statement.expr) |
| 483 |
assert sympy_expected == sympy_actual, ( |
| 484 |
f"RHS expressions '{sympy_to_str(sympy_expected)}' and" |
| 485 |
f" '{sympy_to_str(sympy_actual)}' are not identical" |
| 486 |
) |
| 487 |
except AssertionError as ex: |
| 488 |
raise AssertionError( |
| 489 |
f"Transformation for statement '{orig}' gave an unexpected result: {ex}" |
| 490 |
) |
| 491 |
|
| 492 |
|
| 493 |
@pytest.mark.codegen_independent |
| 494 |
@pytest.mark.parametrize( |
| 495 |
"s", |
| 496 |
[ |
| 497 |
"x, y = 3", |
| 498 |
"x * y", |
| 499 |
"x = ", |
| 500 |
"x.a = 3", |
| 501 |
"x++", |
| 502 |
"x[0] = 3", |
| 503 |
"dx/dt = -v / tau", |
| 504 |
"v == 3*mV", |
| 505 |
], |
| 506 |
) |
| 507 |
def test_incorrect_statements(s): |
| 508 |
with pytest.raises(ValueError): |
| 509 |
parse_statement(s) |
| 510 |
|
| 511 |
|
| 512 |
def test_clear_cache(): |
| 513 |
target = prefs.codegen.target |
| 514 |
if target == "numpy": |
| 515 |
assert "numpy" not in _cache_dirs_and_extensions |
| 516 |
with pytest.raises(ValueError): |
| 517 |
clear_cache("numpy") |
| 518 |
else: |
| 519 |
assert target in _cache_dirs_and_extensions |
| 520 |
cache_dir, _ = _cache_dirs_and_extensions[target] |
| 521 |
# Create a file that should not be there |
| 522 |
fname = os.path.join(cache_dir, "some_file.py") |
| 523 |
open(fname, "w").close() |
| 524 |
# clear_cache should refuse to clear the directory |
| 525 |
with pytest.raises(IOError): |
| 526 |
clear_cache(target) |
| 527 |
|
| 528 |
os.remove(fname) |
| 529 |
|
| 530 |
|
| 531 |
@pytest.mark.skipif( |
| 532 |
platform.system() == "Windows", |
| 533 |
reason="CC and CXX variables are ignored on Windows.", |
| 534 |
) |
| 535 |
def test_compiler_error(): |
| 536 |
# In particular on OSX with clang in a conda environment, compilation might fail. |
| 537 |
# Switching to a system gcc might help in such cases. Make sure that the error |
| 538 |
# message mentions that. |
| 539 |
old_CC = os.environ.get("CC", None) |
| 540 |
old_CXX = os.environ.get("CXX", None) |
| 541 |
os.environ.update({"CC": "non-existing-compiler", "CXX": "non-existing-compiler++"}) |
| 542 |
try: |
| 543 |
with catch_logs() as l: |
| 544 |
assert not CythonCodeObject.is_available() |
| 545 |
assert len(l) > 0 # There are additional warnings about compiler flags |
| 546 |
last_warning = l[-1] |
| 547 |
assert last_warning[1].endswith(".failed_compile_test") |
| 548 |
assert "CC" in last_warning[2] and "CXX" in last_warning[2] |
| 549 |
|
| 550 |
finally: |
| 551 |
if old_CC: |
| 552 |
os.environ["CC"] = old_CC |
| 553 |
else: |
| 554 |
del os.environ["CC"] |
| 555 |
if old_CXX: |
| 556 |
os.environ["CXX"] = old_CXX |
| 557 |
else: |
| 558 |
del os.environ["CXX"] |
| 559 |
|
| 560 |
|
| 561 |
def test_compiler_c99(): |
| 562 |
# On a user's computer, we do not know whether the compiler actually |
| 563 |
# has C99 support, so we just check whether the test does not raise an |
| 564 |
# error |
| 565 |
|
| 566 |
# The compiler check previously created spurious '-.o' files (see #1348) |
| 567 |
if os.path.exists("-.o"): |
| 568 |
os.remove("-.o") |
| 569 |
c99_support = compiler_supports_c99() |
| 570 |
assert not os.path.exists("-.o") |
| 571 |
# On our Azure test server we know that the compilers support C99 |
| 572 |
if os.environ.get("AGENT_OS", ""): |
| 573 |
assert c99_support |
| 574 |
|
| 575 |
|
| 576 |
def test_cpp_flags_support(): |
| 577 |
from distutils.ccompiler import get_default_compiler |
| 578 |
|
| 579 |
from brian2.codegen.cpp_prefs import _compiler_flag_compatibility |
| 580 |
|
| 581 |
_compiler_flag_compatibility.clear() # make sure cache is empty |
| 582 |
compiler = get_default_compiler() |
| 583 |
if compiler == "msvc": |
| 584 |
pytest.skip("No flag support check for msvc") |
| 585 |
old_prefs = prefs["codegen.cpp.extra_compile_args"] |
| 586 |
|
| 587 |
# Should always be supported |
| 588 |
prefs["codegen.cpp.extra_compile_args"] = ["-w"] |
| 589 |
_, compile_args = get_compiler_and_args() |
| 590 |
assert compile_args == prefs["codegen.cpp.extra_compile_args"] |
| 591 |
|
| 592 |
# Should never be supported and raise a warning |
| 593 |
prefs["codegen.cpp.extra_compile_args"] = ["-invalidxyz"] |
| 594 |
with catch_logs() as l: |
| 595 |
_, compile_args = get_compiler_and_args() |
| 596 |
assert len(l) == 1 and l[0][0] == "WARNING" |
| 597 |
assert compile_args == [] |
| 598 |
|
| 599 |
prefs["codegen.cpp.extra_compile_args"] = old_prefs |
| 600 |
|
| 601 |
|
| 602 |
@pytest.mark.skipif( |
| 603 |
platform.system() != "Windows", reason="MSVC flags are only relevant on Windows" |
| 604 |
) |
| 605 |
@pytest.mark.skipif( |
| 606 |
prefs["codegen.target"] == "numpy", reason="Test only relevant for compiled code" |
| 607 |
) |
| 608 |
def test_msvc_flags(): |
| 609 |
# Very basic test that flags are stored to disk |
| 610 |
import brian2.codegen.cpp_prefs as cpp_prefs |
| 611 |
|
| 612 |
user_dir = os.path.join(os.path.expanduser("~"), ".brian") |
| 613 |
flag_file = os.path.join(user_dir, "cpu_flags.txt") |
| 614 |
assert len(cpp_prefs.msvc_arch_flag) |
| 615 |
assert os.path.exists(flag_file) |
| 616 |
with open(flag_file, encoding="utf-8") as f: |
| 617 |
previously_stored_flags = json.load(f) |
| 618 |
hostname = socket.gethostname() |
| 619 |
assert hostname in previously_stored_flags |
| 620 |
assert len(previously_stored_flags[hostname]) |
| 621 |
|
| 622 |
|
| 623 |
@pytest.mark.codegen_independent |
| 624 |
@pytest.mark.parametrize( |
| 625 |
"renderer", |
| 626 |
[ |
| 627 |
NodeRenderer(), |
| 628 |
NumpyNodeRenderer(), |
| 629 |
CythonNodeRenderer(), |
| 630 |
CPPNodeRenderer(), |
| 631 |
], |
| 632 |
) |
| 633 |
def test_number_rendering(renderer): |
| 634 |
import ast |
| 635 |
|
| 636 |
for number in [0.5, np.float32(0.5), np.float64(0.5)]: |
| 637 |
# In numpy 2.0, repr(np.float64(0.5)) is 'np.float64(0.5)' |
| 638 |
node = ast.Constant(value=number) |
| 639 |
assert renderer.render_node(node) == "0.5" |
| 640 |
|
| 641 |
|
| 642 |
if __name__ == "__main__": |
| 643 |
test_auto_target() |
| 644 |
test_analyse_identifiers() |
| 645 |
test_get_identifiers_recursively() |
| 646 |
test_write_to_subexpression() |
| 647 |
test_repeated_subexpressions() |
| 648 |
test_nested_subexpressions() |
| 649 |
test_apply_loop_invariant_optimisation() |
| 650 |
test_apply_loop_invariant_optimisation_integer() |
| 651 |
test_apply_loop_invariant_optimisation_boolean() |
| 652 |
test_apply_loop_invariant_optimisation_no_optimisation() |
| 653 |
test_apply_loop_invariant_optimisation_simplification() |
| 654 |
test_apply_loop_invariant_optimisation_constant_evaluation() |
| 655 |
test_automatic_augmented_assignments() |
| 656 |
test_clear_cache() |
| 657 |
test_msvc_flags() |