Debian Codegraph @

brian2/core/preferences.py

raw
1 """
2 Brian global preferences are stored as attributes of a `BrianGlobalPreferences`
3 object ``prefs``.
4 """
5
6 import os
7 import re
8 from collections.abc import MutableMapping
9 from io import StringIO
10
11 from brian2.units.fundamentalunits import Quantity, have_same_dimensions
12 from brian2.utils.stringtools import deindent, indent
13
14 __all__ = ["PreferenceError", "BrianPreference", "prefs", "brian_prefs"]
15
16
17 def parse_preference_name(name):
18 """
19 Split a preference name into a base and end name.
20
21 Parameters
22 ----------
23 name : str
24 The full name of the preference.
25
26 Returns
27 -------
28 basename : str
29 The first part of the name up to the final ``.``.
30 endname : str
31 The last part of the name from the final ``.`` onwards.
32
33 Examples
34 --------
35 >>> parse_preference_name('core.default_float_dtype')
36 ('core', 'default_float_dtype')
37 >>> parse_preference_name('codegen.cpp.compiler')
38 ('codegen.cpp', 'compiler')
39 """
40 # parse the name
41 parts = name.split(".")
42 basename = ".".join(parts[:-1])
43 endname = parts[-1]
44 return basename, endname
45
46
47 def check_preference_name(name):
48 """
49 Make sure that a preference name is valid. This currently checks that the
50 name does not contain illegal characters and does not clash with method
51 names such as "keys" or "items".
52
53 Parameters
54 ----------
55 name : str
56 The name to check.
57
58 Raises
59 ------
60 PreferenceError
61 In case the name is invalid.
62 """
63 if not re.match("[A-Za-z][_a-zA-Z0-9]*$", name):
64 raise PreferenceError(
65 f"Illegal preference name '{name}': A preference "
66 "name can only start with a letter and only "
67 "contain letters, digits or underscore."
68 )
69 if name in dir(MutableMapping) or name in prefs.__dict__:
70 raise PreferenceError(
71 f"Illegal preference name '{name}': This is also the name of a method."
72 )
73
74
75 class PreferenceError(Exception):
76 """
77 Exception relating to the Brian preferences system.
78 """
79
80 pass
81
82
83 class DefaultValidator:
84 """
85 Default preference validator
86
87 Used by `BrianPreference` as the default validator if none is given.
88 First checks if the provided value is of the same class as the default
89 value, and then if the default is a `Quantity`, checks that the units
90 match.
91 """
92
93 def __init__(self, value):
94 self.value = value
95
96 def __call__(self, value):
97 if not isinstance(value, self.value.__class__):
98 return False
99 if isinstance(self.value, Quantity):
100 if not have_same_dimensions(self.value, value):
101 return False
102 return True
103
104
105 class BrianPreference:
106 """
107 Used for defining a Brian preference.
108
109 Parameters
110 ----------
111 default : object
112 The default value.
113 docs : str
114 Documentation for the preference value.
115 validator : func
116 A function that True or False depending on whether the preference value
117 is valid or not. If not specified, uses the `DefaultValidator` for the
118 default value provided (check if the class is the same, and for
119 `Quantity` objects, whether the units are consistent).
120 representor : func
121 A function that returns a string representation of a valid preference
122 value that can be passed to `eval`. By default, uses `repr` which
123 works in almost all cases.
124 """
125
126 def __init__(self, default, docs, validator=None, representor=repr):
127 self.representor = representor
128 if validator is None:
129 validator = DefaultValidator(default)
130 self.validator = validator
131 self.default = default
132 self.docs = docs
133
134
135 class BrianGlobalPreferences(MutableMapping):
136 """
137 Class of the ``prefs`` object.
138
139 Used for getting/setting/validating/registering preference values.
140 All preferences must be registered via `register_preferences`. To get or
141 set a preference, you can either use a dictionary-based or an
142 attribute-based interface::
143
144 prefs['core.default_float_dtype'] = float32
145 prefs.core.default_float_dtype = float32
146
147 Preferences can be read from files, see `load_preferences` and
148 `read_preference_file`. Note that `load_preferences` is called
149 automatically when Brian has finished importing.
150 """
151
152 def __init__(self):
153 self.prefs = {}
154 self.backup_prefs = {}
155 self.prefs_unvalidated = {}
156 self.pref_register = {}
157 self.eval_namespace = {}
158 exec(
159 deindent(
160 """
161 from numpy import *
162 from brian2.units import *
163 from brian2.units.stdunits import *
164 """
165 ),
166 self.eval_namespace,
167 )
168
169 def __getitem__(self, item):
170 if item in self.pref_register:
171 # This asks for a category, not a single preference
172 return BrianGlobalPreferencesView(item, self)
173 return self.prefs[item]
174
175 def __len__(self):
176 return len(self.prefs)
177
178 def __iter__(self):
179 return iter(self.prefs)
180
181 def __contains__(self, item):
182 return item in self.prefs
183
184 def __setitem__(self, name, value):
185 basename, endname = parse_preference_name(name)
186 if basename not in self.pref_register:
187 raise PreferenceError(
188 "Preference category " + basename + " is unregistered. Spelling error?"
189 )
190 prefdefs, _ = self.pref_register[basename]
191 if endname in prefdefs:
192 # do validation
193 pref = prefdefs[endname]
194 if not pref.validator(value):
195 raise PreferenceError(
196 f"Value '{value}' for preference '{name}' is invalid."
197 )
198 self.prefs[name] = value
199 if name in self.prefs_unvalidated:
200 del self.prefs_unvalidated[name]
201 else:
202 raise PreferenceError(
203 f"Preference '{name}' is unregistered. Spelling error?"
204 )
205
206 def __delitem__(self, item):
207 raise PreferenceError("Preferences cannot be deleted.")
208
209 def __getattr__(self, name):
210 if name in self.__dict__ or name.startswith("__"):
211 return super().__getattribute__(name)
212
213 # This function might get called from BrianGlobalPreferencesView with
214 # a prefixed name -- therefore the name can contain dots!
215 if name in self.pref_register:
216 # This asks for a category, not a single preference
217 return BrianGlobalPreferencesView(name, self)
218
219 basename, _ = parse_preference_name(name)
220 if len(basename) and basename not in self.pref_register:
221 raise AssertionError(
222 f"__getattr__ received basename '{basename}' which is "
223 "unregistered. This should never happen!"
224 )
225
226 try:
227 return self[name]
228 except KeyError as ex:
229 raise AttributeError(
230 f"Object of type {type(self).__name__} does not have an attribute '{ex.args[0]}'",
231 name=ex.args[0],
232 obj=self,
233 ) from ex
234
235 def __setattr__(self, name, value):
236 # Do not allow to set a category name to something else
237 if "pref_register" in self.__dict__ and name in self.pref_register:
238 raise PreferenceError("Cannot set a preference category.")
239 else:
240 MutableMapping.__setattr__(self, name, value)
241
242 def __delattr__(self, name):
243 if "pref_register" in self.__dict__ and name in self.pref_register:
244 raise PreferenceError("Cannot delete a preference category.")
245 else:
246 MutableMapping.__delattr__(self, name)
247
248 toplevel_categories = property(
249 fget=lambda self: [
250 category for category in self.pref_register if "." not in category
251 ],
252 doc="The toplevel preference categories",
253 )
254
255 def _get_docstring(self):
256 """
257 Document the toplevel categories, used as a docstring for the object.
258 """
259 s = "Preference categories:\n\n"
260 for category in self.toplevel_categories:
261 s += "** %s **\n" % category
262 _, category_doc = self.pref_register[category]
263 s += " " + category_doc + "\n\n"
264
265 return s
266
267 def __dir__(self):
268 res = dir(type(self)) + list(self.__dict__)
269 categories = self.toplevel_categories
270 res.extend(categories)
271 return res
272
273 def eval_pref(self, value):
274 """
275 Evaluate a string preference in the units namespace
276 """
277 return eval(value, self.eval_namespace)
278
279 def _set_preference(self, name, value):
280 """
281 Try to set the preference and allow for unregistered base names. This
282 method is used internally when reading preferences from the file
283 because the preferences are potentially defined in packages that are
284 not imported yet. Unvalidated preferences are safed and will be
285 validated as soon as the category is registered. `Network.run` will
286 also check for unvalidated preferences.
287 """
288 basename, _ = parse_preference_name(name)
289 if basename not in self.pref_register:
290 self.prefs_unvalidated[name] = value
291 else:
292 # go via the standard __setitem__ method
293 self[name] = value
294
295 def _backup(self):
296 """
297 Store a backup copy of the preferences to restore with `_restore`.
298 """
299 self.backup_prefs.update(**self.prefs)
300
301 def _restore(self):
302 """
303 Restore a copy of the values of the preferences backed up with `_backup`.
304 """
305 self.prefs.update(**self.backup_prefs)
306
307 def _get_one_documentation(self, basename, link_targets):
308 """
309 Document a single category of preferences.
310 """
311
312 s = ""
313 if basename not in self.pref_register:
314 raise ValueError(
315 f"No preferences under the name '{basename}' are registered"
316 )
317 prefdefs, basedoc = self.pref_register[basename]
318 s += deindent(basedoc, docstring=True).strip() + "\n\n"
319 for name in sorted(prefdefs.keys()):
320 pref = prefdefs[name]
321 name = basename + "." + name
322 linkname = name.replace("_", "-").replace(".", "-")
323 if link_targets:
324 # Make a link target
325 s += f".. _brian-pref-{linkname}:\n\n"
326 s += f"``{name}`` = ``{pref.representor(pref.default)}``\n"
327 s += indent(deindent(pref.docs, docstring=True))
328 s += "\n\n"
329 return s
330
331 def get_documentation(self, basename=None, link_targets=True):
332 """
333 Generates a string documenting all preferences with the given
334 `basename`. If no `basename` is given, all preferences are documented.
335 """
336 s = ""
337 if basename is None:
338 basenames = sorted(
339 [tuple(basename.split(".")) for basename in self.pref_register]
340 )
341 for basename in basenames:
342 lev = len(basename)
343 basename = ".".join(basename)
344 if lev == 1:
345 s += basename + "\n" + '"' * len(basename) + "\n\n"
346 else:
347 s += "**" + basename + "**\n\n"
348 s += self._get_one_documentation(basename, link_targets)
349 # for basename in self.pref_register:
350 # s += '**' + basename + '**\n\n'
351 # s += basename+'\n'+'"'*len(basename)+'\n\n'
352 # s += self._get_one_documentation(basename, link_targets)
353 else:
354 s += self._get_one_documentation(basename, link_targets)
355
356 return s
357
358 def _as_pref_file(self, valuefunc):
359 """
360 Helper function used to generate the preference file for the default or current preference values.
361 """
362 s = ""
363 for basename, (prefdefs, basedoc) in self.pref_register.items():
364 s += "#" + "-" * 79 + "\n"
365 s += (
366 "\n".join(
367 [
368 "# " + line
369 for line in deindent(basedoc, docstring=True)
370 .strip()
371 .split("\n")
372 ]
373 )
374 + "\n"
375 )
376 s += "#" + "-" * 79 + "\n\n"
377 s += "[" + basename + "]\n\n"
378 for name in sorted(prefdefs.keys()):
379 pref = prefdefs[name]
380 s += (
381 "\n".join(
382 [
383 "# " + line
384 for line in deindent(pref.docs, docstring=True)
385 .strip()
386 .split("\n")
387 ]
388 )
389 + "\n\n"
390 )
391 s += (
392 name
393 + " = "
394 + pref.representor(valuefunc(pref, basename + "." + name))
395 + "\n\n"
396 )
397 return s
398
399 def _get_defaults_as_file(self):
400 return self._as_pref_file(lambda pref, fullname: pref.default)
401
402 defaults_as_file = property(
403 fget=_get_defaults_as_file,
404 doc="Get a Brian preference doc file format string for the default preferences",
405 )
406
407 def _get_as_file(self):
408 return self._as_pref_file(lambda pref, fullname: self[fullname])
409
410 as_file = property(
411 fget=_get_as_file,
412 doc="Get a Brian preference doc file format string for the current preferences",
413 )
414
415 def read_preference_file(self, file):
416 """
417 Reads a Brian preferences file
418
419 The file format for Brian preferences is a plain text file of the form::
420
421 a.b.c = 1
422 # Comment line
423 [a]
424 b.d = 2
425 [a.b]
426 e = 3
427
428 Blank and comment lines are ignored, all others should be of one of the
429 following two forms::
430
431 key = value
432 [section]
433
434 `eval` is called on the values, so strings should be written as, e.g.
435 ``'3'`` rather than ``3``. The eval is called with all unit names
436 available.
437 Within a section, the section name is prepended to the key. So in the above
438 example, it would give the following unvalidated dictionary::
439
440 {'a.b.c': 1,
441 'a.b.d': 2,
442 'a.b.e': 3,
443 }
444
445 Parameters
446 ----------
447 file : file, str
448 The file object or filename of the preference file.
449 """
450 if isinstance(file, str):
451 filename = file
452 file = open(file)
453 else:
454 filename = repr(file)
455 lines = file.readlines()
456 file.close()
457 # remove empty lines
458 lines = [line.strip() for line in lines]
459 lines = [line for line in lines if line]
460 # Remove comments
461 lines = [line for line in lines if not line.startswith("#")]
462 bases = [] # start with no base
463 for line in lines:
464 # Match section names, which are used as a prefix for subsequent entries
465 m = re.match(r"\[([^\]]*)\]", line)
466 if m:
467 bases = m.group(1).strip().split(".")
468 continue
469 # Match entries
470 m = re.match("(.*?)=(.*)", line)
471 if m:
472 extname = m.group(1).strip()
473 value = m.group(2).strip()
474 keyname = ".".join(bases + extname.split("."))
475 self._set_preference(keyname, self.eval_pref(value))
476 continue
477 # Otherwise raise a parsing error
478 raise PreferenceError("Parsing error in preference file " + filename)
479
480 def load_preferences(self):
481 """
482 Load all the preference files, but do not validate them.
483
484 Preference files are read in the following order:
485
486 1. ``~/.brian/user_preferences`` from the user's home directory
487 2. ``./brian_preferences`` from the current directory
488
489 Files that are missing are ignored. Preferences read at each step
490 override preferences from previous steps.
491
492 See Also
493 --------
494 read_preference_file
495 """
496 user_dir = os.path.join(os.path.expanduser("~"), ".brian")
497 user_prefs = os.path.join(user_dir, "user_preferences")
498 cur_prefs = "brian_preferences"
499
500 files = [user_prefs, cur_prefs]
501 for file in files:
502 try:
503 self.read_preference_file(file)
504 except OSError:
505 pass
506
507 # The "default_preferences" file is no longer used, but we raise a
508 # warning if it is present (note that we do this after reading the
509 # preference files, since they can affect the preferences of the logger
510 # itself)
511 curdir, _ = os.path.split(__file__)
512 basedir = os.path.normpath(os.path.join(curdir, ".."))
513 default_prefs = os.path.join(basedir, "default_preferences")
514 if os.path.exists(default_prefs):
515 from brian2.utils.logger import get_logger
516
517 logger = get_logger(__name__)
518 logger.warn(
519 "Brian no longer loads preferences from the "
520 f"'default_preferences' file (in '{basedir}'). Use a "
521 "'user_preferences' file in "
522 f"'{user_dir}', "
523 "or a 'brian_preferences' file in the current "
524 "directory instead.",
525 name_suffix="deprecated_default_preferences",
526 once=True,
527 )
528
529 def reset_to_defaults(self):
530 """
531 Resets the parameters to their default values.
532 """
533 self.read_preference_file(StringIO(self.defaults_as_file))
534
535 def register_preferences(self, prefbasename, prefbasedoc, **prefs):
536 """
537 Registers a set of preference names, docs and validation functions.
538
539 Parameters
540 ----------
541 prefbasename : str
542 The base name of the preference.
543 prefbasedoc : str
544 Documentation for this base name
545 **prefs : dict of (name, `BrianPreference`) pairs
546 The preference names to be defined. The full preference name will be
547 ``prefbasename.name``, and the `BrianPreference` value is used to define
548 the default value, docs, and validation function.
549
550 Raises
551 ------
552 PreferenceError
553 If the base name is already registered.
554
555 See Also
556 --------
557 BrianPreference
558 """
559 if prefbasename in self.pref_register:
560 # During the initial import phase the same base category may be
561 # created twice, ignore that
562 previous = self.pref_register[prefbasename]
563 if not (len(previous[0]) == 0 and previous[1] == prefbasedoc):
564 raise PreferenceError(
565 "Base name " + prefbasename + " already registered."
566 )
567 # Check that the new category does not clash with a preference name of
568 # the parent category. For example, if a category "a" with the
569 # preference "b" is already registered, do not allow to register a
570 # preference category "a.b"
571 basename, category_name = parse_preference_name(prefbasename)
572 if len(basename) and basename in self.pref_register:
573 parent_preferences, _ = self.pref_register[basename]
574 if category_name in parent_preferences:
575 raise PreferenceError(
576 f"Cannot register category '{prefbasename}', "
577 f"parent category '{basename}' already has a "
578 f"preference named '{category_name}'."
579 )
580
581 self.pref_register[prefbasename] = (prefs, prefbasedoc)
582 for k, v in prefs.items():
583 fullname = prefbasename + "." + k
584 # The converse of the above check: Check that a preference name
585 # does not clash with a category
586 if fullname in self.pref_register:
587 raise PreferenceError(
588 f"Cannot register '{fullname}' as a preference, "
589 "it is already registered as a "
590 "preference category."
591 )
592 check_preference_name(k)
593 self.prefs_unvalidated[fullname] = v.default
594 self.do_validation()
595
596 # Update the docstring (a new toplevel category might have been added)
597 self.__doc__ = self._get_docstring()
598
599 def do_validation(self):
600 """
601 Validates preferences that have not yet been validated.
602 """
603 for name, value in dict(self.prefs_unvalidated).items():
604 self[name] = value
605
606 def check_all_validated(self):
607 """
608 Checks that all preferences that have been set have been validated.
609
610 Logs a warning if not. Should be called by `Network.run` or other
611 key Brian functions.
612 """
613 if len(self.prefs_unvalidated):
614 from brian2.utils.logger import get_logger
615
616 logger = get_logger(__name__)
617 logger.warn(
618 "The following preferences values have been set but "
619 "are not registered preferences:\n%s\nThis is usually "
620 "because of a spelling mistake or missing library "
621 "import." % ", ".join(self.prefs_unvalidated),
622 once=True,
623 )
624
625 def __repr__(self):
626 description = "<{classname} with top-level categories: {categories}>"
627 categories = ", ".join(
628 ['"%s"' % category for category in self.toplevel_categories]
629 )
630 return description.format(
631 classname=self.__class__.__name__, categories=categories
632 )
633
634
635 class BrianGlobalPreferencesView(MutableMapping):
636 """
637 A class allowing for accessing preferences in a subcategory. It forwards
638 requests to `BrianGlobalPreferences` and provides documentation and
639 autocompletion support for all preferences in the given category. This
640 object is used to allow accessing preferences via attributes of the
641 `prefs` object.
642
643 Parameters
644 ----------
645 basename : str
646 The name of the preference category. Has to correspond to a key in
647 `BrianGlobalPreferences.pref_register`.
648 all_prefs : `BrianGlobalPreferences`
649 A reference to the main object storing the preferences.
650 """
651
652 def __init__(self, basename, all_prefs):
653 self._basename = basename
654 self._all_prefs = all_prefs
655 self._subcategories = [
656 key for key in all_prefs.pref_register if key.startswith(basename + ".")
657 ]
658 self._preferences = list(all_prefs.pref_register[basename][0].keys())
659 self.__doc__ = all_prefs.get_documentation(
660 basename=basename, link_targets=False
661 )
662
663 _sub_preferences = property(
664 lambda self: [
665 pref[len(self._basename + ".") :]
666 for pref in self._all_prefs
667 if pref.startswith(self._basename + ".")
668 ],
669 doc="All preferences in this category and its subcategories",
670 )
671
672 def __getitem__(self, item):
673 return self._all_prefs[self._basename + "." + item]
674
675 def __setitem__(self, item, value):
676 self._all_prefs[self._basename + "." + item] = value
677
678 def __delitem__(self, item):
679 raise PreferenceError("Preferences cannot be deleted.")
680
681 def __len__(self):
682 return len(self._sub_preferences)
683
684 def __iter__(self):
685 return iter(self._sub_preferences)
686
687 def __contains__(self, item):
688 return item in self._sub_preferences
689
690 def __getattr__(self, name):
691 return getattr(self._all_prefs, self._basename + "." + name)
692
693 def __setattr__(self, name, value):
694 # Names starting with an underscore are not preferences but normal
695 # instance attributes
696 if name.startswith("_"):
697 MutableMapping.__setattr__(self, name, value)
698 else:
699 self._all_prefs[self._basename + "." + name] = value
700
701 def __delattr__(self, name):
702 # Names starting with an underscore are not preferences but normal
703 # instance attributes
704 if name.startswith("_"):
705 MutableMapping.__delattr__(self, name)
706 else:
707 del self._all_prefs[self._basename + "." + name]
708
709 def __dir__(self):
710 res = dir(type(self)) + list(self.__dict__)
711 res.extend(self._preferences)
712 res.extend(
713 [category[len(self._basename + ".") :] for category in self._subcategories]
714 )
715 return res
716
717 def __repr__(self):
718 description = '<{classname} for preference category "{category}">'
719 return description.format(
720 classname=self.__class__.__name__, category=self._basename
721 )
722
723
724 # : Object storing Brian's preferences
725 prefs = BrianGlobalPreferences()
726
727
728 # Simple class to give a useful error message when using `brian_prefs`
729 class ErrorRaiser:
730 def __getattr__(self, item):
731 raise AttributeError(
732 "The global preferences object has been renamed "
733 "from 'brian_prefs' to 'prefs'"
734 )
735
736 def __getitem__(self, item):
737 raise AttributeError(
738 "The global preferences object has been renamed "
739 "from 'brian_prefs' to 'prefs'"
740 )
741
742
743 brian_prefs = ErrorRaiser()