def test_Distance(self): """Interface check on distance calculations.""" ldict = {'elements': 'iaf_neuron', 'rows': 4, 'columns': 5} nest.ResetKernel() l = topo.CreateLayer(ldict) n = nest.GetLeaves(l)[0] # gids -> gids, all displacements must be zero here d = topo.Distance(n, n) self.assertEqual(len(d), len(n)) self.assertTrue(all([dd == 0. for dd in d])) # single gid -> gids d = topo.Distance(n[:1], n) self.assertEqual(len(d), len(n)) self.assertTrue(all([isinstance(dd, float) for dd in d])) # gids -> single gid d = topo.Distance(n, n[:1]) self.assertEqual(len(d), len(n)) self.assertTrue(all([isinstance(dd, float) for dd in d])) from numpy import array # position -> gids d = topo.Distance(array([0.0, 0.0]), n) self.assertEqual(len(d), len(n)) self.assertTrue(all([isinstance(dd, float) for dd in d])) # positions -> gids d = topo.Distance([array([0.0, 0.0])] * len(n), n) self.assertEqual(len(d), len(n)) self.assertTrue(all([isinstance(dd, float) for dd in d]))
def test_create_overlapping_patches(self): self.reset() r_loc = 0.3 p_loc = 0.5 p_r = r_loc / 2. distance = .7 num_patches = 2 p_p = 0.3 nc.create_overlapping_patches( self.torus_layer, r_loc=r_loc, p_loc=p_loc, distance=distance, num_patches=num_patches, p_p=p_p ) anchors = [tu.to_coordinates(n * 360. / float(num_patches), distance) for n in range(1, num_patches + 1)] for s in self.torus_nodes: pos_s = tp.GetPosition([s])[0] patch_centers = (np.asarray(anchors) + np.asarray(pos_s)).tolist() conn = nest.GetConnections(source=[s]) targets = [t for t in nest.GetStatus(conn, "target") if t in self.torus_nodes] for t in targets: d = tp.Distance([s], [t])[0] self.assertGreaterEqual(d, distance - p_r, "Established connection is too short") self.assertLessEqual(d, distance + p_r, "Established connection is too long") d_to_centers = list(tp.Distance(patch_centers, [t])) self.assertTrue( np.any(np.asarray(d_to_centers) <= p_r), "Node is too far from any patch center" )
def pn_fig(fig, loc, ldict, cdict, xlim=[0., .5], ylim=[0, 3.5], xticks=range(0, 51, 5), yticks=np.arange(0., 1.1, 0.2), clr='blue', label=''): nest.ResetKernel() l = tp.CreateLayer(ldict) tp.ConnectLayers(l, l, cdict) ax = fig.add_subplot(loc) rn = nest.GetLeaves(l)[0] conns = nest.GetConnections(rn) cstat = nest.GetStatus(conns) srcs = [sd['source'] for sd in cstat] tgts = [sd['target'] for sd in cstat] dist = np.array(tp.Distance(srcs, tgts)) ax.hist(dist, bins=50, histtype='stepfilled', normed=True) r = np.arange(0., 0.51, 0.01) plt.plot(r, 2 * np.pi * r * (1 - 2 * r) * 12 / np.pi, 'r-', lw=3, zorder=-10) ax.set_xlim(xlim) ax.set_ylim(ylim) """ax.set_xticks(xticks) ax.set_yticks(yticks)""" # ax.set_aspect(100, 'box') ax.set_xlabel('Source-target distance d') ax.set_ylabel('Connection probability pconn(d)')
def test_create_stimulus_based_local_connections(self): self.reset() r_loc = 0.2 connect_dict = {"rule": "pairwise_bernoulli", "p": 0.8} inh_weight = -5. cap_s = 2. nc.create_stimulus_based_local_connections( self.torus_layer, self.torus_tree, self.neuron_to_tuning_map, self.tuning_to_neuron_map, self.inh_nodes, r_loc=r_loc, inh_weight=inh_weight, connect_dict=connect_dict ) connect = nest.GetConnections(self.torus_layer) for c in connect: s = nest.GetStatus(c, "source") t = nest.GetStatus(c, "target") w = nest.GetStatus([c], "weight")[0] self.assertLessEqual(tp.Distance(s, t), r_loc) self.assertEqual(self.neuron_to_tuning_map[s], self.neuron_to_tuning_map[t]) if s in self.inh_nodes: self.assertEqual(w, inh_weight, "Inhibitory weight was not set properly") else: self.assertEqual(w, cap_s, "Excitatory weight was not set properly")
def test_create_local_circular_connections(self): self.reset() r_loc = 0.3 inh_weight = -5. cap_s = 2. connect_dict = { "rule": "pairwise_bernoulli", "p": 0.4, } nc.create_local_circular_connections( self.torus_layer, self.torus_tree, self.inh_nodes, inh_weight=inh_weight, cap_s=cap_s, connect_dict=connect_dict, r_loc=r_loc, ) connect = nest.GetConnections(self.torus_nodes) for c in connect: s = nest.GetStatus([c], "source")[0] t = nest.GetStatus([c], "target")[0] if t in self.torus_nodes: d = tp.Distance([s], [t])[0] w = nest.GetStatus([c], "weight")[0] self.assertLessEqual(d, r_loc) if s in self.inh_nodes: self.assertEqual(w, inh_weight, "Inhibitory weight was not set properly") else: self.assertEqual(w, cap_s, "Excitatory weight was not set properly")
def test_create_random_patches(self): self.reset() r_loc = 0.2 p_loc = 0.8 p_p = 0.6 num_patches = 2 d_p = r_loc cap_s = 1. nc.create_random_patches( self.torus_layer, self.inh_nodes, r_loc=r_loc, p_loc=p_loc, num_patches=num_patches, p_p=p_p, cap_s=cap_s, plot=False ) for s in self.torus_nodes: conn = nest.GetConnections(source=[s]) targets = [t for t in nest.GetStatus(conn, "target") if t in self.torus_nodes] patches = [] for t in targets: distance_s_t = tp.Distance([s], [t])[0] self.assertGreaterEqual(distance_s_t, r_loc, "Target node is too close") patch_not_existent = True for idx, patch in enumerate(patches): patch_not_existent = False for p in patch: d = tp.Distance([t], [p])[0] if d > d_p: patch_not_existent = True break if not patch_not_existent: patches[idx].add(t) patch_not_existent = False break if patch_not_existent: patches.append(set([t])) self.assertLessEqual(len(patches), num_patches, "Created too many patches")
def test_create_local_circular_connections_topology(self): self.reset() r_loc = 0.3 p_loc = 0.4 nc.create_local_circular_connections_topology(self.torus_layer, r_loc=r_loc, p_loc=p_loc) connect = nest.GetConnections(self.torus_nodes) for c in connect: s = nest.GetStatus([c], "source")[0] t = nest.GetStatus([c], "target")[0] if t in self.torus_nodes: d = tp.Distance([s], [t])[0] self.assertLessEqual(d, r_loc)
def test_create_distant_np_connections(self): self.reset() r_loc = .2 p_loc = .5 p_p = 0.5 nc.create_distant_np_connections(self.torus_layer, p_loc=p_loc, r_loc=r_loc, p_p=p_p) conn = nest.GetConnections(source=self.torus_nodes) conn = [c for c in conn if nest.GetStatus([c], "target")[0] in self.torus_nodes] for c in conn: s = nest.GetStatus([c], "source")[0] t = nest.GetStatus([c], "target")[0] d = tp.Distance([s], [t])[0] self.assertLessEqual(d, self.size_layer / 2., "Distance is too large") self.assertGreaterEqual(d, r_loc, "Distance is too low")
def makePandas(senderEvents, ctr): """ Return a pandas DataFrame (Sender, Time, Position, Distance from ctr) for the recordings of a spike detector :param senderEvents: Recordings from spike detector :param ctr: Center Element(GID) :return: Pandas dataframe with Sender, Time, Position and Distance """ senders = [int(i) for i in senderEvents['senders']] #int necessary, because GID's for tp.GetPosition. Otherwise error times = [i for i in senderEvents['times']] positions = [i for i in tp.GetPosition(senders)] if len(senders) >= 2: distances = [i for i in tp.Distance(senders, [ctr])] return pd.DataFrame({'Sender': senders, 'Time': times, 'Distance from Center': distances, 'Position': positions }) else: return pd.DataFrame({'Sender': senders, 'Time': times, 'Position': positions })
def test_create_stimulus_based_patches_random(self): self.reset() num_patches = 2 r_loc = 0.2 p_loc = 0.1 p_p = 0.4 connect_dict = {"rule": "pairwise_bernoulli", "p": 0.7} cap_s = 2. filter_patches = True nc.create_stimulus_based_patches_random( self.torus_layer, self.neuron_to_tuning_map, self.tuning_to_neuron_map, self.inh_nodes, self.torus_tree, num_patches=num_patches, r_loc=r_loc, p_loc=p_loc, p_p=p_p, cap_s=cap_s, connect_dict=connect_dict, filter_patches=filter_patches ) connect = nest.GetConnections(self.torus_nodes) for c in connect: s = nest.GetStatus([c], "source")[0] t = nest.GetStatus([c], "target")[0] if t in self.torus_nodes: d = tp.Distance([s], [t])[0] w = nest.GetStatus([c], "weight")[0] self.assertLessEqual(d, self.size_layer) self.assertGreaterEqual(d, r_loc) self.assertEqual(self.neuron_to_tuning_map[s], self.neuron_to_tuning_map[t]) self.assertEqual(w, cap_s, "The weight for patchy connections wasn't set properly")
def distance(eventSenders, distanceMin, distanceMax, distanceFrom): """ Returns ID of Sender (Firing Neuron), and related firing time for Neuron in given distance from 'distanceFrom' :param eventSenders: Events perceived from Spike Recording device :param distanceMin: Minimum distance :param distanceMax: Maximum distance :param distanceFrom: Defines from wich elemnt to take the distance from :return: event: Event ID's ts: Times of spiking """ event = [] ts = [] senders = eventSenders['senders'] times = eventSenders['times'] for i in np.arange(0, len(senders), 1): currSender = senders[i] currTime = times[i] distance = tp.Distance([currSender], [distanceFrom])[0] if (distance >= distanceMin and distance <= distanceMax): event.append(currSender) ts.append(currTime) return event, ts
# l1_children is a work-around until NEST 3.0 is released l1_children = nest.hl_api.GetChildren(l1)[0] # extract position information, transpose to list of x, y and z positions xpos, ypos, zpos = zip(*topo.GetPosition(l1_children)) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter(xpos, ypos, zpos, s=15, facecolor='b', edgecolor='none') # Gaussian connections in full volume [-0.75,0.75]**3 topo.ConnectLayers(l1, l1, {'connection_type': 'divergent', 'allow_autapses': False, 'mask': {'volume': {'lower_left': [-0.75, -0.75, -0.75], 'upper_right': [0.75, 0.75, 0.75]}}, 'kernel': {'gaussian': {'p_center': 1., 'sigma': 0.25}}}) # show connections from center element # sender shown in red, targets in green ctr = topo.FindCenterElement(l1) xtgt, ytgt, ztgt = zip(*topo.GetTargetPositions(ctr, l1)[0]) xctr, yctr, zctr = topo.GetPosition(ctr)[0] ax.scatter([xctr], [yctr], [zctr], s=40, facecolor='r', edgecolor='none') ax.scatter(xtgt, ytgt, ztgt, s=40, facecolor='g', edgecolor='g') tgts = topo.GetTargetNodes(ctr, l1)[0] d = topo.Distance(ctr, tgts) plt.figure() plt.hist(d, 25) # plt.show()
def _target_distances(self): '''Return distances from source node to connected nodes.''' connections = nest.GetConnections(source=self._driver) target_nodes = [conn[1] for conn in connections] return topo.Distance(self._driver, target_nodes)
def _distances(self): '''Return distances to all nodes in target population.''' return topo.Distance(self._driver, nest.GetLeaves(self._lt)[0])
def test_create_partially_overlapping_patches(self): self.reset() r_loc = 0.1 p_loc = 0.7 d_p = r_loc size_boxes = 0.2 num_patches = 2 num_shared_patches = 3 num_patches_replaced = 3 p_p = 0.3 nc.create_partially_overlapping_patches( self.torus_layer, r_loc=r_loc, p_loc=p_loc, size_boxes=size_boxes, num_patches=num_patches, num_shared_patches=num_shared_patches, num_patches_replaced=num_patches_replaced, p_p=p_p ) sublayer_anchors, box_mask = nc.create_distinct_sublayer_boxes(size_boxes, size_layer=self.size_layer) for anchor in sublayer_anchors: box_nodes = tp.SelectNodesByMask( self.torus_layer, anchor, mask_obj=tp.CreateMask("rectangular", specs=box_mask) ) box_patches = [] for s in box_nodes: conn = nest.GetConnections(source=[s]) targets = [t for t in nest.GetStatus(conn, "target") if t in self.torus_nodes] patch_idx = set() for t in targets: distance_anchor_t = tp.Distance([anchor], [t])[0] self.assertGreaterEqual(distance_anchor_t, r_loc, "Target node is too close to anchor") patch_not_existent = True for idx, patch in enumerate(box_patches): patch_not_existent = False ds = tp.Distance([t], list(patch)) if np.any(np.asarray(ds) > d_p): patch_not_existent = True continue if not patch_not_existent: patch_idx.add(idx) box_patches[idx].add(t) patch_not_existent = False break self.assertLessEqual(len(patch_idx), num_patches, "Created too many patches per neuron") if patch_not_existent: box_patches.append({t}) # Chose num shared patches + 1, as it can happen that patches are very close to each other # -x-x-x- ==> If all patches (x) are right next to each other the algorithm can accidentally # see the spaces in between (-) as patch as well. Then the maximum is one more than the # num of shared patches self.assertLessEqual(len(box_patches), num_shared_patches+1, "Created too many patches per box")