Debian Codegraph @

brian2/codegen/runtime/numpy_rt/templates/synapses_create_generator.py_

raw
1 {#
2 USES_VARIABLES { _synaptic_pre, _synaptic_post, N,
3 N_pre, N_post, _source_offset, _target_offset }
4 #}
5 {# WRITES_TO_READ_ONLY_VARIABLES { _synaptic_pre, _synaptic_post, N}
6 #}
7 {# ITERATE_ALL { _idx } #}
8 {% extends 'common_group.py_' %}
9
10 {% block maincode %}
11 # Only need to do the initial import once, and trying is not expensive
12 # only catching exceptions is expensive (which we just do the first time)
13 try:
14 _done_initial_import
15 except:
16 _done_initial_import = True
17 import sys as _sys
18 from numpy.random import rand as _np_rand
19 if _sys.version_info[0]==2:
20 range = xrange
21
22 from numpy.random import binomial as _binomial
23 import bisect as _bisect
24 def _sample_without_replacement(low, high, step, p=None, size=None):
25 if p == 0:
26 return _numpy.array([], dtype=_numpy.int32)
27 if p == 1:
28 return _numpy.arange(low, high, step)
29 if step > 0:
30 n = (high-low-1)//step+1
31 else:
32 n = (low-high-1)//-step+1
33 if n <= 0 or (size is not None and size == 0):
34 return _numpy.array([], dtype=_numpy.int32)
35 elif size is not None and size < 0:
36 {% if skip_if_invalid %}
37 return _numpy.array([], dtype=_numpy.int32)
38 {% else %}
39 raise IndexError(f"Requested sample size {size} is negative.")
40 {% endif %}
41 elif size is not None and size > n:
42 {% if skip_if_invalid %}
43 size = n
44 {% else %}
45 raise IndexError(f"Requested sample size {size} is bigger than the "
46 f"population size {n}.")
47 {% endif %}
48 if n == size:
49 return _numpy.arange(low, high, step)
50 if p is None:
51 if step == 1:
52 _choice = _numpy.random.choice(n, size=size, replace=False) + low
53 else:
54 _chose_from = _numpy.arange(low, high, step)
55 _choice = _numpy.random.choice(_chose_from, size=size, replace=False)
56 return _numpy.sort(_choice)
57 if n <= 1000 or p > 0.25: # based on rough profiling
58 samples, = (_np_rand(n)<p).nonzero()
59 else:
60 # use jump method
61 pconst = 1.0/_numpy.log(1-p) # this will be fine as 0<p<0.25
62 start = 0 # start will be the smallest number we can produce (with a jump of 0)
63 all_samples = [] # if we have to draw multiple times, we'll use this
64 while 1: # we potentially have to redraw random numbers multiple times
65 # this constant was determined by fairly rough and ready profiling, and can
66 # probably be improved. The idea is that the expected number of items we'll
67 # need is n*p (or (n-start)*p if we've already done up to start). We add
68 # a small proportion (this constant can probably be tweaked to be better)
69 # to reduce the number of times we need to redraw samples. Finally, we add
70 # 10 which is basically because once you get down to doing as few as this,
71 # the main factor that determines how long it takes is the Python overheads,
72 # so we should never do less than some small constant (again, another constant
73 # that can probably be tweaked).
74 m = int(_numpy.ceil((n-start)*p*1.05))+10
75 # this formula gives the jump sizes, i.e. the space between hits (where rand()<p).
76 # however it can't therefore give a jump size of 0, but we could have rand()<p for
77 # for the first array. Therefore we set start to the actual first place we'd like
78 # to see a hit minus one, allowing us to have start as the first hit.
79 jump = _numpy.array(_numpy.ceil(_numpy.log(_np_rand(m))*pconst), dtype=_numpy.int32)
80 jump[0] += start-1
81 samples = _numpy.cumsum(jump)
82 all_samples.append(samples)
83 start = samples[-1]+1 # this is the starting point for the next round
84 if start >= n:
85 break
86 if len(all_samples) > 1:
87 samples = _numpy.hstack(all_samples)
88 samples = samples[:_bisect.bisect_left(samples, n)] # only keep the ones in the range we want
89 return samples*step+low
90
91 # number of synapses in the beginning
92 _old_num_synapses = {{N}}
93 # number of synapses during the creation process
94 _cur_num_synapses = _old_num_synapses
95
96 # scalar code
97 _vectorisation_idx = 1
98 {{scalar_code['setup_iterator']|autoindent}}
99 {{scalar_code['generator_expr']|autoindent}}
100 {{scalar_code['create_cond']|autoindent}}
101 {{scalar_code['update']|autoindent}}
102
103 {# For a connect call j='k+i for k in range(0, N_post, 2) if k+i < N_post'
104 "j" is called the "result index" (and "_post_idx" the "result index array", etc.)
105 "i" is called the "outer index" (and "_pre_idx" the "outer index array", etc.)
106 "k" is called the inner variable #}
107
108 for _{{outer_index}} in range({{outer_index_size}}):
109 _raw{{outer_index_array}} = _{{outer_index}} + {{outer_index_offset}}
110 {% if not result_index_condition %}
111 {{vector_code['create_cond']|autoindent}}
112 if not _cond:
113 continue
114 {% endif %}
115 {{vector_code['setup_iterator']|autoindent}}
116 {% if iterator_func=='range' %}
117 {{inner_variable}} = _numpy.arange(_iter_low, _iter_high, _iter_step)
118 {% elif iterator_func=='sample' %}
119 {% if iterator_kwds['sample_size'] == 'fixed' %}
120 {{inner_variable}} = _sample_without_replacement(_iter_low, _iter_high, _iter_step, None, size=_iter_size)
121 {% else %}
122 {{inner_variable}} = _sample_without_replacement(_iter_low, _iter_high, _iter_step, _iter_p)
123 {% endif %}
124 {% endif %}
125
126 _vectorisation_idx = {{inner_variable}}
127 {{vector_code['generator_expr']|autoindent}}
128 _vectorisation_idx = _{{result_index}}
129 _raw{{result_index_array}} = _{{result_index}} + {{result_index_offset}}
130 {% if result_index_condition %}
131 {% if result_index_used %}
132 {# The condition could index outside of array range #}
133 {% if skip_if_invalid %}
134 if _numpy.isscalar(_{{result_index}}):
135 if _{{result_index}}<0 or _{{result_index}}>={{result_index_size}}:
136 continue
137 else:
138 _in_range = _numpy.logical_and(_{{result_index}}>=0, _{{result_index}}<{{result_index_size}})
139 _{{result_index}} = _{{result_index}}[_in_range]
140 {% else %}
141 if _numpy.isscalar(_{{result_index}}):
142 _min_val = _max_val = _{{result_index}}
143 elif _{{result_index}}.shape == (0, ):
144 continue
145 else:
146 _min_val = _numpy.min(_{{result_index}})
147 _max_val = _numpy.max(_{{result_index}})
148 if _min_val < 0:
149 # Stick to % formatting, since curly braces are used by Jinja2 already
150 raise IndexError("index {{result_index}}=%d outside allowed range from 0 to %d, and the condition refers to a post-synaptic variable" % (_min_val, {{result_index_size}}-1))
151 elif _max_val >= {{result_index_size}}:
152 raise IndexError("index {{result_index}}=%d outside allowed range from 0 to %d, and the condition refers to a post-synaptic variable" % (_max_val, {{result_index_size}}-1))
153 {% endif %}
154 {% endif %}
155 {{vector_code['create_cond']|autoindent}}
156 {% endif %}
157 {% if if_expression!='True' and result_index_condition %}
158 _{{result_index}}, _cond = _numpy.broadcast_arrays(_{{result_index}}, _cond)
159 _{{result_index}} = _{{result_index}}[_cond]
160 {% else %}
161 _{{result_index}}, {{inner_variable}} = _numpy.broadcast_arrays(_{{result_index}}, {{inner_variable}})
162 {% endif %}
163
164 {% if skip_if_invalid %}
165 if _numpy.isscalar(_{{result_index}}):
166 if _{{result_index}}<0 or _{{result_index}}>={{result_index_size}}:
167 continue
168 else:
169 _in_range = _numpy.logical_and(_{{result_index}}>=0, _{{result_index}}<{{result_index_size}})
170 _{{result_index}} = _{{result_index}}[_in_range]
171 {% elif not result_index_used %}
172 {# Otherwise, we already checked before #}
173 if _numpy.isscalar(_{{result_index}}):
174 _min_val = _max_val = _{{result_index}}
175 elif _{{result_index}}.shape == (0, ):
176 continue
177 else:
178 _min_val = _numpy.min(_{{result_index}})
179 _max_val = _numpy.max(_{{result_index}})
180 if _min_val < 0:
181 raise IndexError("index _{{result_index}}=%d outside allowed range from 0 to %d" % (_min_val, {{result_index_size}}-1))
182 elif _max_val >= {{result_index_size}}:
183 raise IndexError("index _{{result_index}}=%d outside allowed range from 0 to %d" % (_max_val, {{result_index_size}}-1))
184 {% endif %}
185
186 _vectorisation_idx = _{{result_index}}
187 _raw{{result_index_array}} = _{{result_index}} + {{result_index_offset}}
188 {{vector_code['update']|autoindent}}
189
190 if not _numpy.isscalar(_n):
191 # The "n" expression involved the target variable
192 {{result_index_array}} = {{result_index_array}}.repeat(_n[_j])
193 elif _n != 1:
194 # We have a target-independent number
195 {{result_index_array}} = {{result_index_array}}.repeat(_n)
196 _numnew = len({{result_index_array}})
197
198 _new_num_synapses = _cur_num_synapses + _numnew
199 {{_dynamic__synaptic_pre}}.resize(_new_num_synapses)
200 {{_dynamic__synaptic_post}}.resize(_new_num_synapses)
201 {{_dynamic__synaptic_pre}}[_cur_num_synapses:] = _pre_idx
202 {{_dynamic__synaptic_post}}[_cur_num_synapses:] = _post_idx
203 _cur_num_synapses += _numnew
204
205 # Resize all dependent dynamic arrays (synaptic weights, delays, etc.) and set
206 # the total number of synapses
207 _owner._resize(_cur_num_synapses)
208
209 # And update N_incoming, N_outgoing and synapse_number
210 _owner._update_synapse_numbers(_old_num_synapses)
211 {% endblock %}