def test_apply_positions(self): """ NodeCollection apply with positions """ n = nest.Create('iaf_psc_alpha', positions=nest.spatial.grid([2, 2])) param = nest.spatial.distance # Single target position target = [[1., 2.], ] for source in n: source_x, source_y = nest.GetPosition(source) target_x, target_y = (target[0][0], target[0][1]) ref_distance = np.sqrt((target_x - source_x) ** 2 + (target_y - source_y)**2) self.assertEqual(param.apply(source, target), ref_distance) # Multiple target positions targets = np.array(nest.GetPosition(n)) for source in n: source_x, source_y = nest.GetPosition(source) ref_distances = np.sqrt((targets[:, 0] - source_x)**2 + (targets[:, 1] - source_y)**2) self.assertEqual(param.apply(source, list(targets)), tuple(ref_distances)) # Raises when passing source with multiple node IDs with self.assertRaises(ValueError): param.apply(n, target) # Erroneous position specification source = n[0] with self.assertRaises(nest.kernel.NESTError): param.apply(source, [[1., 2., 3.], ]) # Too many dimensions with self.assertRaises(TypeError): param.apply(source, [1., 2.]) # Not a list of lists with self.assertRaises(ValueError): # Not consistent dimensions param.apply(source, [[1., 2.], [1., 2., 3.]])
def test_GetPosition(self): """Check if GetPosition returns proper positions.""" pos = ((1.0, 0.0), (0.0, 1.0), (3.5, 1.5)) nest.ResetKernel() l = nest.Create('iaf_psc_alpha', positions=nest.spatial.free(pos)) # GetPosition of single node nodepos_exp = nest.GetPosition(l[:1]) self.assertEqual(nodepos_exp, pos[0]) nodepos_exp = nest.GetPosition(l[-1:]) self.assertEqual(nodepos_exp, pos[-1]) nodepos_exp = nest.GetPosition(l[1:2]) self.assertEqual(nodepos_exp, pos[1]) # GetPosition of all the nodes in the layer nodepos_exp = nest.GetPosition(l) for npe, npr in zip(nodepos_exp, pos): self.assertEqual(npe, npr) self.assertEqual(pos, nodepos_exp) # GetPosition on some of the node IDs nodepos_exp = nest.GetPosition(l[:2]) self.assertEqual(nodepos_exp, (pos[0], pos[1]))
def wd_fig(fig, loc, pos, cdict, sdict, what, rpos=None, xlim=[-1, 51], ylim=[0, 1], xticks=range(0, 51, 5), yticks=np.arange(0., 1.1, 0.2), clr='blue', label=''): nest.ResetKernel() l = nest.Create('iaf_psc_alpha', positions=pos) nest.Connect(l, l, cdict, sdict) ax = fig.add_subplot(loc) if rpos is None: rn = l[0] # first node else: rn = nest.FindNearestElement(l, rpos) conns = nest.GetConnections(rn) vals = np.array([c.get(what) for c in conns]) tgts = [c.get('target') for c in conns] locs = np.array([nest.GetPosition(l[l.index(t)]) for t in tgts]) ax.plot(locs[:, 0], vals, 'o', mec='none', mfc=clr, label=label) ax.set_xlim(xlim) ax.set_ylim(ylim) ax.set_xticks(xticks) ax.set_yticks(yticks)
def geometryFunction(population): positions = nest.GetPosition(population) def geometry_function(idx): return positions[idx] return geometry_function
def test_PlotLayer(self): """Test plotting layer.""" nest.ResetKernel() layer = nest.Create('iaf_psc_alpha', positions=nest.spatial.grid(shape=[3, 3], extent=[2., 2.], edge_wrap=True)) nest.PlotLayer(layer) plotted_datapoints = plt.gca().collections[-1].get_offsets().data reference_datapoints = nest.GetPosition(layer) self.assertTrue(np.allclose(plotted_datapoints, reference_datapoints))
def test_apply(self): """ NodeCollection apply """ n = nest.Create('iaf_psc_alpha', positions=nest.spatial.grid([2, 2])) param = nest.spatial.pos.x ref_positions = np.array(nest.GetPosition(n)) self.assertEqual(param.apply(n), tuple(ref_positions[:, 0])) self.assertEqual(param.apply(n[0]), (ref_positions[0, 0], )) self.assertEqual(param.apply(n[::2]), tuple(ref_positions[::2, 0])) with self.assertRaises(nest.kernel.NESTError): nest.spatial.pos.z.apply(n)
def calculate_distance(self, conns, s_nodes, t_nodes): """Calculate a reference distance between source and target nodes""" s_pos = nest.GetPosition(s_nodes) t_pos = nest.GetPosition(t_nodes) src = conns.source trgt = conns.target in_3d = len(s_pos[0]) == 3 ref_distance = [] for s, t in zip(src, trgt): x_ref = t_pos[t_nodes.index(t)][0] - s_pos[s_nodes.index(s)][0] y_ref = t_pos[t_nodes.index(t)][1] - s_pos[s_nodes.index(s)][1] z_ref = 0.0 if in_3d: z_ref = t_pos[t_nodes.index(t)][2] - s_pos[s_nodes.index(s)][2] ref_dist = math.sqrt(x_ref * x_ref + y_ref * y_ref + z_ref * z_ref) ref_distance.append(ref_dist) return tuple(ref_distance)
def test_DumpNodes(self): """Test dumping nodes.""" nest.ResetKernel() spatial_nodes = nest.Create('iaf_psc_alpha', positions=nest.spatial.grid(shape=[3, 3], extent=[2., 2.], edge_wrap=True)) filename = os.path.join(self.nest_tmpdir(), 'test_DumpNodes.out.lyr') nest.DumpLayerNodes(spatial_nodes, filename) npa = np.genfromtxt(filename) reference = np.array([[n.get('global_id')] + list(nest.GetPosition(n)) for n in spatial_nodes]) self.assertTrue(np.allclose(npa, reference)) os.remove(filename)
def test_plot_probability_kernel(self): """Plot parameter probability""" nest.ResetKernel() plot_shape = [10, 10] plot_edges = [-0.5, 0.5, -0.5, 0.5] def probability_calculation(distance): return 1 - 1.5 * distance layer = nest.Create('iaf_psc_alpha', positions=nest.spatial.grid([10, 10], edge_wrap=False)) source = layer[25] source_pos = np.array(nest.GetPosition(source)) source_x, source_y = source_pos # Calculate reference values ref_probability = np.zeros(plot_shape[::-1]) for i, x in enumerate( np.linspace(plot_edges[0], plot_edges[1], plot_shape[0])): positions = np.array([[ x, y ] for y in np.linspace(plot_edges[2], plot_edges[3], plot_shape[1]) ]) ref_distances = np.sqrt((positions[:, 0] - source_x)**2 + (positions[:, 1] - source_y)**2) values = probability_calculation(ref_distances) ref_probability[:, i] = np.maximum(np.minimum(np.array(values), 1.0), 0.0) # Create the parameter parameter = probability_calculation(nest.spatial.distance) fig, ax = plt.subplots() nest.PlotProbabilityParameter(source, parameter, ax=ax, shape=plot_shape, edges=plot_edges) self.assertEqual(len(ax.images), 1) img = ax.images[0] img_data = img.get_array().data self.assertTrue(np.array_equal(img_data, ref_probability))
def test_PlotTargets(self): """Test plotting targets.""" delta = 0.05 mask = { 'rectangular': { 'lower_left': [-delta, -2 / 3 - delta], 'upper_right': [2 / 3 + delta, delta] } } cdict = {'rule': 'pairwise_bernoulli', 'p': 1., 'mask': mask} sdict = {'synapse_model': 'stdp_synapse'} nest.ResetKernel() layer = nest.Create('iaf_psc_alpha', positions=nest.spatial.grid(shape=[3, 3], extent=[2., 2.], edge_wrap=True)) # connect layer -> layer nest.Connect(layer, layer, cdict, sdict) ctr = nest.FindCenterElement(layer) fig = nest.PlotTargets(ctr, layer) fig.gca().set_title('Plain call') plotted_datapoints = plt.gca().collections[0].get_offsets().data eps = 0.01 pos = np.array(nest.GetPosition(layer)) pos_xmask = pos[np.where(pos[:, 0] > -eps)] reference_datapoints = pos_xmask[np.where(pos_xmask[:, 1] < eps)][::-1] self.assertTrue( np.array_equal(np.sort(plotted_datapoints, axis=0), np.sort(reference_datapoints, axis=0))) fig = nest.PlotTargets(ctr, layer, mask=mask) ax = fig.gca() ax.set_title('Call with mask') self.assertGreaterEqual(len(ax.patches), 1)
# ! place shows that network construction and simulation went through. # ! Inspecting the connections actually created # ! ::::::::::::::::::::::::::::::::::::::::::: # ! The following block of messy and makeshift code plots the targets of the # ! center neuron of the B/E population in the B/E and the B/I populations. E_ctr = nest.FindCenterElement(RG_E) # get all targets, split into excitatory and inhibitory Econns = nest.GetConnections(E_ctr, RG_E, synapse_model='static_synapse') Etgts = Econns.get('target') Iconns = nest.GetConnections(E_ctr, RG_I, synapse_model='static_synapse') Itgts = Iconns.get('target') # obtain positions of targets Etpos = np.array([nest.GetPosition(RG_E[RG_E.index(tnode_id)]) for tnode_id in Etgts]) Itpos = np.array([nest.GetPosition(RG_I[RG_I.index(tnode_id)]) for tnode_id in Itgts]) # plot excitatory plt.clf() plt.subplot(121) plt.scatter(Etpos[:, 0], Etpos[:, 1]) ctrpos = nest.GetPosition(E_ctr) ax = plt.gca() ax.add_patch(plt.Circle(ctrpos, radius=0.02, zorder=99, fc='r', alpha=0.4, ec='none')) ax.add_patch( plt.Rectangle(ctrpos + np.array((-0.4, -0.2)), 0.8, 0.4, zorder=1, fc='none', ec='r', lw=3)) ax.add_patch(
""" import nest import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D nest.ResetKernel() pos = nest.spatial.free(nest.random.uniform(-0.5, 0.5), extent=[1.5, 1.5, 1.5]) l1 = nest.Create('iaf_psc_alpha', 1000, positions=pos) # visualize # extract position information, transpose to list of x, y and z positions xpos, ypos, zpos = zip(*nest.GetPosition(l1)) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter(xpos, ypos, zpos, s=15, facecolor='b') # Gaussian connections in full box volume [-0.75,0.75]**3 nest.Connect(l1, l1, {'rule': 'pairwise_bernoulli', 'p': nest.spatial_distributions.gaussian(nest.spatial.distance, std=0.25), 'allow_autapses': False, 'mask': {'box': {'lower_left': [-0.75, -0.75, -0.75], 'upper_right': [0.75, 0.75, 0.75]}}}) # show connections from center element # sender shown in red, targets in green ctr = nest.FindCenterElement(l1)
def _positions(self): """Return positions of all nodes.""" return [tuple(pos) for pos in nest.GetPosition(self._lt)]
markerfacecolor=(0.7, 0.7, 0.7), markersize=10, markeredgewidth=0, zorder=1, label='_nolegend_') plt.plot(tin_x, tin_y, 'o', markerfacecolor=(0.7, 0.7, 0.7), markersize=10, markeredgewidth=0, zorder=1, label='_nolegend_') # mark sender position with transparent red circle ctrpos = nest.GetPosition(ctr_id) plt.gca().add_patch( plt.Circle(ctrpos, radius=0.15, zorder=99, fc='r', alpha=0.4, ec='none')) # mark mask positions with open red/blue circles plt.gca().add_patch( plt.Circle(ctrpos, radius=0.5, zorder=2, fc='none', ec='b', lw=3)) plt.gca().add_patch( plt.Circle(ctrpos, radius=1.0, zorder=2, fc='none', ec='r', lw=3)) # mark layer edge plt.gca().add_patch( plt.Rectangle((-1.5, -1.5), 3.0, 3.0, zorder=1, fc='none', ec='k', lw=3)) # beautify plt.axes().set_xticks(np.arange(-1.5, 1.55, 0.5))
tgt = a[tgt_index:tgt_index + 1] # obtain list of outgoing connections for ctr spos = nest.GetTargetPositions(tgt, b)[0] spos_x = np.array([x for x, y in spos]) spos_y = np.array([y for x, y in spos]) print(spos_x) print(spos_y) # scatter-plot plt.scatter(spos_x, spos_y, 20, zorder=10) # mark sender position with transparent red circle ctrpos = np.array(nest.GetPosition(tgt)) plt.gca().add_patch( plt.Circle(ctrpos, radius=0.1, zorder=99, fc='r', alpha=0.4, ec='none')) # mark mask position with open red rectangle plt.gca().add_patch( plt.Rectangle(ctrpos - (0.2, 0.5), 0.4, 1.0, zorder=1, fc='none', ec='r', lw=3)) # mark layer edge
def _positions(self): '''Return positions of all nodes.''' return [tuple(pos) for pos in nest.GetPosition(self._lt)]