### Install eFEL using pip Source: https://github.com/openbraininstitute/efel/blob/master/docs/source/installation.rst This snippet shows how to install the eFEL Python package using pip. It covers standard installation and alternative methods for users without administrator access or those using virtual environments. ```shell pip install efel ``` ```shell pip install efel --user ``` ```shell virtualenv pythonenv . ./pythonenv/bin/activate pip install git+git://github.com/BlueBrain/eFEL ``` -------------------------------- ### Compile and Install C++ eFEL Library with CMake Source: https://github.com/openbraininstitute/efel/blob/master/docs/source/installation.rst This snippet outlines the steps to build and install the C++ standalone eFEL library. It requires CMake and involves creating a build directory, configuring the installation path, and then compiling and installing the library. ```shell mkdir build_cmake cd build_cmakecmake .. -DCMAKE_INSTALL_PREFIX=YOURINSTALLDIR make install ``` -------------------------------- ### Install LaTeX Packages on Ubuntu Source: https://github.com/openbraininstitute/efel/blob/master/docs/source/developers.rst This command installs necessary LaTeX packages on Ubuntu systems for building documentation that includes PDF output. It ensures that all required LaTeX components are available. ```bash sudo apt-get install texlive-latex-base texlive-latex-extra xzdec tlmgr install helvetic ``` -------------------------------- ### Get Available eFEL Feature Names Source: https://github.com/openbraininstitute/efel/blob/master/docs/source/python_example1.rst This code retrieves a list of all eFeature names that can be calculated by the eFEL library. Note that some features require special handling and are not listed here. ```python efel.get_feature_names() ``` -------------------------------- ### Build Documentation with Makefile Source: https://github.com/openbraininstitute/efel/blob/master/docs/source/developers.rst This command invokes the 'doc' target in the Makefile to build the project's documentation. This process requires Sphinx and potentially LaTeX to be installed on your system. ```bash make doc ``` -------------------------------- ### Initialize Efel and Neuron Simulation Source: https://github.com/openbraininstitute/efel/blob/master/examples/deap/GranuleCell1/GranuleCellDeap1.ipynb Initializes the Neuron simulation environment and the Efel library. It loads standard Neuron run files and imports necessary Python modules for simulation and data analysis. This setup is crucial for running any Efel-based simulation. ```python import neuron neuron.h.load_file('stdrun.hoc') import efel import numpy as np ``` -------------------------------- ### Evolutionary Algorithm Setup with DEAP in Python Source: https://github.com/openbraininstitute/efel/blob/master/examples/deap/GranuleCell1/GranuleCellDeap1.ipynb This Python code sets up an evolutionary algorithm using the DEAP library. It defines population size, offspring size, number of generations, crossover and mutation probabilities, and parameters like ETA. It registers functions for initialization, evaluation, mating, mutation, variation, and selection within a DEAP toolbox. The setup includes custom individual creation and fitness definition, and culminates in running a checkpointed EA. ```python def main(): import random # Set random seed random.seed(1) # Set number of individuals in population POP_SIZE = 50 # Set number of individuals to create in every offspring OFFSPRING_SIZE = 50 # Total number of generation to run #NGEN = 100 NGEN = 3 # Total population size of EA ALPHA = POP_SIZE # Total parent population size of EA MU = OFFSPRING_SIZE # Total offspring size of EA LAMBDA = OFFSPRING_SIZE # Crossover, mutation probabilities CXPB = 0.7 MUTPB = 0.3 # Eta parameter of crossover / mutation parameters # Basically defines how much they 'spread' solution around # The higher this value, the more spread ETA = 10.0 # Number of parameters IND_SIZE = 12 # Number of objectives OBJ_SIZE = 13 # Bounds for the parameters LOWER = [] UPPER = [] for key, value in orig_conductances.items(): LOWER.append(value - 1.0 * abs(value)) UPPER.append(value + 1.0 * abs(value)) # Create a fitness function # By default DEAP selector will try to optimise fitness values, # so we add a -1 weight value to minise creator.create("Fitness", base.Fitness, weights=[-1.0] * OBJ_SIZE) class Individual(list): def __init__(self, *args): list.__init__(self, *args) self.time = None self.voltage = None # Create an individual that consists of a list creator.create("Individual", Individual, fitness=creator.Fitness) # Define a function that will uniformly pick an individual def uniform(lower_list, upper_list, dimensions): """Fill array """ if hasattr(lower_list, '__iter__'): return [random.uniform(lower, upper) for lower, upper in zip(lower_list, upper_list)] else: return [random.uniform(lower_list, upper_list) for _ in range(dimensions)] # Create a DEAP toolbox toolbox = base.Toolbox() # Register the 'uniform' function toolbox.register("uniformparams", uniform, LOWER, UPPER, IND_SIZE) # Register the individual format # An indiviual is create by 'creator.Individual' and parameters are initially # picked by 'uniform' toolbox.register( "Individual", tools.initIterate, creator.Individual, toolbox.uniformparams) # Register the population format. It is a list of individuals toolbox.register("population", tools.initRepeat, list, toolbox.Individual) # Register the evaluation function for the individuals # import deap_efel_eval1 toolbox.register("evaluate", evaluate) # Register the mate operator toolbox.register( "mate", deap.tools.cxSimulatedBinaryBounded, eta=ETA, low=LOWER, up=UPPER) # Register the mutation operator toolbox.register("mutate", deap.tools.mutPolynomialBounded, eta=ETA, low=LOWER, up=UPPER, indpb=0.1) # Register the variate operator toolbox.register("variate", deap.algorithms.varAnd) # Register the selector (picks parents from population) toolbox.register("select", plot_selector, selector=selIBEA) # toolbox.register("select", tools.selIBEA) # toolbox.register("select", tools.selIBEA) # Generate the population object pop = toolbox.population(n=MU) pop, hof, log, history = bluepyopt.deapext.algorithms.eaAlphaMuPlusLambdaCheckpoint( pop, toolbox, MU, CXPB, 1 - CXPB, NGEN) main() ``` -------------------------------- ### Import eFEL Module Source: https://github.com/openbraininstitute/efel/blob/master/docs/source/python_example1.rst This snippet shows the basic import statement required to use the eFEL library in a Python script. It's the first step before utilizing any of eFEL's functionalities. ```python import efel ``` -------------------------------- ### Import DEAP and BluePyOpt Tools (Python) Source: https://github.com/openbraininstitute/efel/blob/master/examples/deap/GranuleCell1/GranuleCellDeap1.ipynb Imports necessary modules from the DEAP library for evolutionary computation and BluePyOpt for neuroscientific modeling extensions. This setup is crucial for optimization tasks. ```python import deap.gp from deap import base from deap import creator from deap import tools from bluepyopt.deapext.tools import selIBEA import bluepyopt.deapext.algorithms ``` -------------------------------- ### Full DEAP efel Example Script Source: https://github.com/openbraininstitute/efel/blob/master/docs/source/deap_optimisation.rst The complete Python script for the DEAP efel project, including imports, parameter definitions, creator setup, toolbox registration, and the main execution block for the evolutionary algorithm. ```python import random import numpy import deap import deap.gp import deap.benchmarks from deap import base from deap import creator from deap import tools from deap import algorithms random.seed(1) POP_SIZE = 100 OFFSPRING_SIZE = 100 NGEN = 300 ALPHA = POP_SIZE MU = OFFSPRING_SIZE LAMBDA = OFFSPRING_SIZE CXPB = 0.7 MUTPB = 0.3 ETA = 10.0 SELECTOR = "NSGA2" IND_SIZE = 2 LOWER = [1e-8, -100.0] UPPER = [1e-4, -20.0] creator.create("Fitness", base.Fitness, weights=[-1.0] * 2) creator.create("Individual", list, fitness=creator.Fitness) def uniform(lower_list, upper_list, dimensions): """Fill array """ if hasattr(lower_list, '__iter__'): return [random.uniform(lower, upper) for lower, upper in zip(lower_list, upper_list)] else: return [random.uniform(lower_list, upper_list) for _ in range(dimensions)] toolbox = base.Toolbox() toolbox.register("uniformparams", uniform, LOWER, UPPER, IND_SIZE) toolbox.register( "Individual", tools.initIterate, creator.Individual, toolbox.uniformparams) toolbox.register("population", tools.initRepeat, list, toolbox.Individual) import deap_efel_eval1 toolbox.register("evaluate", deap_efel_eval1.evaluate) toolbox.register( "mate", deap.tools.cxSimulatedBinaryBounded, eta=ETA, low=LOWER, up=UPPER) toolbox.register("mutate", deap.tools.mutPolynomialBounded, eta=ETA, low=LOWER, up=UPPER, indpb=0.1) toolbox.register( "select", tools.selNSGA2) # Initialise the population with the size of the offspring pop = toolbox.population(n=MU) # Register statistics first_stats = tools.Statistics(key=lambda ind: ind.fitness.values[0]) second_stats = tools.Statistics(key=lambda ind: ind.fitness.values[1]) stats = tools.MultiStatistics(obj1=first_stats, obj2=second_stats) stats.register("min", numpy.min, axis=0) # Run the algorithm if __name__ == '__main__': pop, logbook = algorithms.eaMuPlusLambda( pop, toolbox, MU, LAMBDA, CXPB, MUTPB, NGEN, stats, halloffame=None) ``` -------------------------------- ### CMake Configuration for eFEL Project Source: https://github.com/openbraininstitute/efel/blob/master/efel/CMakeLists.txt This snippet shows the basic CMake configuration for the eFEL project. It sets the minimum required CMake version to 2.6, installs a file named 'DependencyV5.txt' to the 'share' directory, and includes the 'cppcore' subdirectory for additional build definitions. This is essential for compiling and setting up the project environment. ```cmake cmake_minimum_required(VERSION 2.6) install(FILES DependencyV5.txt DESTINATION share) add_subdirectory(cppcore) ``` -------------------------------- ### Clone eFEL Git Repository Source: https://github.com/openbraininstitute/efel/blob/master/docs/source/developers.rst This command clones the eFEL project from GitHub to your local machine. Ensure you have Git installed and replace 'yourgithubusername' with your actual GitHub username. ```bash git clone https://github.com/yourgithubusername/eFEL.git ``` -------------------------------- ### Run Makefile Test Target Source: https://github.com/openbraininstitute/efel/blob/master/docs/source/developers.rst This command executes the 'test' target in the Makefile. It typically installs the project and runs all associated tests to ensure code integrity and feature correctness. ```bash make test ``` -------------------------------- ### Extract eFeatures from Voltage Trace Data Source: https://github.com/openbraininstitute/efel/blob/master/docs/source/python_example1.rst This Python example demonstrates how to extract electrophysiological features from voltage trace data using eFEL. It involves loading data, preparing trace structures with time, voltage, and stimulus information, and then calling `efel.get_feature_values` to compute specified features. The output includes printing the calculated feature values. ```python """Basic example 1 for eFEL""" import efel import numpy def main(): """Main""" # Use numpy to read the trace data from the txt file data = numpy.loadtxt('example_trace1.txt') # Time is the first column time = data[:, 0] # Voltage is the second column voltage = data[:, 1] # Now we will construct the datastructure that will be passed to eFEL # A 'trace' is a dictionary trace1 = {} # Set the 'T' (=time) key of the trace trace1['T'] = time # Set the 'V' (=voltage) key of the trace trace1['V'] = voltage # Set the 'stim_start' (time at which a stimulus starts, in ms) # key of the trace # Warning: this need to be a list (with one element) trace1['stim_start'] = [700] # Set the 'stim_end' (time at which a stimulus end) key of the trace # Warning: this need to be a list (with one element) trace1['stim_end'] = [2700] # Multiple traces can be passed to the eFEL at the same time, so the # argument should be a list traces = [trace1] # Now we pass 'traces' to the efel and ask it to calculate the feature # values traces_results = efel.get_feature_values(traces, ['AP_amplitude', 'voltage_base']) # The return value is a list of trace_results, every trace_results # corresponds to one trace in the 'traces' list above (in same order) for trace_results in traces_results: # trace_result is a dictionary, with as keys the requested eFeatures for feature_name, feature_values in trace_results.items(): print("Feature %s has the following values: %s" % \ (feature_name, ', '.join([str(x) for x in feature_values]))) if __name__ == '__main__': main() ``` -------------------------------- ### Install eFEL Python Package Source: https://github.com/openbraininstitute/efel/blob/master/README.md Instructions for installing the eFEL Python package. It can be installed directly from PyPI or from the GitHub repository. ```bash # Activate python environment source ./pythonenv/bin/activate.csh # Install from PyPI pip install efel ``` ```bash # Install from GitHub repository pip install git+git://github.com/openbraininstitute/eFEL ``` -------------------------------- ### Setup Python Environment for eFEL Source: https://github.com/openbraininstitute/efel/blob/master/examples/nmc-portal/L5TTPC2.ipynb Ensures that matplotlib plots are displayed inline within the notebook environment and installs the eFEL library. It requires Python 3.9+ and pip. ```python %matplotlib inline !pip install efel import efel ``` -------------------------------- ### Install eFEL Python Package using Pip Source: https://github.com/openbraininstitute/efel/blob/master/README.md This snippet demonstrates the standard method for installing the eFEL Python package using pip. It can also be installed for user-specific directories or within a virtual environment. ```bash pip install efel ``` ```bash pip install efel --user ``` ```bash virtualenv pythonenv . ./pythonenv/bin/activate ``` -------------------------------- ### Configure Matplotlib for Plotting (Python) Source: https://github.com/openbraininstitute/efel/blob/master/examples/deap/GranuleCell1/GranuleCellDeap1.ipynb Configures Matplotlib to display plots inline and sets the figure size for better visualization. This is a standard setup for data visualization in Python environments like Jupyter notebooks. ```python %matplotlib inline import pylab pylab.rcParams['figure.figsize'] = 20, 12 from IPython import display ``` -------------------------------- ### Initialize Original Conductances Dictionary (Python) Source: https://github.com/openbraininstitute/efel/blob/master/examples/deap/GranuleCell1/GranuleCellDeap1.ipynb Initializes an OrderedDict to store the original conductance values for a neuron model. This dictionary serves as a reference for subsequent comparisons and evaluations. ```python import collections orig_conductances = collections.OrderedDict() orig_conductances['GrC_CaHVA'] = 0.00046 orig_conductances['GrC_KA'] = 0.004 orig_conductances['GrC_Lkg1'] = 5.68e-5 orig_conductances['GrG_KM'] = 0.00035 orig_conductances['Calc'] = 1.5 orig_conductances['GrC_KCa'] = 0.004 orig_conductances['GrC_Kir'] = 0.0009 orig_conductances['GrC_Lkg2'] = 2.17e-5 orig_conductances['GrC_pNa'] = 2e-5 orig_conductances['GrG_KV'] = 0.003 orig_conductances['GrG_Na'] = 0.013 orig_conductances['GrG_Nar'] = 0.0005 ``` -------------------------------- ### Create a New Git Branch for an eFeature Source: https://github.com/openbraininstitute/efel/blob/master/docs/source/developers.rst This command creates a new Git branch for developing a specific eFeature. Replace 'your_efeaturename' with a descriptive name for your new feature. ```bash git checkout -b your_efeaturename ``` -------------------------------- ### Commit and Push Changes for Pull Request Source: https://github.com/openbraininstitute/efel/blob/master/docs/source/developers.rst These commands are used to stage all changes, commit them with a message, and then push the new eFeature branch to your GitHub repository. This is a prerequisite for creating a pull request. ```bash git commit -a git push origin your_efeaturename ``` -------------------------------- ### DEAP Genetic Algorithm Setup and Parameters Source: https://github.com/openbraininstitute/efel/blob/master/docs/source/deap_optimisation.rst This Python snippet configures settings for the DEAP genetic algorithm. It imports necessary modules, defines constants for population size, number of generations, crossover and mutation probabilities, and bounds for the parameters (g_pas, e_pas). Dependencies include 'random', 'numpy', and various 'deap' modules. ```python import random import numpy import deap import deap.gp import deap.benchmarks from deap import base from deap import creator from deap import tools from deap import algorithms random.seed(1) # Population size POP_SIZE = 100 # Number of offspring in every generation OFFSPRING_SIZE = 100 # Number of generations NGEN = 300 # The parent and offspring population size are set the same MU = OFFSPRING_SIZE LAMBDA = OFFSPRING_SIZE # Crossover probability CXPB = 0.7 # Mutation probability, should sum to one together with CXPB MUTPB = 0.3 # Eta parameter of cx and mut operators ETA = 10.0 # The size of the individual is 2 (parameters g_pas and e_pas) IND_SIZE = 2 LOWER = [1e-8, -100.0] UPPER = [1e-4, -20.0] # As evolutionary algorithm we choose # NSGA2 :: SELECTOR = "NSGA2" ``` -------------------------------- ### Prepare Trace Dictionary for eFEL Source: https://github.com/openbraininstitute/efel/blob/master/examples/basic/basic_notebook1.ipynb Constructs a dictionary representing the voltage trace, which is required by the `efel.get_feature_values()` function. This dictionary includes the time vector ('T'), voltage vector ('V'), and the start and end times of the stimulus ('stim_start', 'stim_end'). ```python stim_start = 700 stim_end = 2700 trace = {'T': time, 'V': voltage, 'stim_start': [stim_start], 'stim_end': [stim_end]} ``` -------------------------------- ### Import Libraries and Setup for eFEL Source: https://github.com/openbraininstitute/efel/blob/master/examples/basic/basic_notebook1.ipynb Imports the necessary libraries including `efel`, `numpy`, `json`, and `matplotlib.pyplot`. It also configures matplotlib for inline plotting and sets the figure size. This is a prerequisite for using the eFEL library and visualizing data. ```python import efel import numpy import json %matplotlib notebook %matplotlib inline from matplotlib import pyplot as plt plt.rcParams['figure.figsize'] = 10, 10 ``` -------------------------------- ### Exponential Fitting and Plotting of Traces in Python Source: https://github.com/openbraininstitute/efel/blob/master/examples/voltage_clamp/voltage_clamp.ipynb Iterates through voltage traces, extracts relevant segments (stimulus start to end), corrects time for the start of the stimulus, and performs an exponential fit using `scipy.optimize.curve_fit`. It then plots the original trace, the fitted exponential curve, and marks the time constant. Dependencies include NumPy, SciPy, and Matplotlib. ```python for i, trace in enumerate(traces): stim_start_idx = np.argwhere(trace["T"] >= trace["stim_start"][0])[0][0] stim_end_idx = np.argwhere(trace["V"] >= np.max(trace["V"]))[0][0] # trace["stim_end"] - 1 to account for artefact if stim_end_idx < stim_start_idx or trace["T"][stim_end_idx] > trace["stim_end"][0] - 1: continue t_interval = trace["T"][stim_start_idx:stim_end_idx + 1] v_interval = trace["V"][stim_start_idx:stim_end_idx + 1] t0 = t_interval[0] t_interval_corrected = t_interval - t0 popt, _ = curve_fit(exp_fit, t_interval_corrected, v_interval) v_fit = exp_fit(t_interval_corrected, act_tau_efel[i], popt[1], popt[2]) plt.plot(trace["T"], trace["V"], c="red") plt.plot(t_interval, v_fit, "--", c="black", lw=3) t_tau = popt[0] + t0 plt.plot(t_tau, exp_fit(popt[0], *popt), 'o', color='black', markersize=12) plt.xlim(90, 170) ``` -------------------------------- ### Compare Electrophysiological Features (Python) Source: https://github.com/openbraininstitute/efel/blob/master/examples/deap/GranuleCell1/GranuleCellDeap1.ipynb Defines a function `compare_features` that calculates the difference between original and new electrophysiological features. It returns a list of objective values representing the discrepancies. ```python def compare_features(orig_features, new_features): obj_values = [] for step_number in orig_features: for feature_name, feature_value in orig_features[step_number].items(): if feature_value is not None: # print new_features # print step_number, feature_name if new_features[step_number][feature_name] is None: ``` -------------------------------- ### Extract Electrophysiological Features (Python) Source: https://github.com/openbraininstitute/efel/blob/master/examples/deap/GranuleCell1/GranuleCellDeap1.ipynb Defines a function `get_features` that simulates neuron steps using provided conductances and extracts key electrophysiological features using the `efel` library. It returns feature values, times, and voltages for each simulation step. ```python def get_features(conductances): import GranuleCell1 as grcsteps import collections feature_values = collections.defaultdict(dict) traces = [] times = [] voltages = [] for step_number in range(3): time, voltage = grcsteps.steps(step_number, conductances) trace = {} # dictionary with time, voltage start and end vectors. trace['T'] = time trace['V'] = voltage trace['stim_start'] = [100] trace['stim_end'] = [500] traces = [trace] result = efel.get_feature_values( traces, [ 'voltage_base', 'spike_count', 'min_voltage_between_spikes', 'AP_height', 'steady_state_voltage_stimend']) for feature_name, feature_list in result[0].items(): if feature_list is not None and len(feature_list) > 0: feature_values[step_number][ feature_name] = np.mean(feature_list) else: feature_values[step_number][feature_name] = None times.append(time) voltages.append(voltage) return feature_values, times, voltages orig_features, orig_times, orig_voltages = get_features(orig_conductances) ``` -------------------------------- ### Prepare Model Directory and Compile Mechanisms Source: https://github.com/openbraininstitute/efel/blob/master/examples/nmc-portal/L5TTPC2.ipynb Changes the current working directory to the extracted model package directory and compiles the Neuron mechanisms using 'nrnivmodl'. This step is essential for the Neuron simulator to correctly interpret the model's components. It requires a correctly installed version of Neuron with Python support. ```python import os os.chdir('L5_TTPC2_cADpyr232_1') !nrnivmodl ./mechanisms ``` -------------------------------- ### CMake Build Configuration for eFEL Library Source: https://github.com/openbraininstitute/efel/blob/master/efel/cppcore/CMakeLists.txt This snippet configures the CMake build system for the eFEL project. It sets the C++ standard, defines source files, compiler flags, and manages the installation of both static and shared libraries along with header files. ```cmake cmake_minimum_required(VERSION 3.12) # Set C++ standard set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) set(CMAKE_BUILD_TYPE Debug) set(FEATURESRCS Utils.cpp BasicFeatures.cpp SpikeEvent.cpp SpikeShape.cpp Subthreshold.cpp FillFptrTable.cpp DependencyTree.cpp cfeature.cpp mapoperations.cpp) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra") add_library(efelStatic ${FEATURESRCS}) set_target_properties(efelStatic PROPERTIES OUTPUT_NAME efel) install(TARGETS efelStatic ARCHIVE DESTINATION lib) add_library(efel SHARED ${FEATURESRCS}) install(TARGETS efel LIBRARY DESTINATION lib) install(FILES cfeature.h FillFptrTable.h BasicFeatures.h SpikeEvent.h SpikeShape.h Subthreshold.h mapoperations.h Utils.h DependencyTree.h eFELLogger.h EfelExceptions.h types.h DESTINATION include) ``` -------------------------------- ### DEAP Multi-Statistics Setup for Optimization Source: https://github.com/openbraininstitute/efel/blob/master/docs/source/deap_optimisation.rst Configures multi-objective statistics to track minimum values for two objectives. It utilizes DEAP's Statistics and MultiStatistics classes, along with NumPy for aggregation. Input is expected to be individual fitness values. ```python first_stats = tools.Statistics(key=lambda ind: ind.fitness.values[0]) second_stats = tools.Statistics(key=lambda ind: ind.fitness.values[1]) stats = tools.MultiStatistics(obj1=first_stats, obj2=second_stats) stats.register("min", numpy.min, axis=0) ``` -------------------------------- ### Plot Population and Best Individual Traces (Python) Source: https://github.com/openbraininstitute/efel/blob/master/examples/deap/GranuleCell1/GranuleCellDeap1.ipynb Implements a `plot_selector` function that visualizes the traces of a population of neuron models, highlights the best individual, and displays feature errors. It uses Matplotlib for plotting and IPython display for live updates. ```python def plot_selector(population, k, selector=None, **kwargs): for index in range(3): pylab.subplot(4, 1, index+1) pylab.cla() for ind in population: time = ind.times[index] voltage = ind.voltages[index] pylab.plot(time, voltage, color='black', alpha=0.05) import operator best_ind = min(population, key=operator.attrgetter("tot_fitness")) # print best_ind, best_ind.fitness time = best_ind.times[index] voltage = best_ind.voltages[index] # target_voltage1 = best_ind.target_voltage1 # target_voltage2 = best_ind.target_voltage2 pylab.plot(orig_times[index], orig_voltages[index], color='blue', linewidth=3) pylab.plot(time, voltage, color='red', linewidth=3) # pylab.plot(time, numpy.ones(len(time))*target_voltage1, '--', color='black') # pylab.plot(time, numpy.ones(len(time))*target_voltage2, '--', color='black') pylab.ylim(-100, 50) pylab.xlabel('Time (ms)') pylab.ylabel('Membrane voltage (mv)') pylab.subplot(4, 1, 4) pylab.cla() # for ind in population: # pylab.plot([ind.fitness.values[0]], [ind.fitness.values[1]], 'o', color='grey', alpha=0.2, markersize=15) # pylab.plot([best_ind.fitness.values[0]], [best_ind.fitness.values[1]], 'o', color='red', markersize=15) pylab.bar(range(len(best_ind.fitness.values)), best_ind.fitness.values, color='red') pylab.ylim(0, 10) pylab.ylabel('Feature errors') pylab.xlabel('Features') display.clear_output(wait=True) pylab.draw() display.display(pylab.gcf()) pylab.pause(0.5) selected_pop = selector(population, k, **kwargs) return selected_pop ``` -------------------------------- ### Prepare Inactivation Traces (100-1600ms interval) for eFEL Source: https://github.com/openbraininstitute/efel/blob/master/examples/voltage_clamp/voltage_clamp.ipynb This Python code prepares inactivation traces for eFEL, specifically setting the stimulus interval for computing the inactivation time constant. The stimulus start is set to 100 ms and the end to 1600 ms. ```python traces = [] rep_name = "repetition1" exp_type = "Inactivation" for idx in range(len(data[exp_type][rep_name]["dt"])): trace = {} i = data[exp_type][rep_name]["current"][:,idx] t = np.arange(i.size) * data[exp_type][rep_name]["dt"][idx] # efel expects ms: s -> ms t = t * 1000.0 trace["T"] = t trace["V"] = i # trick: input current as if it was voltage trace["stim_start"] = [100] trace["stim_end"] = [1600] traces.append(trace) ``` -------------------------------- ### Get Documentation for a Specific eFEL Feature (peak_to_valley) Source: https://github.com/openbraininstitute/efel/blob/master/examples/extracellular/extrafeats_example.ipynb Demonstrates how to use Python's built-in `help()` function to access the docstring for a specific extracellular feature, in this case, `peak_to_valley`. This provides details on the function's purpose, parameters, and return values. ```python help(extrafeats.peak_to_valley) ``` -------------------------------- ### Load Data from Neo-supported Formats Source: https://context7.com/openbraininstitute/efel/llms.txt Loads electrophysiology data from files supported by the Neo library, such as .nwb, .abf, and .axon. It allows optional specification of stimulus start and end times if not encoded in the file. The loaded data is structured as [blocks][segments][traces], with each trace ready for feature extraction. ```python import efel efel_data = efel.io.load_neo_file( 'recording.nwb', stim_start=100, # Optional if encoded in file stim_end=500 # Optional if encoded in file ) # Data structure: [blocks][segments][traces] for block in efel_data: for segment in block: for trace in segment: # Each trace is ready for eFEL results = efel.get_feature_values([trace], ['AP_amplitude']) print(results) ``` -------------------------------- ### Initialize CircuitSimulation with Configuration Source: https://github.com/openbraininstitute/efel/blob/master/examples/sonata-network/sonata-network.ipynb Initializes a `CircuitSimulation` object from BlueCellulab using a provided JSON configuration file. This object will be used to set up and run the network simulation. The configuration file specifies network details, stimuli, and reporting settings. ```python simulation_config = Path("./") / "simulation_config.json" with open(simulation_config) as f: simulation_config_dict = json.load(f) sim = CircuitSimulation(simulation_config) ``` -------------------------------- ### Load Neo File with Explicit Stimulus Times (Python) Source: https://github.com/openbraininstitute/efel/blob/master/docs/source/neoIO_example.rst Loads data from a neurophysiology file (e.g., .abf) using efel.io.load_neo_file(). This function reads data supported by the Neo package and formats it for eFEL. It requires explicit specification of stimulus start and end times. The function returns data structured as a list of lists, representing segments and traces within those segments. ```python import efel data = efel.io.load_neo_file("path/first_file.abf", stim_start=200, stim_end=700) ``` -------------------------------- ### Extract Interval Data for Exponential Fit Source: https://github.com/openbraininstitute/efel/blob/master/examples/voltage_clamp/voltage_clamp.ipynb This Python code snippet prepares data intervals from traces for performing an exponential fit. It identifies time and voltage points within the specified stimulus start and end times, excluding the last data point to avoid artifacts. ```python for i, trace in enumerate(traces): # - 1 to account for artifacts interval_indices = np.where((trace["T"] >= trace["stim_start"][0]) & (trace["T"] < trace["stim_end"][0] - 1)) t_interval = trace["T"][interval_indices] v_interval = trace["V"][interval_indices] ``` -------------------------------- ### Load and Preprocess Deactivation Traces for eFEL Source: https://github.com/openbraininstitute/efel/blob/master/examples/voltage_clamp/voltage_clamp.ipynb Loads deactivation experiment data and prepares it into a list of traces compatible with the eFEL library. Each trace is structured with time ('T'), current ('V'), stimulus start, and stimulus end times. The current is treated as voltage ('V') for eFEL compatibility. Time is converted to milliseconds. ```python traces = [] rep_name = "repetition1" exp_type = "Deactivation" for idx in range(len(data[exp_type][rep_name]["dt"])): trace = {} i = data[exp_type][rep_name]["current"][:,idx] t = np.arange(i.size) * data[exp_type][rep_name]["dt"][idx] # efel expects ms: s -> ms t = t * 1000.0 trace["T"] = t trace["V"] = i # trick: input current as if it was voltage trace["stim_start"] = [401] trace["stim_end"] = [599] traces.append(trace) ``` -------------------------------- ### Load Data from ASCII Files Source: https://context7.com/openbraininstitute/efel/llms.txt Loads time-voltage data from a specified text file and creates a trace object suitable for eFEL. It supports custom delimiters for the ASCII file and allows setting stimulus start and end times. The extracted features include AP_amplitude and voltage_base. ```python import efel.io # Load time-voltage data from text file time, voltage = efel.io.load_ascii_input('trace.txt', delimiter=' ') # Create trace for eFEL trace = { 'T': time, 'V': voltage, 'stim_start': [100], 'stim_end': [600] } # Extract features results = efel.get_feature_values([trace], ['AP_amplitude', 'voltage_base']) ``` -------------------------------- ### Compile Mechanisms with nrnivmodl Source: https://github.com/openbraininstitute/efel/blob/master/examples/sonata-network/sonata-network.ipynb Compiles the necessary NEURON mechanisms for the simulation. This is a prerequisite step before importing and using the BlueCellulab library. It takes the path to the mechanisms directory as an argument. ```shell !nrnivmodl ./mechanisms ``` -------------------------------- ### Load and Print SONATA Simulation Configuration Source: https://github.com/openbraininstitute/efel/blob/master/examples/sonata-network/sonata-network.ipynb Loads the simulation configuration from a JSON file and prints it to the console. This configuration defines parameters such as simulation time, cell types, stimuli, and output settings. It uses `pathlib` to construct the file path and `json.load` to parse the file. ```python simulation_config = Path("./") / "simulation_config.json" with open(simulation_config) as f: simulation_config_dict = json.load(f) print(json.dumps(simulation_config_dict, indent=4)) ``` -------------------------------- ### Import Libraries for BlueCellulab and eFEL Source: https://github.com/openbraininstitute/efel/blob/master/examples/sonata-network/sonata-network.ipynb Imports essential Python libraries for circuit simulation, data handling, plotting, and feature extraction. This includes `json` for configuration files, `pathlib` for path manipulation, `matplotlib.pyplot` for plotting, `bluecellulab.CircuitSimulation` for running simulations, and `efel` for feature analysis. ```python import json from pathlib import Path from matplotlib import pyplot as plt from bluecellulab import CircuitSimulation import efel ``` -------------------------------- ### Calculate AP Begin Width Source: https://github.com/openbraininstitute/efel/blob/master/docs/source/eFeatures.rst Measures the width of the action potential from its start to the point where the voltage drops below the initial start voltage. Requires minimum inter-AHP indices and AP begin indices. The result is in milliseconds. ```pseudocode for i in range(len(min_AHP_indices)): rise_idx = AP_begin_indices[i] fall_idx = numpy.where(v[rise_idx + 1:min_AHP_indices[i]] < v[rise_idx])[0] AP_begin_width[i] = t[fall_idx] - t[rise_idx] AP1_begin_width = AP_begin_width[0] AP2_begin_width = AP_begin_width[1] ``` -------------------------------- ### Visualizing Bursts and Spikes Source: https://github.com/openbraininstitute/efel/blob/master/examples/neo/load_nwb.ipynb Visualizes the extracted voltage trace, highlighting the detected burst interval and individual spike times. It also displays the calculated mean burst frequency within the burst interval. ```python burst_begin_indices = feature_values['burst_begin_indices'][0] burst_end_indices = feature_values['burst_end_indices'][0] peak_times = feature_values['peak_time'] ap_heights = feature_values['AP_height'] burst_mean_freq = feature_values['strict_burst_mean_freq'] time_spike_indices = numpy.where((time > stim_start) & (time < stim_end)) time_spike = time[time_spike_indices] voltage_spike = voltage[time_spike_indices] plt.figure(figsize=(10, 6)) plt.plot(time_spike, voltage_spike, label='Voltage Trace') burst_start = peak_times[burst_begin_indices] burst_end = peak_times[burst_end_indices] mean_frequency = burst_mean_freq[0] plt.axvspan(burst_start, burst_end, color='yellow', alpha=0.3, label='Burst Interval') for spike_time in peak_times[burst_begin_indices:burst_end_indices+1]: plt.axvline(x=spike_time, color='red', linestyle='--', label='Spike' if 'Spike' not in plt.gca().get_legend_handles_labels()[1] else "") plt.text((burst_start + burst_end) / 2, max(voltage_spike), f'Burst Mean Freq: {mean_frequency:.2f} Hz', horizontalalignment='center', color='black') plt.legend() plt.xlabel('Time (ms)') plt.ylabel('Voltage (mV)') plt.show() ``` -------------------------------- ### Calculate Voltage Deflection Between Stimulus Start and Steady State Source: https://github.com/openbraininstitute/efel/blob/master/docs/source/eFeatures.rst Calculates the voltage deflection from the baseline to the steady-state voltage shortly after stimulation begins. It requires time, voltage, stimulus start, and end times. The output is in mV. ```python voltage_base = numpy.mean(V[t < stim_start]) tstart = stim_start + 0.05 * (stim_end - stim_start) tend = stim_start + 0.15 * (stim_end - stim_start) condition = numpy.all((tstart < t, t < tend), axis=0) steady_state_voltage_stimend = numpy.mean(V[condition]) voltage_deflection = steady_state_voltage_stimend - voltage_base ``` -------------------------------- ### Calculate Multiple Decay Time Constants After Stimuli (Python) Source: https://github.com/openbraininstitute/efel/blob/master/docs/source/eFeatures.rst Calculates a list of decay time constants, one for each stimulus applied in a protocol. This function iterates through multiple stimuli, applying the decay time constant calculation after each one. Requires time, voltage, stimulus start and end times, and lists of multi-stimulus start and end times. ```python import numpy # ... (assuming time, voltage, stim_start, stim_end are defined) # multi_stim_start, multi_stim_end, decay_start_after_stim, decay_end_after_stim are defined multiple_decay_time_constant_after_stim = [] for i in range(len(multi_stim_start)): # Placeholder for the logic to calculate tau for each stimulus # This would involve calling a similar fitting procedure as in the single stimulus case, # using multi_stim_start[i] and multi_stim_end[i] to define the interval. # Example: # current_tau = calculate_decay_tau(time, voltage, multi_stim_start[i], multi_stim_end[i], decay_start_after_stim, decay_end_after_stim) # multiple_decay_time_constant_after_stim.append(current_tau) pass # Replace with actual calculation ``` -------------------------------- ### Download and Unzip Model Package Source: https://github.com/openbraininstitute/efel/blob/master/examples/nmc-portal/L5TTPC2.ipynb Downloads a specified model package from the Neocortical Microcircuit Portal using curl and then extracts its contents using unzip. This step is crucial for obtaining the model files needed for simulation. ```shell !curl -o L5_TTPC2.zip https://bbp.epfl.ch/nmc-portal/assets/documents/static/downloads-zip/L5_TTPC2_cADpyr232_1.zip !unzip L5_TTPC2.zip ``` -------------------------------- ### Run DEAP EA Mu Plus Lambda Algorithm Source: https://github.com/openbraininstitute/efel/blob/master/docs/source/deap_optimisation.rst Initializes and runs the EA Mu Plus Lambda evolutionary algorithm from the DEAP library. It takes the initial population, toolbox, algorithm parameters (MU, LAMBDA, CXPB, MUTPB, NGEN), and statistics as input. ```python if __name__ == '__main__': pop, logbook = algorithms.eaMuPlusLambda( pop, toolbox, MU, LAMBDA, CXPB, MUTPB, NGEN, stats, halloffame=None) ``` -------------------------------- ### Get Available Feature Names Source: https://context7.com/openbraininstitute/efel/llms.txt Retrieves a list of all available electrophysiological feature names that can be extracted by the eFEL library. ```APIDOC ## GET /efel/features/names ### Description Retrieves a list of all available electrophysiological feature names that can be extracted by the eFEL library. ### Method GET ### Endpoint `/efel/features/names` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json (No request body for GET request) ``` ### Response #### Success Response (200) - **feature_names** (list of str) - A list containing all available feature names. #### Response Example ```json { "feature_names": [ "AP_amplitude", "AP_width", "AHP_depth", "ISI_CV", "burst_mean_freq", ... ] } ``` ``` -------------------------------- ### Configure DEAP Toolbox for Evolutionary Algorithm Source: https://github.com/openbraininstitute/efel/blob/master/examples/deap/deap_efel_neuron2.ipynb This Python snippet configures a DEAP toolbox for an evolutionary algorithm. It registers functions for parameter initialization, individual and population creation, evaluation, mating, mutation, variate, and selection. Dependencies include 'deap', 'creator', and 'bluepyopt'. ```python import deap import creator import bluepyopt.deapext.tools import bluepyopt.deapext.algorithms # Assuming LOWER, UPPER, IND_SIZE, ETA, MU, CXPB, NGEN, and 'evaluate' are defined elsewhere # Create a DEAP toolbox toolbox = deap.base.Toolbox() # Register the 'uniform' function toolbox.register("uniformparams", uniform, LOWER, UPPER, IND_SIZE) # Register the individual format # An indiviual is create by 'creator.Individual' and parameters are initially # picked by 'uniform' toolbox.register( "Individual", deap.tools.initIterate, creator.Individual, toolbox.uniformparams) # Register the population format. It is a list of individuals toolbox.register("population", deap.tools.initRepeat, list, toolbox.Individual) # Register the evaluation function for the individuals toolbox.register("evaluate", evaluate) # Register the mate operator toolbox.register( "mate", deap.tools.cxSimulatedBinaryBounded, eta=ETA, low=LOWER, up=UPPER) # Register the mutation operator toolbox.register("mutate", deap.tools.mutPolynomialBounded, eta=ETA, low=LOWER, up=UPPER, indpb=0.1) # Register the variate operator toolbox.register("variate", deap.algorithms.varAnd) # Register the selector (picks parents from population) toolbox.register("select", plot_selector, selector=bluepyopt.deapext.tools.selIBEA) # Generate the population object pop = toolbox.population(n=MU) ``` -------------------------------- ### Calculate Time to First Spike Source: https://github.com/openbraininstitute/efel/blob/master/docs/source/eFeatures.rst Determines the time from the start of a stimulus to the maximum of the first detected spike. This feature requires the 'peak_indices' to be pre-calculated. The output is in milliseconds. ```Python time_to_first_spike = peak_time[0] - stimstart ``` -------------------------------- ### Import Libraries and Load NWB Data with Neo Source: https://github.com/openbraininstitute/efel/blob/master/examples/neo/load_nwb.ipynb Imports necessary libraries (efel, numpy, matplotlib) and loads electrophysiology data from an NWB file using efel's load_neo_file function. It specifies the file path and stimulus start/end times for data loading. ```python import efel import numpy %matplotlib notebook %matplotlib inline from matplotlib import pyplot as plt plt.rcParams['figure.figsize'] = 10, 10 test_data = "../../tests/testdata/JY180308_A_1.nwb" stim_start = 250 stim_end = 600 blocks = efel.io.load_neo_file(test_data, stim_start, stim_end) traces = blocks[0][0] ``` -------------------------------- ### Find Maximum Voltage During Stimulus Source: https://github.com/openbraininstitute/efel/blob/master/docs/source/eFeatures.rst Identifies the maximum voltage value recorded during the stimulus period. Requires time, voltage, stimulus start, and end times. The output is in mV. ```python maximum_voltage = max(voltage[numpy.where((t >= stim_start) & (t <= stim_end))]) ``` -------------------------------- ### Plotting the Voltage Trace Source: https://github.com/openbraininstitute/efel/blob/master/examples/neo/load_nwb.ipynb Generates a plot of the membrane voltage over time for the selected trace. It sets axis labels for clarity. ```python plt.rcParams['figure.figsize'] = 10, 10 fig1, ax1 = plt.subplots(1) ax1.plot(time, voltage) ax1.set_xlabel('Time (ms)') ax1.set_ylabel('Membrane voltage (mV)'); ``` -------------------------------- ### Find Minimum Voltage During Stimulus Source: https://github.com/openbraininstitute/efel/blob/master/docs/source/eFeatures.rst Identifies the minimum voltage value recorded during the stimulus period. Requires time, voltage, stimulus start, and end times. The output is in mV. ```python minimum_voltage = min(voltage[numpy.where((t >= stim_start) & (t <= stim_end))]) ``` -------------------------------- ### Calculate Time to Last Spike Source: https://github.com/openbraininstitute/efel/blob/master/docs/source/eFeatures.rst Calculates the time from stimulus start to the last detected spike. It requires 'peak_time' and 'stimstart' as inputs. If no spikes are detected, it returns 0. The output is in milliseconds. ```Python if len(peak_time) > 0: time_to_last_spike = peak_time[-1] - stimstart else: time_to_last_spike = 0 ``` -------------------------------- ### Initialize DEAP Toolbox and Operators Source: https://github.com/openbraininstitute/efel/blob/master/docs/source/deap_optimisation.rst Configures the DEAP toolbox by registering functions for generating parameters, creating individuals, and forming populations. It also registers the evaluation function and genetic operators like crossover and mutation. ```python toolbox = base.Toolbox() toolbox.register("uniformparams", uniform, LOWER, UPPER, IND_SIZE) toolbox.register( "Individual", tools.initIterate, creator.Individual, toolbox.uniformparams) toolbox.register("population", tools.initRepeat, list, toolbox.Individual) import deap_efel_eval1 toolbox.register("evaluate", deap_efel_eval1.evaluate) toolbox.register( "mate", deap.tools.cxSimulatedBinaryBounded, eta=ETA, low=LOWER, up=UPPER) toolbox.register("mutate", deap.tools.mutPolynomialBounded, eta=ETA, low=LOWER, up=UPPER, indpb=0.1) toolbox.register( "select", tools.selNSGA2) ```