| 1 |
""" |
| 2 |
Brian 2 |
| 3 |
""" |
| 4 |
|
| 5 |
import logging |
| 6 |
import signal |
| 7 |
|
| 8 |
|
| 9 |
def _check_dependencies(): |
| 10 |
"""Check basic dependencies""" |
| 11 |
import sys |
| 12 |
|
| 13 |
missing = [] |
| 14 |
try: |
| 15 |
import numpy |
| 16 |
except ImportError as ex: |
| 17 |
sys.stderr.write(f"Importing numpy failed: '{ex}'\n") |
| 18 |
missing.append("numpy") |
| 19 |
try: |
| 20 |
import sympy |
| 21 |
except ImportError as ex: |
| 22 |
sys.stderr.write(f"Importing sympy failed: '{ex}'\n") |
| 23 |
missing.append("sympy") |
| 24 |
try: |
| 25 |
import pyparsing |
| 26 |
except ImportError as ex: |
| 27 |
sys.stderr.write(f"Importing pyparsing failed: '{ex}'\n") |
| 28 |
missing.append("pyparsing") |
| 29 |
try: |
| 30 |
import jinja2 |
| 31 |
except ImportError as ex: |
| 32 |
sys.stderr.write(f"Importing Jinja2 failed: '{ex}'\n") |
| 33 |
missing.append("jinja2") |
| 34 |
|
| 35 |
if len(missing): |
| 36 |
raise ImportError( |
| 37 |
f"Some required dependencies are missing:\n{', '.join(missing)}" |
| 38 |
) |
| 39 |
|
| 40 |
|
| 41 |
_check_dependencies() |
| 42 |
|
| 43 |
try: |
| 44 |
from pylab import * |
| 45 |
except ImportError: |
| 46 |
# Do the non-matplotlib pylab imports manually |
| 47 |
# don't let numpy's datetime hide stdlib |
| 48 |
import datetime |
| 49 |
|
| 50 |
import numpy.ma as ma |
| 51 |
from numpy import * |
| 52 |
from numpy.fft import * |
| 53 |
from numpy.linalg import * |
| 54 |
from numpy.random import * |
| 55 |
|
| 56 |
# Make sure that Brian's unit-aware functions are used, even when directly |
| 57 |
# using names prefixed with numpy or np |
| 58 |
import brian2.numpy_ as np |
| 59 |
import brian2.numpy_ as numpy |
| 60 |
|
| 61 |
try: |
| 62 |
from ._version import __version__, __version_tuple__ |
| 63 |
except ImportError: |
| 64 |
try: |
| 65 |
from setuptools_scm import get_version |
| 66 |
|
| 67 |
__version__ = get_version( |
| 68 |
root="..", |
| 69 |
relative_to=__file__, |
| 70 |
version_scheme="post-release", |
| 71 |
local_scheme="no-local-version", |
| 72 |
) |
| 73 |
__version_tuple__ = tuple(int(x) for x in __version__.split(".")[:3]) |
| 74 |
except ImportError: |
| 75 |
logging.getLogger("brian2").warning( |
| 76 |
"Cannot determine Brian version, running from source and " |
| 77 |
"setuptools_scm is not installed." |
| 78 |
) |
| 79 |
__version__ = "unknown" |
| 80 |
__version_tuple__ = (0, 0, 0) |
| 81 |
|
| 82 |
# delete some annoying names from the namespace |
| 83 |
if "x" in globals(): |
| 84 |
del x |
| 85 |
if "f" in globals(): |
| 86 |
del f |
| 87 |
if "rate" in globals(): |
| 88 |
del rate |
| 89 |
|
| 90 |
__docformat__ = "restructuredtext en" |
| 91 |
|
| 92 |
from brian2.only import * |
| 93 |
from brian2.only import test |
| 94 |
|
| 95 |
# Initialize the logging system |
| 96 |
BrianLogger.initialize() |
| 97 |
logger = get_logger(__name__) |
| 98 |
|
| 99 |
|
| 100 |
# Check the caches |
| 101 |
def _get_size_recursively(dirname): |
| 102 |
import os |
| 103 |
|
| 104 |
total_size = 0 |
| 105 |
for dirpath, _, filenames in os.walk(dirname): |
| 106 |
for fname in filenames: |
| 107 |
# When other simulations are running, files may disappear while |
| 108 |
# we walk through the directory (in particular with Cython, where |
| 109 |
# we delete the source files after compilation by default) |
| 110 |
try: |
| 111 |
size = os.path.getsize(os.path.join(dirpath, fname)) |
| 112 |
total_size += size |
| 113 |
except OSError: |
| 114 |
pass # ignore the file |
| 115 |
return total_size |
| 116 |
|
| 117 |
|
| 118 |
#: Stores the cache directory for code generation targets |
| 119 |
_cache_dirs_and_extensions = {} |
| 120 |
|
| 121 |
|
| 122 |
def check_cache(target): |
| 123 |
cache_dir, _ = _cache_dirs_and_extensions.get(target, (None, None)) |
| 124 |
if cache_dir is None: |
| 125 |
return |
| 126 |
size = _get_size_recursively(cache_dir) |
| 127 |
size_in_mb = int(round(size / 1024.0 / 1024.0)) |
| 128 |
if size_in_mb > prefs.codegen.max_cache_dir_size: |
| 129 |
logger.info( |
| 130 |
f"Cache size for target '{target}': {size_in_mb} MB.\n" |
| 131 |
f"You can call clear_cache('{target}') to delete all " |
| 132 |
"files from the cache or manually delete files in the " |
| 133 |
f"'{cache_dir}' directory." |
| 134 |
) |
| 135 |
else: |
| 136 |
logger.debug(f"Cache size for target '{target}': {size_in_mb} MB") |
| 137 |
|
| 138 |
|
| 139 |
def clear_cache(target): |
| 140 |
""" |
| 141 |
Clears the on-disk cache with the compiled files for a given code generation |
| 142 |
target. |
| 143 |
|
| 144 |
Parameters |
| 145 |
---------- |
| 146 |
target : str |
| 147 |
The code generation target (e.g. ``'cython'``) |
| 148 |
|
| 149 |
Raises |
| 150 |
------ |
| 151 |
ValueError |
| 152 |
If the given code generation target does not have an on-disk cache |
| 153 |
IOError |
| 154 |
If the cache directory contains unexpected files, suggesting that |
| 155 |
deleting it would also delete files unrelated to the cache. |
| 156 |
""" |
| 157 |
import os |
| 158 |
import shutil |
| 159 |
|
| 160 |
cache_dir, extensions = _cache_dirs_and_extensions.get(target, (None, None)) |
| 161 |
if cache_dir is None: |
| 162 |
raise ValueError(f'No cache directory registered for target "{target}".') |
| 163 |
cache_dir = os.path.abspath(cache_dir) # just to make sure... |
| 164 |
for folder, _, files in os.walk(cache_dir): |
| 165 |
for f in files: |
| 166 |
for ext in extensions: |
| 167 |
if f.endswith(ext): |
| 168 |
break |
| 169 |
else: |
| 170 |
raise OSError( |
| 171 |
f"The cache directory for target '{target}' contains " |
| 172 |
f"the file '{os.path.join(folder, f)}' of an unexpected type and " |
| 173 |
"will therefore not be removed. Delete files in " |
| 174 |
f"'{cache_dir}' manually" |
| 175 |
) |
| 176 |
if os.path.exists(cache_dir): |
| 177 |
logger.debug(f"Clearing cache for target '{target}' (directory '{cache_dir}').") |
| 178 |
shutil.rmtree(cache_dir) |
| 179 |
else: |
| 180 |
logger.debug( |
| 181 |
f"Cache for target '{target}' (directory '{cache_dir}') does not exist, nothing to clear." |
| 182 |
) |
| 183 |
|
| 184 |
|
| 185 |
def _check_caches(): |
| 186 |
from brian2.codegen.runtime.cython_rt.extension_manager import ( |
| 187 |
get_cython_cache_dir, |
| 188 |
get_cython_extensions, |
| 189 |
) |
| 190 |
|
| 191 |
for target, (dirname, extensions) in [ |
| 192 |
("cython", (get_cython_cache_dir(), get_cython_extensions())) |
| 193 |
]: |
| 194 |
_cache_dirs_and_extensions[target] = (dirname, extensions) |
| 195 |
if prefs.codegen.max_cache_dir_size > 0: |
| 196 |
check_cache(target) |
| 197 |
|
| 198 |
|
| 199 |
_check_caches() |
| 200 |
|
| 201 |
|
| 202 |
class _InterruptHandler: |
| 203 |
""" |
| 204 |
Class to turn a Ctrl+C interruption (SIGINT signal) into a `stop` signal for |
| 205 |
a running simulation (i.e., finish simulating the current time step and then |
| 206 |
stop). This handler is activated by default, but can be switched off by |
| 207 |
setting the `core.stop_on_keyboard_interrupt` preference to ``False``. |
| 208 |
Note that this will only handle interruptions during a `Network.run`, |
| 209 |
interrupting at any other time will raise a `KeyboardInterrupt` in the |
| 210 |
usual way. In case that finishing the current time step takes a long time |
| 211 |
(or hangs for some reason), interrupting with Ctrl+C a second time will |
| 212 |
force the usual interrupt, regardless of the preference setting. |
| 213 |
""" |
| 214 |
|
| 215 |
def __init__(self, previous_handler): |
| 216 |
self.previous_handler = previous_handler |
| 217 |
|
| 218 |
def __call__(self, signalnum, stack_frame): |
| 219 |
if ( |
| 220 |
not prefs.core.stop_on_keyboard_interrupt |
| 221 |
or not Network._globally_running |
| 222 |
or Network._globally_stopped |
| 223 |
): |
| 224 |
self.previous_handler(signalnum, stack_frame) |
| 225 |
else: |
| 226 |
logging.getLogger("brian2").warning( |
| 227 |
"Simulation stop requested. Press Ctrl+C again to interrupt." |
| 228 |
) |
| 229 |
Network._globally_stopped = True |
| 230 |
|
| 231 |
|
| 232 |
_int_handler = _InterruptHandler(signal.getsignal(signal.SIGINT)) |
| 233 |
signal.signal(signal.SIGINT, _int_handler) |