### Install GeNN Build Dependencies (Legacy) Source: https://github.com/genn-team/genn/blob/master/README.md Installs the necessary build dependencies for GeNN using pip, required for legacy setup.py installations. ```bash pip install pybind11 psutil pkgconfig setuptools>=61 ``` -------------------------------- ### Create Editable GeNN Install Source: https://github.com/genn-team/genn/blob/master/docs/installation.md Create an editable installation of GeNN from a local clone of the repository. This is recommended for development purposes. ```bash git clone https://github.com/genn-team/genn.git cd genn pip install -e . ``` -------------------------------- ### Simulation Setup Source: https://github.com/genn-team/genn/blob/master/docs/tutorials/mushroom_body/4_third_layer.ipynb Configures the simulation time, time step, and other simulation-specific parameters. ```python sim_time = 1.0 # seconds dt = 1e-4 # seconds num_steps = int(sim_time / dt) # Create a simulation object sim = Example(neurons, synapses, dt) ``` -------------------------------- ### Create Editable GeNN Install with Userproject Dependencies Source: https://github.com/genn-team/genn/blob/master/docs/installation.md Create an editable installation of GeNN that includes additional dependencies required for running user projects. Clone the repository first, then install. ```bash git clone https://github.com/genn-team/genn.git cd genn pip install -e .[userproject] ``` -------------------------------- ### Build GeNN using setup.py (Legacy) Source: https://github.com/genn-team/genn/blob/master/README.md Builds and installs GeNN using the legacy setup.py script. This method is not recommended for general use. ```bash python setup.py develop ``` -------------------------------- ### Install libffi-dev on Ubuntu Source: https://github.com/genn-team/genn/blob/master/README.md Installs the development version of the libffi library on Ubuntu. This is often required for C extensions. ```bash sudo apt-get install libffi-dev ``` -------------------------------- ### Example Usage Source: https://github.com/genn-team/genn/blob/master/docs/tutorials/mnist_inference/tutorial_1.ipynb Demonstrates how to use the inference function with a sample image path. Replace 'path/to/your/digit.png' with an actual image file. ```python # Example usage: image_file = 'path/to/your/digit.png' # Replace with your image path predicted_digit, probabilities = predict_digit(image_file) print(f"Predicted digit: {predicted_digit}") print(f"Probabilities: {probabilities}") ``` -------------------------------- ### Install MNIST Library Source: https://github.com/genn-team/genn/blob/master/docs/tutorials/mnist_inference/tutorial_2.ipynb Installs the 'mnist' Python library, which is used for handling MNIST dataset operations. This command uses pip for installation. ```bash !pip install mnist ``` -------------------------------- ### Build GeNN with setup.py (Legacy) Source: https://github.com/genn-team/genn/blob/master/docs/installation.md Legacy method for building GeNN using setup.py. This is not recommended for general use but may be required for special development versions. Ensure build dependencies are installed first. ```bash pip install pybind11 psutil pkgconfig setuptools>=61 git clone https://github.com/genn-team/genn.git cd genn python setup.py develop ``` -------------------------------- ### Build Debug Version of GeNN with setup.py (Legacy) Source: https://github.com/genn-team/genn/blob/master/docs/installation.md Legacy method to build a debug version of GeNN using setup.py. This requires cloning the repository and installing build dependencies beforehand. ```bash pip install pybind11 psutil pkgconfig setuptools>=61 git clone https://github.com/genn-team/genn.git cd genn python setup.py build_ext --debug develop ``` -------------------------------- ### Basic Data Structure Example Source: https://github.com/genn-team/genn/blob/master/docs/tutorials/mushroom_body/4_third_layer.ipynb Demonstrates a simple data structure, likely for representing neural components or experimental data. No specific setup or constraints are mentioned. ```python class MushroomBody: def __init__(self): self.layers = [] def add_layer(self, layer): self.layers.append(layer) class Layer: def __init__(self, name): self.name = name self.neurons = [] def add_neuron(self, neuron): self.neurons.append(neuron) class Neuron: def __init__(self, id): self.id = id self.connections = [] def add_connection(self, connection): self.connections.append(connection) ``` -------------------------------- ### Layer Initialization Example Source: https://github.com/genn-team/genn/blob/master/docs/tutorials/mushroom_body/4_third_layer.ipynb Demonstrates the creation of a 'Layer' object with a specified name. This is a basic step in constructing the mushroom body model. ```python third_layer = Layer("Third Layer") ``` -------------------------------- ### Install Latest GeNN from GitHub using Pip Source: https://github.com/genn-team/genn/blob/master/docs/installation.md Install the latest development version of GeNN directly from its GitHub repository using pip. Ensure pip is up-to-date before running this command. ```bash pip install https://github.com/genn-team/genn/archive/refs/heads/master.zip ``` -------------------------------- ### Basic GeNN Model Simulation Source: https://github.com/genn-team/genn/blob/master/docs/simulating_networks.md Build and load a GeNN model, then simulate it for a specified number of timesteps. Ensure the model is built and loaded before starting the simulation loop. ```python model.build() model.load() while model.timestep < 100: model.step_time() ``` -------------------------------- ### Install GCC on Ubuntu Source: https://github.com/genn-team/genn/blob/master/README.md Installs the GNU Compiler Collection (GCC) version 7.5 or above on Ubuntu systems. This is a prerequisite for compiling C++ code. ```bash sudo apt-get install g++ ``` -------------------------------- ### Launch Interactive GeNN Docker Session with User Permissions Source: https://github.com/genn-team/genn/blob/master/README.md Starts an interactive GeNN Docker session, mounting the host's home directory and setting the container user's UID/GID to match the host user. This ensures correct file permissions for mounted volumes. ```bash docker run -it --gpus=all -e LOCAL_USER_ID=`id -u $USER` -e LOCAL_GROUP_ID=`id -g $USER` -v $HOME:/local_home gennteam/genn:latest ``` -------------------------------- ### Editable Install GeNN with Userproject Dependencies Source: https://github.com/genn-team/genn/blob/master/README.md Installs GeNN in editable mode and includes additional dependencies required for running user projects. ```bash pip install -e .[userproject] ``` -------------------------------- ### Install Specific GeNN Release from GitHub using Pip Source: https://github.com/genn-team/genn/blob/master/docs/installation.md Install a specific release version of GeNN (e.g., 5.3.0) from its GitHub archive using pip. This is useful for reproducible builds. ```bash pip install https://github.com/genn-team/genn/archive/refs/tags/5.3.0.zip ``` -------------------------------- ### Setup Memory Views for Model Variables Source: https://github.com/genn-team/genn/blob/master/docs/tutorials/mnist_inference/tutorial_2.ipynb Prepare memory views for input current, output spike count, and neuron voltages. These views are essential for interacting with the model's variables during simulation. ```python current_input_magnitude = current_input.vars["magnitude"] output_spike_count = neurons[-1].vars["SpikeCount"] neuron_voltages = [n.vars["V"] for n in neurons] ``` -------------------------------- ### Install PyGeNN Wheel in Google Colab Source: https://github.com/genn-team/genn/blob/master/docs/tutorials/comp_neuro_101/2_synapses.ipynb Installs the PyGeNN wheel file from Google Drive and sets the CUDA path. This is specific to Google Colab environments. ```python if "google.colab" in str(get_ipython()): !gdown 128FKTJ1GVF7TgwT9-4o7r4eWqduMYVO4 !pip install pygenn-5.4.0-cp312-cp312-linux_x86_64.whl %env CUDA_PATH=/usr/local/cuda ``` -------------------------------- ### GeNN Spike Recording Setup and Simulation Source: https://github.com/genn-team/genn/blob/master/docs/simulating_networks.md Enable spike recording for a neuron group, load the model with recording buffers, simulate timesteps, and pull recording data to the host. Spike data is accessed via the neuron group's spike_recording_data property. ```python pop.spike_recording_enabled = True model.build() model.load(num_recording_timesteps=100) while model.timestep < 100: model.step_time() model.pull_recording_buffers_from_device() spike_times, spike_ids = pop.spike_recording_data[0] ``` -------------------------------- ### Editable Install GeNN Source: https://github.com/genn-team/genn/blob/master/README.md Installs GeNN in editable mode using pip. This is useful for development as changes to the source code are immediately reflected. ```bash pip install -e . ``` -------------------------------- ### Initialize GeNNModel with Default Precision Source: https://github.com/genn-team/genn/blob/master/docs/building_networks.md Create a GeNNModel instance specifying the default precision and a unique name for your model. This is the basic setup for any GeNN simulation. ```python model = GeNNModel("float", "YourModelName") ``` -------------------------------- ### Import Necessary Modules Source: https://github.com/genn-team/genn/blob/master/docs/tutorials/mushroom_body/4_third_layer.ipynb Imports required libraries for data handling, model creation, and visualization. Ensure these are installed before running. ```python import mnist import numpy as np from copy import copy from matplotlib import pyplot as plt from pygenn import ( create_current_source_model, create_neuron_model, create_weight_update_model, init_postsynaptic, init_sparse_connectivity, init_weight_update, GeNNModel ) ``` -------------------------------- ### Neuron Activation Example Source: https://github.com/genn-team/genn/blob/master/docs/tutorials/mushroom_body/4_third_layer.ipynb Defines the 'activate' method for a 'Neuron' class. This method would typically contain the logic for how a neuron responds to input. ```python def activate(self, stimulus): # Logic to process stimulus and update neuron state pass ``` -------------------------------- ### Clone GeNN Repository Source: https://github.com/genn-team/genn/blob/master/README.md Clones the GeNN repository from GitHub. This is the first step for an editable installation or for developing GeNN. ```bash git clone https://github.com/genn-team/genn.git ``` -------------------------------- ### Download Pre-trained Weights and MNIST Test Data Source: https://github.com/genn-team/genn/blob/master/docs/tutorials/mnist_inference/tutorial_2.ipynb Downloads pre-trained weights (weights_0_1.npy and weights_1_2.npy) and MNIST test data using gdown. Ensure you have gdown installed. ```bash !gdown 1cmNL8W0QZZtn3dPHiOQnVjGAYTk6Rhpc !gdown 131lCXLEH6aTXnBZ9Nh4eJLSy5DQ6LKSF ``` -------------------------------- ### Launch Interactive GeNN Docker Session Source: https://github.com/genn-team/genn/blob/master/README.md Starts an interactive bash shell within the GeNN Docker container, enabling GPU access. This is suitable for interactive development with GeNN or PyGeNN. ```bash docker run -it --gpus=all gennteam/genn:latest ``` -------------------------------- ### Basic Neuron Model Source: https://github.com/genn-team/genn/blob/master/docs/tutorials/comp_neuro_101/1_neurons.ipynb Illustrates a simplified model of a neuron, including inputs, weights, a bias, and an activation function. This serves as a foundational example for understanding neuron computation. ```python import numpy as np def sigmoid(x): return 1 / (1 + np.exp(-x)) class Neuron: def __init__(self, weights, bias): self.weights = weights self.bias = bias def feedforward(self, inputs): # Weighted sum of inputs + bias total = np.dot(self.weights, inputs) + self.bias # Activation function return sigmoid(total) # Example usage: weights = np.array([0, 1]) # w1 = 0, w2 = 1 bias = 0 neuron = Neuron(weights, bias) inputs = np.array([2, 3]) # x1 = 2, x2 = 3 output = neuron.feedforward(inputs) print(output) ``` -------------------------------- ### Update pip Source: https://github.com/genn-team/genn/blob/master/README.md Ensures that pip is updated to the latest version before installing GeNN. This can prevent potential installation issues. ```bash pip install -U pip ``` -------------------------------- ### Initialize and Configure a Neural Network Source: https://github.com/genn-team/genn/blob/master/docs/tutorials/mushroom_body/4_third_layer.ipynb Sets up a neural network with specified parameters. Ensure all required libraries are imported before use. ```python import numpy as np import matplotlib.pyplot as plt import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader, TensorDataset from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.metrics import accuracy_score, confusion_matrix, classification_report # Set random seeds for reproducibility np.random.seed(42) torch.manual_seed(42) # Load data (replace with your actual data loading) # For demonstration, we create dummy data X = np.random.rand(100, 10) * 10 y = np.random.randint(0, 2, 100) # Split data into training and testing sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # Scale features scaler = StandardScaler() X_train = scaler.fit_transform(X_train) X_test = scaler.transform(X_test) # Convert to PyTorch tensors X_train_tensor = torch.tensor(X_train, dtype=torch.float32) y_train_tensor = torch.tensor(y_train, dtype=torch.long).unsqueeze(1) X_test_tensor = torch.tensor(X_test, dtype=torch.float32) y_test_tensor = torch.tensor(y_test, dtype=torch.long).unsqueeze(1) # Create DataLoaders train_dataset = TensorDataset(X_train_tensor, y_train_tensor) test_dataset = TensorDataset(X_test_tensor, y_test_tensor) train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True) test_loader = DataLoader(test_dataset, batch_size=32) # Define the neural network model class SimpleNN(nn.Module): def __init__(self, input_size, hidden_size, num_classes): super(SimpleNN, self).__init__() self.fc1 = nn.Linear(input_size, hidden_size) self.relu = nn.ReLU() self.fc2 = nn.Linear(hidden_size, num_classes) def forward(self, x): out = self.fc1(x) out = self.relu(out) out = self.fc2(out) return out input_size = X_train.shape[1] hidden_size = 64 num_classes = 2 model = SimpleNN(input_size, hidden_size, num_classes) # Define loss function and optimizer criterion = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(model.parameters(), lr=0.001) print("Model initialized successfully.") ``` -------------------------------- ### Build Debug Version of GeNN using setup.py (Legacy) Source: https://github.com/genn-team/genn/blob/master/README.md Builds a debug version of GeNN using the legacy setup.py script. This is useful for development and troubleshooting. ```bash python setup.py build_ext --debug develop ``` -------------------------------- ### Perform Inference and Get Predictions Source: https://github.com/genn-team/genn/blob/master/docs/tutorials/mnist_inference/tutorial_1.ipynb Uses the preprocessed image to get predictions from the loaded MNIST model. The output is a probability distribution over the 10 digits. ```python # Make a prediction predictions = model.predict(x) # Get the predicted digit predicted_digit = np.argmax(predictions[0]) confidence = np.max(predictions[0]) print(f'Predicted digit: {predicted_digit}') print(f'Confidence: {confidence:.2f}') ``` -------------------------------- ### Define Simulation Parameters Source: https://github.com/genn-team/genn/blob/master/docs/tutorials/mnist_inference/tutorial_1.ipynb Sets up key simulation parameters such as timestep, presentation duration, and input scaling. ```python # Simulation timestep of model in ms TIMESTEP = 1.0 # How many timesteps to present images for PRESENT_TIMESTEPS = 100 # How much to scale input images INPUT_CURRENT_SCALE = 1.0 / 100.0 ``` -------------------------------- ### Build and Load Model Source: https://github.com/genn-team/genn/blob/master/docs/tutorials/mnist_inference/tutorial_1.ipynb Builds the PyGeNN model and loads it with a specified number of recording timesteps. This is typically the first step before simulation. ```python model.build() model.load(num_recording_timesteps=PRESENT_TIMESTEPS) ``` -------------------------------- ### Define Simulation Parameters Source: https://github.com/genn-team/genn/blob/master/docs/tutorials/mnist_inference/tutorial_2.ipynb Sets up key simulation parameters such as timestep, presentation duration, and input current scaling. ```python TIMESTEP = 1.0 PRESENT_TIMESTEPS = 100 INPUT_CURRENT_SCALE = 1.0 / 100.0 ``` -------------------------------- ### Import Modules Source: https://github.com/genn-team/genn/blob/master/docs/tutorials/mushroom_body/1_first_layer.ipynb Imports all necessary libraries for the tutorial, including MNIST dataset handling, numerical operations, plotting, and the GeNN model. ```python import mnist import numpy as np from copy import copy from matplotlib import pyplot as plt from pygenn import create_current_source_model, init_postsynaptic, init_weight_update, GeNNModel ``` -------------------------------- ### Initialize and Configure GeNN Model Source: https://github.com/genn-team/genn/blob/master/docs/tutorials/comp_neuro_101/1_neurons.ipynb Creates a new GeNN model instance with specified precision and sets the simulation timestep. The timestep should be chosen carefully based on the model's dynamics. ```python model = GeNNModel("float", "tutorial1") model.dt = 0.1 ``` -------------------------------- ### Build PyGeNN Model and Load Weights Source: https://github.com/genn-team/genn/blob/master/docs/tutorials/mnist_inference/tutorial_2.ipynb Initializes the GeNNModel, sets the timestep, loads pre-trained weights, and defines parameters and initial states for neuron populations. ```python model = GeNNModel("float", "tutorial_2") model.dt = TIMESTEP # Load weights weights_0_1 = np.load("weights_0_1.npy") weights_1_2 = np.load("weights_1_2.npy") if_params = {"Vthr": 5.0} if_init = {"V": 0.0, "SpikeCount":0} neurons = [model.add_neuron_population("neuron0", weights_0_1.shape[0], if_model, if_params, if_init), model.add_neuron_population("neuron1", weights_0_1.shape[1], if_model, if_params, if_init), model.add_neuron_population("neuron2", weights_1_2.shape[1], if_model, if_params, if_init)] model.add_synapse_population( "synapse_0_1", "DENSE", neurons[0], neurons[1], init_weight_update("StaticPulse", {}, {"g": weights_0_1.flatten()}), init_postsynaptic("DeltaCurr")) model.add_synapse_population( "synapse_1_2", "DENSE", neurons[1], neurons[2], init_weight_update("StaticPulse", {}, {"g": weights_1_2.flatten()}), init_postsynaptic("DeltaCurr")); current_input = model.add_current_source("current_input", cs_model, neurons[0], {}, {"magnitude": 0.0}) ``` -------------------------------- ### Initialize GeNN Model and Set Time Step Source: https://github.com/genn-team/genn/blob/master/docs/tutorials/mnist_inference/tutorial_3.ipynb Creates a new GeNNModel instance with a specified precision ('float') and a unique name ('tutorial_3'). It also sets the simulation time step. ```python model = GeNNModel("float", "tutorial_3") model.dt = TIMESTEP ``` -------------------------------- ### Launch Interactive GeNN Docker Session with Volume Mount Source: https://github.com/genn-team/genn/blob/master/README.md Launches an interactive GeNN Docker session while mounting the host's home directory to '/local_home' inside the container. This allows access to host files. ```bash docker run -it --gpus=all -v $HOME:/local_home gennteam/genn:latest ``` -------------------------------- ### Set CUDA_PATH on Linux Source: https://github.com/genn-team/genn/blob/master/docs/installation.md Manually set the CUDA_PATH environment variable on Linux systems. This is necessary for GeNN to detect the CUDA installation. Ensure this command is added to your login script for persistence. ```bash export CUDA_PATH=/usr/local/cuda ``` -------------------------------- ### Define Model Parameters Source: https://github.com/genn-team/genn/blob/master/docs/tutorials/mushroom_body/1_first_layer.ipynb Sets up key simulation parameters including the time step (DT), input current scaling factor, number of projection neurons, and image presentation time. ```python # Simulation time step DT = 0.1 # Scaling factor for converting normalised image pixels to input currents (nA) INPUT_SCALE = 80.0 # Number of Projection Neurons in model (should match image size) NUM_PN = 784 # How long to present each image to model PRESENT_TIME_MS = 20.0 ``` -------------------------------- ### Build and Load Model Source: https://github.com/genn-team/genn/blob/master/docs/tutorials/mushroom_body/1_first_layer.ipynb Generate and load the model code into PyGeNN. Allocate sufficient buffer for spike recording based on simulation time and timestep. ```python # Concert present time into timesteps present_timesteps = int(round(PRESENT_TIME_MS / DT)) # Build model and load it model.build() model.load(num_recording_timesteps=present_timesteps) ``` -------------------------------- ### Create Neuron Populations and Synapses Source: https://github.com/genn-team/genn/blob/master/docs/tutorials/mushroom_body/5_testing.ipynb Initializes a GeNN model and adds various neuron populations (pn, kc, ggn, mbon) with specified parameters and initial conditions. It also sets up spike recording and defines current sources and synapse populations, including their weights and synaptic dynamics. ```python # Create model model = GeNNModel("float", "mnist_mb_testing") model.dt = DT # Create neuron populations lif_init = {"V": PN_PARAMS["Vreset"], "RefracTime": 0.0} if_init = {"V": 0.0} pn = model.add_neuron_population("pn", NUM_PN, "LIF", PN_PARAMS, lif_init) kc = model.add_neuron_population("kc", NUM_KC, "LIF", LIF_PARAMS, lif_init) ggn = model.add_neuron_population("ggn", 1, if_model, GGN_PARAMS, if_init) mbon = model.add_neuron_population("mbon", NUM_MBON, "LIF", LIF_PARAMS, lif_init) # Turn on spike recording pn.spike_recording_enabled = True kc.spike_recording_enabled = True mbon.spike_recording_enabled = True # Create current sources to deliver input to network pn_input = model.add_current_source("pn_input", cs_model, pn , {}, {"magnitude": 0.0}) # Create synapse populations kc_ggn = model.add_synapse_population("kc_ggn", "DENSE", kc, ggn, init_weight_update("StaticPulseConstantWeight", {"g": 1.0}), init_postsynaptic("DeltaCurr")) ggn_kc = model.add_synapse_population("ggn_kc", "DENSE", ggn, kc, init_weight_update("StaticPulseConstantWeight", {"g": -5.0}), init_postsynaptic("ExpCurr", {"tau": 5.0})) ``` -------------------------------- ### Build and Load Model Source: https://github.com/genn-team/genn/blob/master/docs/tutorials/mushroom_body/4_third_layer.ipynb Builds the PyGeNN model and loads it, specifying the number of recording timesteps. This is used when spike recording is not required. ```python # Convert present time into timesteps present_timesteps = int(round(PRESENT_TIME_MS / DT)) # Build model and load it model.build() model.load(num_recording_timesteps=present_timesteps) ``` -------------------------------- ### Set HIP_PATH and HIP_PLATFORM on Linux Source: https://github.com/genn-team/genn/blob/master/docs/installation.md Manually set HIP_PATH and HIP_PLATFORM environment variables for HIP installations on Linux. Specify 'nvidia' or 'amd' for HIP_PLATFORM based on your GPU. Add these to your login script for persistence. ```bash export HIP_PATH=/path/to/hip export HIP_PLATFORM='nvidia' ``` ```bash export HIP_PATH=/path/to/hip export HIP_PLATFORM='amd' ``` -------------------------------- ### Build GeNN Docker Container with Specific CUDA Version Source: https://github.com/genn-team/genn/blob/master/README.md Builds the GeNN Docker container using a specific CUDA version (e.g., 11.3) as the base image. This is useful for compatibility with host systems having older CUDA installations. ```bash docker build --build-arg BASE=11.3.0-devel-ubuntu20.04 -t genn:latest_cuda_11_3 . ``` -------------------------------- ### Initialize GeNN Model Source: https://github.com/genn-team/genn/blob/master/docs/tutorials/comp_neuro_101/2_synapses.ipynb Create a new GeNN model instance with specified precision and simulation timestep. ```python model = GeNNModel("float", "tutorial2") model.dt = 1.0 ``` -------------------------------- ### Initialize GeNNModel with Single-Threaded CPU Backend Source: https://github.com/genn-team/genn/blob/master/docs/building_networks.md Manually select the single-threaded CPU backend when initializing the GeNNModel. Use this if hardware acceleration is unavailable or not desired. ```python model = GeNNModel("float", "YourModelName", backend="single_threaded_cpu") ``` -------------------------------- ### Build and Load GeNN Model Source: https://github.com/genn-team/genn/blob/master/docs/tutorials/comp_neuro_101/2_synapses.ipynb Generate simulation code for the model and load it into PyGeNN, allocating buffer for spike recording. ```python model.build() model.load(num_recording_timesteps=1000) ``` -------------------------------- ### Build Model, Load Weights, and Create Populations Source: https://github.com/genn-team/genn/blob/master/docs/tutorials/mnist_inference/tutorial_3.ipynb Loads pre-trained weights from NumPy files and adds neuron, synapse, and current source populations to the GeNN model. It configures parameters and initial states for these populations. ```python # Load weights weights_0_1 = np.load("weights_0_1.npy") weights_1_2 = np.load("weights_1_2.npy") if_params = {"Vthr": 5.0} if_init = {"V": 0.0, "SpikeCount":0} neurons = [model.add_neuron_population("neuron0", weights_0_1.shape[0], if_model, if_params, if_init), model.add_neuron_population("neuron1", weights_0_1.shape[1], if_model, if_params, if_init), model.add_neuron_population("neuron2", weights_1_2.shape[1], if_model, if_params, if_init)] model.add_synapse_population( "synapse_0_1", "DENSE", neurons[0], neurons[1], init_weight_update("StaticPulse", {}, {"g": weights_0_1.flatten()}), init_postsynaptic("DeltaCurr")) model.add_synapse_population( "synapse_1_2", "DENSE", neurons[1], neurons[2], init_weight_update("StaticPulse", {}, {"g": weights_1_2.flatten()}), init_postsynaptic("DeltaCurr")); current_input = model.add_current_source("current_input", cs_model, neurons[0], {}, {"magnitude": 0.0}) ``` -------------------------------- ### Set Variable Memory and Push to Device Source: https://github.com/genn-team/genn/blob/master/docs/simulating_networks.md Demonstrates setting variable values directly in host memory and then pushing these changes to the GPU device. This is a common pattern for updating variable states. ```python pop.vars["V"].current_view[:] = 1.0 pop.vars["V"].push_to_device() ``` -------------------------------- ### Build and Load PyGeNN Model Source: https://github.com/genn-team/genn/blob/master/docs/tutorials/mnist_inference/tutorial_2.ipynb Generates the simulation code for the defined model and loads it into PyGeNN. No recording buffer size is specified as spike recording is not needed. ```python model.build() model.load() ``` -------------------------------- ### Basic Structure and Initialization Source: https://github.com/genn-team/genn/blob/master/docs/tutorials/mushroom_body/4_third_layer.ipynb Initializes the simulation environment and defines basic parameters for the mushroom body. ```python import numpy as np import matplotlib.pyplot as plt from genn import Example from genn.example.neuron import LIF from genn.example.synapse import StaticSynapse # Basic parameters num_neurons = 100 num_inputs = 50 # Initialize neurons and synapses neurons = LIF(num_neurons) synapses = StaticSynapse(num_inputs, num_neurons) ``` -------------------------------- ### Build and Load GeNN Model, Prepare MNIST Data Source: https://github.com/genn-team/genn/blob/master/docs/tutorials/mnist_inference/tutorial_3.ipynb Builds the GeNN model, loads it onto the target device, and prepares the MNIST test dataset. It reshapes the images and asserts compatibility with the model's input layer dimensions. ```python # Build and load our model model.build() model.load() mnist.datasets_url = "https://storage.googleapis.com/cvdf-datasets/mnist/" testing_images = mnist.test_images() testing_labels = mnist.test_labels() testing_images = np.reshape(testing_images, (testing_images.shape[0], -1)) assert testing_images.shape[1] == weights_0_1.shape[0] assert np.max(testing_labels) == (weights_1_2.shape[1] - 1) ``` -------------------------------- ### Load Model and Preprocess Data Source: https://github.com/genn-team/genn/blob/master/docs/tutorials/mnist_inference/tutorial_1.ipynb Loads a pre-trained model and prepares input data for inference. Ensure the model path is correct. ```python import numpy as np import tensorflow as tf from tensorflow.keras.models import load_model from tensorflow.keras.preprocessing import image # Load the pre-trained model model = load_model('mnist_model.h5') # Function to preprocess an image def preprocess_image(img_path): img = image.load_img(img_path, color_mode='grayscale', target_size=(28, 28)) img_array = image.img_to_array(img) img_array = np.expand_dims(img_array, axis=0) # Add batch dimension img_array /= 255.0 # Normalize pixel values to [0, 1] return img_array ``` -------------------------------- ### Enable Performance Profiling in GeNN Source: https://github.com/genn-team/genn/blob/master/docs/simulating_networks.md Enable timing measurements for simulation phases by setting `timing_enabled` to `True` before building the model. This helps in identifying performance bottlenecks. ```python model = GeNNModel("float", "profiled_model") model.timing_enabled = True # ... add populations and synapses ... model.build() model.load() ``` -------------------------------- ### Running the Simulation Source: https://github.com/genn-team/genn/blob/master/docs/tutorials/mushroom_body/4_third_layer.ipynb Executes the simulation with the defined neurons, synapses, and input current. ```python output = sim.run(input_current) ``` -------------------------------- ### Initialize Neuron Variables Source: https://github.com/genn-team/genn/blob/master/docs/tutorials/comp_neuro_101/2_synapses.ipynb Set initial values for neuron variables, such as membrane potential, using uniform distribution. ```python lif_init = {"V": init_var("Uniform", {"min": -60.0, "max": -50.0}), "RefracTime": 0.0} ``` -------------------------------- ### Import Standard Modules and PyGeNN Functionality Source: https://github.com/genn-team/genn/blob/master/docs/tutorials/mnist_inference/tutorial_3.ipynb Imports necessary libraries for the simulation, including PyGeNN components, NumPy for numerical operations, Matplotlib for plotting, and time for performance measurement. ```python import mnist import numpy as np import matplotlib.pyplot as plt from pygenn import ( create_neuron_model, create_current_source_model, create_custom_update_model, create_var_ref, init_postsynaptic, init_weight_update, GeNNModel ) from time import perf_counter from tqdm.auto import tqdm TIMESTEP = 1.0 PRESENT_TIMESTEPS = 100 INPUT_CURRENT_SCALE = 1.0 / 100.0 ``` -------------------------------- ### Download Learned Weights from Device Source: https://github.com/genn-team/genn/blob/master/docs/tutorials/mushroom_body/4_third_layer.ipynb Pulls the learned weights for the 'g' variable from the device and obtains a memory view for access. This is the first step before visualizing or saving the weights. ```python kc_mbon.vars["g"].pull_from_device() kc_mbon_g_view = kc_mbon.vars["g"].view ``` -------------------------------- ### Run Jupyter Notebooks in GeNN Docker Container Source: https://github.com/genn-team/genn/blob/master/README.md Launches a Jupyter Notebook server within the GeNN Docker container, publishing port 8080 and mounting the host's home directory. Notebooks will be created in the host's home directory, ensuring persistence. ```bash docker run --gpus=all -p 8080:8080 -e LOCAL_USER_ID=`id -u $USER` -e LOCAL_GROUP_ID=`id -g $USER` -v $HOME:/local_home gennteam/genn:latest notebook /local_home ``` -------------------------------- ### Initialize GeNN Model Source: https://github.com/genn-team/genn/blob/master/docs/tutorials/mnist_inference/tutorial_1.ipynb Initializes a new GeNNModel instance with single-precision scalar variables and specifies the output directory. ```python model = GeNNModel("float", "tutorial_1") model.dt = TIMESTEP ``` -------------------------------- ### Define Model Parameters Source: https://github.com/genn-team/genn/blob/master/docs/tutorials/mushroom_body/2_second_layer.ipynb Sets up essential parameters for the neural network simulation, including time step, input scaling, neuron counts, presentation time, and LIF neuron parameters. ```python # Simulation time step DT = 0.1 # Scaling factor for converting normalised image pixels to input currents (nA) INPUT_SCALE = 80.0 # Number of Projection Neurons in model (should match image size) NUM_PN = 784 # Number of Kenyon Cells in model (defines memory capacity) NUM_KC = 20000 # How long to present each image to model PRESENT_TIME_MS = 20.0 # Standard LIF neurons parameters LIF_PARAMS = { "C": 0.2, "TauM": 20.0, "Vrest": -60.0, "Vreset": -60.0, "Vthresh": -50.0, "Ioffset": 0.0, "TauRefrac": 2.0} # We only want PNs to spike once PN_PARAMS = copy(LIF_PARAMS) PN_PARAMS["TauRefrac"] = 100.0 ``` -------------------------------- ### Import tqdm for Progress Bars Source: https://github.com/genn-team/genn/blob/master/docs/tutorials/mushroom_body/4_third_layer.ipynb Imports the `tqdm` library, commonly used for displaying progress bars during long-running operations like training or data processing. ```python from tqdm.auto import tqdm ``` -------------------------------- ### Initialize Toeplitz Synaptic Connectivity Source: https://github.com/genn-team/genn/blob/master/docs/building_networks.md Initializes Toeplitz synaptic connectivity on the GPU. This is a specialized method for Toeplitz matrices. ```python initialise_toeplitz_synaptic_connectivity(model, sg, weight_update_model, postsynaptic_model) ``` -------------------------------- ### Initialize Dense Synaptic Connectivity Source: https://github.com/genn-team/genn/blob/master/docs/building_networks.md Initializes dense synaptic connectivity on the GPU. This method is suitable for dense connectivity matrices. ```python initialise_dense_synaptic_connectivity(model, sg, weight_update_model, postsynaptic_model) ``` -------------------------------- ### Import Core PyGeNN Libraries Source: https://github.com/genn-team/genn/blob/master/docs/tutorials/comp_neuro_101/1_neurons.ipynb Imports necessary libraries for building a GeNN model, including numpy for numerical operations and matplotlib for plotting. ```python import numpy as np import matplotlib.pyplot as plt from pygenn import GeNNModel ``` -------------------------------- ### Basic Neuron Model Simulation Source: https://github.com/genn-team/genn/blob/master/docs/tutorials/comp_neuro_101/1_neurons.ipynb This snippet demonstrates a basic simulation of a neuron's response to input. It's useful for understanding the fundamental dynamics of neuronal activity. ```python import numpy as np import matplotlib.pyplot as plt # Neuron parameters tau_m = 10e-3 # Membrane time constant (s) E_L = -70e-3 # Resting membrane potential (V) V_T = -55e-3 # Threshold potential (V) R_m = 10e6 # Membrane resistance (Ohm) # Simulation parameters dt = 1e-4 # Time step (s) T = 100e-3 # Total simulation time (s) # Input current I_in = np.zeros(int(T/dt)) I_in[int(10e-3/dt):int(90e-3/dt)] = 1.5e-9 # Constant input current (A) # Initialize membrane potential V_m = np.zeros(int(T/dt)) V_m[0] = E_L # Simulation loop for i in range(1, int(T/dt)): dV = (-(V_m[i-1] - E_L) + R_m * I_in[i-1]) / tau_m * dt V_m[i] = V_m[i-1] + dV # Plotting t = np.arange(0, T, dt) plt.figure(figsize=(10, 6)) plt.plot(t, V_m * 1e3) # Convert to mV plt.xlabel('Time (s)') plt.ylabel('Membrane Potential (mV)') plt.title('Leaky Integrate-and-Fire Neuron Response') plt.grid(True) plt.show() ``` -------------------------------- ### Build GeNN Docker Container Source: https://github.com/genn-team/genn/blob/master/README.md Builds the GeNN Docker container from the source directory. The resulting image is tagged as 'genn:latest'. ```bash make docker-build ``` -------------------------------- ### Copy Input Data to Memory View Source: https://github.com/genn-team/genn/blob/master/docs/tutorials/mnist_inference/tutorial_1.ipynb Copies the first testing image into the 'magnitude' variable's memory view, scaled by INPUT_CURRENT_SCALE. This prepares the input for the simulation. ```python current_input.vars["magnitude"].values = testing_images[0] * INPUT_CURRENT_SCALE ``` -------------------------------- ### Basic Neuron Model (Perceptron) Source: https://github.com/genn-team/genn/blob/master/docs/tutorials/comp_neuro_101/1_neurons.ipynb This snippet illustrates the mathematical formulation of a simple perceptron, a foundational model for artificial neurons. It shows how inputs are weighted, summed, and passed through an activation function. ```python import numpy as np class Perceptron: def __init__(self, input_size, activation_func=lambda x: 1 if x >= 0 else 0): self.weights = np.random.rand(input_size) * 0.1 self.bias = np.random.rand(1) * 0.1 self.activation_func = activation_func def predict(self, inputs): linear_output = np.dot(inputs, self.weights) + self.bias return self.activation_func(linear_output) # Example Usage: input_data = np.array([0.5, -0.2, 0.1]) perceptron = Perceptron(input_size=len(input_data)) prediction = perceptron.predict(input_data) print(f"Prediction: {prediction}") ``` -------------------------------- ### Import PyGeNN Libraries Source: https://github.com/genn-team/genn/blob/master/docs/tutorials/comp_neuro_101/2_synapses.ipynb Imports essential libraries for PyGeNN model creation, including numpy for numerical operations, matplotlib for plotting, and specific PyGeNN modules for model initialization. ```python import numpy as np import matplotlib.pyplot as plt from pygenn import GeNNModel, init_postsynaptic, init_sparse_connectivity, init_var, init_weight_update ``` -------------------------------- ### Compile the Model Source: https://github.com/genn-team/genn/blob/master/docs/tutorials/mnist_inference/tutorial_1.ipynb Configures the model for training by specifying the optimizer, loss function, and metrics. 'adam' is a popular optimization algorithm, and 'sparse_categorical_crossentropy' is suitable for multi-class classification with integer labels. ```python model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) ``` -------------------------------- ### Initialize GeNNModel with CUDA Backend and Specific Device Source: https://github.com/genn-team/genn/blob/master/docs/building_networks.md Initialize a GeNNModel specifying the CUDA backend and manually selecting the CUDA device ID to use. This is essential for controlling which GPU resources are utilized. ```python model = GeNNModel("float", "YourModelName", backend="cuda", manual_device_id=0) ```