Debian Codegraph @

brian2/core/names.py

raw
1 import re
2 import uuid
3
4 from brian2.core.tracking import Trackable
5 from brian2.utils.logger import get_logger
6
7 __all__ = ["Nameable"]
8
9 logger = get_logger(__name__)
10
11
12 def find_name(name, names=None):
13 """
14 Determine a unique name. If the desired ``name`` is already taken, will try
15 to use a derived ``name_1``, ``name_2``, etc.
16
17 Parameters
18 ----------
19 name : str
20 The desired name.
21 names : Iterable, optional
22 A set of names that are already taken. If not provided, will use the names
23 of all Brian objects as stored in `Nameable`.
24
25 Returns
26 -------
27 unique_name : str
28 A name based on ``name`` or ``name`` itself, unique with respect to the
29 names in ``names``.
30 """
31 if not name.endswith("*"):
32 # explicitly given names are used as given. Network.before_run (and
33 # the device in case of standalone) will check for name clashes later
34 return name
35
36 name = name[:-1]
37
38 if names is None:
39 instances = set(Nameable.__instances__())
40 allnames = {obj().name for obj in instances if hasattr(obj(), "name")}
41 else:
42 allnames = names
43
44 # Try the name without any additions first:
45 if name not in allnames:
46 return name
47
48 # Name is already taken, try _1, _2, etc.
49 i = 1
50 while f"{name}_{str(i)}" in allnames:
51 i += 1
52 return f"{name}_{str(i)}"
53
54
55 class Nameable(Trackable):
56 """
57 Base class to find a unique name for an object
58
59 If you specify a name explicitly, and it has already been taken, a
60 `ValueError` is raised. You can also specify a name with a wildcard asterisk
61 in the end, i.e. in the form ``'name*'``. It will then try ``name`` first
62 but if this is already specified, it will try ``name_1``, `name__2``, etc.
63 This is the default mechanism used by most core objects in Brian, e.g.
64 `NeuronGroup` uses a default name of ``'neurongroup*'``.
65
66 Parameters
67 ----------
68 name : str
69 An name for the object, possibly ending in ``*`` to specify that
70 variants of this name should be tried if the name (without the asterisk)
71 is already taken. If (and only if) the name for this object has already
72 been set, it is also possible to call the initialiser with ``None`` for
73 the `name` argument. This situation can arise when a class derives from
74 multiple classes that derive themselves from `Nameable` (e.g. `Group`
75 and `CodeRunner`) and their initialisers are called explicitely.
76
77 Raises
78 ------
79 ValueError
80 If the name is already taken.
81 """
82
83 def __init__(self, name):
84 if getattr(self, "_name", None) is not None and name is None:
85 # name has already been specified previously
86 return
87
88 self.assign_id()
89
90 if not isinstance(name, str):
91 raise TypeError(
92 "'name' argument has to be a string, is type "
93 f"{repr(type(name))} instead"
94 )
95 if not re.match(r"[_A-Za-z][_a-zA-Z0-9]*\*?$", name):
96 raise ValueError(f"Name {name} not valid variable name")
97
98 self._name = find_name(name)
99 logger.diagnostic(
100 f"Created object of class {self.__class__.__name__} with name {self._name}"
101 )
102
103 def assign_id(self):
104 """
105 Assign a new id to this object. Under most circumstances, this method
106 should only be called once at the creation of the object to generate a
107 unique id. In the case of the `MagicNetwork`, however, the id should
108 change when a new, independent set of objects is simulated.
109 """
110 self._id = uuid.uuid4()
111
112 name = property(
113 fget=lambda self: self._name,
114 doc="""
115 The unique name for this object.
116
117 Used when generating code. Should be an acceptable
118 variable name, i.e. starting with a letter
119 character and followed by alphanumeric characters and
120 ``_``.
121 """,
122 )
123
124 id = property(
125 fget=lambda self: self._id,
126 doc="""
127 A unique id for this object.
128
129 In contrast to names, which may be reused, the id stays
130 unique. This is used in the dependency checking to not
131 have to deal with the chore of comparing weak
132 references, weak proxies and strong references.
133 """,
134 )