### Run Example Simulation Script Source: https://allensdk.readthedocs.io/en/latest/biophysical_models.html Executes the main simulation script for a given example. This command initiates the simulation run after all setup steps are completed. ```bash python simple.py ``` ```bash python multi.py ``` ```bash python multicell_diff.py ``` -------------------------------- ### SDK Usage Examples Source: https://allensdk.readthedocs.io/en/latest/allensdk.brain_observatory.behavior.write_nwb.extensions.html Examples demonstrating how to use the AllenSDK for data analysis. ```APIDOC ## SDK Usage Examples ### Description This section provides code examples for using the AllenSDK to interact with data resources and perform analysis. ### Method N/A (Code examples for SDK usage) ### Endpoint N/A ### Parameters N/A ### Request Example ```python from allensdk.api.queries.brain_observatory_api import BrainObservatoryApi boa = BrainObservatoryApi() # Get a list of all experiments experiments = boa.get_all_ophys_experiments() print(f"Found {len(experiments)} experiments.") # Get data for a specific experiment experiment_id = experiments[0]['id'] stimulus_data = boa.get_stimulus_by_ophys_experiment(experiment_id) print(f"Stimulus data for experiment {experiment_id}:") print(stimulus_data) ``` ### Response N/A (Output depends on the execution of the Python code) ``` -------------------------------- ### Extract and Unpack Example Archive Source: https://allensdk.readthedocs.io/en/latest/biophysical_models.html Extracts a simulation example archive using tar and navigates into the example directory. This is a common first step for setting up a new simulation project. ```bash tar xvzf simple_example.tgz cd simple ``` ```bash tar xvzf multicell_example.tgz cd multicell ``` -------------------------------- ### Report Class - `setup_model` Method Source: https://allensdk.readthedocs.io/en/latest/_modules/allensdk/internal/model/biophysical/make_deap_fit_json.html Sets up the biophysical model environment, including loading morphology, inserting IClamp, and setting stimulus parameters. ```APIDOC ## Report Class - `setup_model` Method ### Description Sets up the biophysical model environment, including loading morphology, inserting IClamp, and setting stimulus parameters. It initializes the `Utils` class and configures the simulation environment. ### Method setup_model ### Parameters None ### Request Body None ### Request Example None ### Response None ### Error Handling None specified. ``` -------------------------------- ### Get Ophys Timestamps (NIKONA1RMP) Source: https://allensdk.readthedocs.io/en/latest/_modules/allensdk/internal/brain_observatory/time_sync.html Retrieves stimulus timestamps for NIKONA1RMP scanner data. It identifies the acquisition start and filters ophys timestamps to include only those after the start. ```python acquiring_key = self._keys["acquiring"] acquisition_start = self._dataset.get_rising_edges( acquiring_key, units="seconds")[0] ophys_times = self._dataset.get_falling_edges( ophys_key, units="seconds") times = ophys_times[ophys_times >= acquisition_start] ``` -------------------------------- ### Main execution entry point Source: https://allensdk.readthedocs.io/en/latest/_modules/allensdk/model/glif/simulate_neuron.html Initializes the simulation environment, downloads necessary data if missing, and configures the GLIF neuron. ```python def main(): args = parse_arguments() logging.getLogger().setLevel(args.log_level) glif_api = None if (args.neuron_config_file is None or args.sweeps_file is None or args.ephys_file is None): assert args.neuronal_model_id is not None, Exception("A neuronal model id is required if no neuron config file, sweeps file, or ephys data file is provided.") glif_api = GlifApi() glif_api.get_neuronal_model(args.neuronal_model_id) if args.neuron_config_file: neuron_config = json_utilities.read(args.neuron_config_file) else: neuron_config = glif_api.get_neuron_config() if args.sweeps_file: sweeps = json_utilities.read(args.sweeps_file) else: sweeps = glif_api.get_ephys_sweeps() if args.ephys_file: ephys_file = args.ephys_file else: ephys_file = 'stimulus_%d.nwb' % args.neuronal_model_id if not os.path.exists(ephys_file): logging.info("Downloading stimulus to %s." % ephys_file) glif_api.cache_stimulus_file(ephys_file) else: logging.warning("Reusing %s because it already exists." % ephys_file) if args.output_ephys_file: output_ephys_file = args.output_ephys_file else: logging.warning("Overwriting input file data with simulated data in place.") output_ephys_file = ephys_file neuron = GlifNeuron.from_dict(neuron_config) ``` -------------------------------- ### Get All Sweep Numbers from NWB File Source: https://allensdk.readthedocs.io/en/latest/_modules/allensdk/core/nwb_data_set.html Retrieves all sweep numbers from the 'epochs' section of an NWB file. Filters keys to include only those starting with 'Sweep_'. ```python def get_sweep_numbers(self): """ Get all of the sweep numbers in the file, including test sweeps. """ with h5py.File(self.file_name, 'r') as f: sweeps = [int(e.split('_')[1]) for e in f['epochs'].keys() if e.startswith('Sweep_')] return sweeps ``` -------------------------------- ### Get Stimulus Epoch Windows Source: https://allensdk.readthedocs.io/en/latest/_modules/allensdk/internal/brain_observatory/demix_report.html Calculates the start and end points of stimulus epochs from a stimulus table. It identifies distinct epochs based on gaps between stimulus events. ```python def _get_epoch_windows(stim_table): start = np.array(stim_table.start) end = np.array(stim_table.end) windows = zip(start,end) window_list = [[start[0]]] for i,w in enumerate(windows[1:]): if start[i+1] - end[i]>1: window_list[-1].append(end[i]) window_list.append([start[i+1]]) #window_list += [end[i],start[i+1]] window_list[-1].append(end[-1]) #window_list = [start[0]] #window_list += [ start[x+1] for x in list(np.where(np.abs(start[1:] - end[:-1]) > 1)[0])] #window_list += [end[-1]] ``` -------------------------------- ### Script Entry Point Source: https://allensdk.readthedocs.io/en/latest/_modules/allensdk/internal/model/biophysical/run_passive_fit.html Parses command-line arguments for limit and manifest path, then calls the main function to start the process. ```python if __name__ == "__main__": limit = sys.argv[-2] manifest_path = sys.argv[-1] main(limit, manifest_path) ``` -------------------------------- ### Get Experiment Sweep Numbers from NWB File Source: https://allensdk.readthedocs.io/en/latest/_modules/allensdk/core/nwb_data_set.html Retrieves sweep numbers specifically for experiment epochs from an NWB file. Excludes test sweeps by filtering for keys starting with 'Experiment_'. ```python def get_experiment_sweep_numbers(self): """ Get all of the sweep numbers for experiment epochs in the file, not including test sweeps. """ with h5py.File(self.file_name, 'r') as f: sweeps = [int(e.split('_')[1]) for e in f['epochs'].keys() if e.startswith('Experiment_')] return sweeps ``` -------------------------------- ### Main Execution Entry Point Source: https://allensdk.readthedocs.io/en/latest/_modules/allensdk/internal/pipeline_modules/gbm/generate_gbm_heatmap.html Loads configuration from a JSON file and orchestrates the generation of output CSV files. ```python def main(): input_file = sys.argv[1] data = json.load(open(input_file)) transcripts_for_genes_output = data["transcripts_for_genes_output"] genes_for_transcripts_output = data["genes_for_transcripts_output"] gene_fpkm_table_output = data["gene_fpkm_table_output"] transcript_fpkm_table_output = data["transcript_fpkm_table_output"] columns_samples_output = data["columns_samples_output"] analysis_run_records = json.load(open(data["analysis_run_records"])) sample_metadata_records = json.load(open(data["sample_metadata_records"])) create_transcripts_for_genes(analysis_run_records["analysis_run_records"][0]).to_csv(transcripts_for_genes_output, index=False, header=False) create_genes_for_transcripts(analysis_run_records["analysis_run_records"][0]).to_csv(genes_for_transcripts_output, index=False, header=False) create_gene_fpkm_table(analysis_run_records["analysis_run_records"]).to_csv(gene_fpkm_table_output) ``` -------------------------------- ### Reset Long Squares Start Time Source: https://allensdk.readthedocs.io/en/latest/allensdk.ephys.ephys_extractor.html Resets the start time for long square pulse sweeps. The 'when' parameter specifies the new start time. ```python allensdk.ephys.ephys_extractor.reset_long_squares_start(_when_)[source]¶ ``` -------------------------------- ### start_specimen Method Source: https://allensdk.readthedocs.io/en/latest/allensdk.internal.model.biophysical.run_optimize.html Initiates the specimen processing for the optimization. ```python start_specimen() ``` -------------------------------- ### Start Output Capture Source: https://allensdk.readthedocs.io/en/latest/_modules/allensdk/internal/model/biophysical/passive_fitting/output_grabber.html Starts capturing the stream data by redirecting the original stream to a pipe. If threaded is True, it starts a worker thread to read the output. ```python def start(self): """ Start capturing the stream data. """ self.capturedtext = "" # Save a copy of the stream: self.streamfd = os.dup(self.origstreamfd) # Replace the Original stream with our write pipe os.dup2(self.pipe_in, self.origstreamfd) if self.threaded: # Start thread that will read the stream: self.workerThread = threading.Thread(target=self.readOutput) self.workerThread.start() # Make sure that the thread is running and os.read is executed: time.sleep(0.01) ``` -------------------------------- ### Main execution entry point Source: https://allensdk.readthedocs.io/en/latest/_modules/allensdk/internal/pipeline_modules/run_observatory_thumbnails.html Parses command line arguments and initiates the thumbnail generation process. ```python def main(): parser = argparse.ArgumentParser() parser.add_argument("-t", "--threads", type=int, default=4) parser.add_argument("--log-level", default=logging.DEBUG) parser.add_argument("--types", default=','.join(PLOT_TYPES)) parser.add_argument("input_json") parser.add_argument("output_json") args = parser.parse_args() args.types = args.types.split(',') logging.getLogger().setLevel(args.log_level) input_data = ju.read(args.input_json) nwb_file, analysis_file, output_directory = parse_input(input_data) build_experiment_thumbnails(nwb_file, analysis_file, output_directory, args.types, args.threads) ju.write(args.output_json, {}) if __name__ == "__main__": main() ``` -------------------------------- ### GET allensdk.api.api.stream_zip_directory_over_http Source: https://allensdk.readthedocs.io/en/latest/allensdk.api.api.html Streams an HTTP GET response and extracts the content to a specified directory. ```APIDOC ## GET allensdk.api.api.stream_zip_directory_over_http ### Description Supply an http get request and stream the response to a file. ### Method GET ### Parameters #### Query Parameters - **url** (str) - Required - Send the request to this url - **directory** (str) - Required - Extract the response to this directory - **members** (list of str) - Optional - Extract only these files - **timeout** (float or tuple of float) - Optional - Specify a timeout for the request. If a tuple, specify seperate connect and read timeouts. ``` -------------------------------- ### main Source: https://allensdk.readthedocs.io/en/latest/_modules/allensdk/internal/pipeline_modules/run_ophys_time_sync.html Main function to parse arguments, initialize alignment, and run time synchronization. ```APIDOC ## main ### Description Main function to parse arguments, initialize alignment, and run time synchronization for brain observatory data. ### Method N/A (Function) ### Endpoint N/A (Script Execution) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None (Executes script and writes output) #### Response Example None ``` -------------------------------- ### GET allensdk.api.api.stream_file_over_http Source: https://allensdk.readthedocs.io/en/latest/allensdk.api.api.html Streams an HTTP GET response to a specified local file path. ```APIDOC ## GET allensdk.api.api.stream_file_over_http ### Description Supply an http get request and stream the response to a file. ### Method GET ### Parameters #### Query Parameters - **url** (str) - Required - Send the request to this url - **file_path** (str) - Required - Stream the response to this path - **timeout** (float or tuple of float) - Optional - Specify a timeout for the request. If a tuple, specify seperate connect and read timeouts. ``` -------------------------------- ### Example Usage of LimsApi Source: https://allensdk.readthedocs.io/en/latest/_modules/allensdk/internal/api/lims_api.html Demonstrates how to instantiate LimsApi and retrieve eye tracking video file paths. ```python if __name__ == "__main__": api = LimsApi() for ii in range(5): print(api.get_eye_tracking_video_filepath_df().loc[ii].raw_behavior_tracking_video_filepath) ``` -------------------------------- ### credential_map Example for PostgresQueryMixin Source: https://allensdk.readthedocs.io/en/latest/allensdk.core.authentication.html Example of a credential_map dictionary used with PostgresQueryMixin to connect to a LIMS database. ```python { “dbname”: “LIMS_DBNAME”, “user”: “LIMS_USER”, “host”: “LIMS_HOST”, “password”: “LIMS_PASSWORD”, “port”: “LIMS_PORT” } ``` -------------------------------- ### Dataset Context Manager Example Source: https://allensdk.readthedocs.io/en/latest/_modules/allensdk/brain_observatory/sync_dataset.html Demonstrates using the Dataset class as a context manager for file operations. This allows for automatic resource management, similar to Python's built-in file handling. ```python with Dataset('my_data.h5') as d: d.stats() ``` -------------------------------- ### Initialize and use Dataset Source: https://allensdk.readthedocs.io/en/latest/_modules/allensdk/brain_observatory/sync_dataset.html Demonstrates standard usage of the Dataset class for loading and inspecting HDF5 sync files. ```python >>> dset = Dataset('my_h5_file.h5') >>> logger.info(dset.meta_data) >>> dset.stats() >>> dset.close() >>> with Dataset('my_h5_file.h5') as d: ... logger.info(dset.meta_data) ... dset.stats() ``` -------------------------------- ### Get Model Type Source: https://allensdk.readthedocs.io/en/latest/allensdk.internal.api.queries.biophysical_module_reader.html Placeholder function for getting the model type. TODO: Add comment. ```python model_type() ``` -------------------------------- ### Initialize ProjectCode Source: https://allensdk.readthedocs.io/en/latest/allensdk.brain_observatory.behavior.data_objects.metadata.behavior_metadata.project_code.html Instantiate a ProjectCode object with an optional project code string. ```python _class _allensdk.brain_observatory.behavior.data_objects.metadata.behavior_metadata.project_code.ProjectCode(_project_code : str | None = None_)[source] ``` -------------------------------- ### get_ramp_stim_characteristics Source: https://allensdk.readthedocs.io/en/latest/_modules/allensdk/ephys/extract_cell_features.html Identifies the start time and start index of a ramp stimulus, assuming a test pulse precedes it. ```APIDOC ## get_ramp_stim_characteristics ### Description Identifies the start time and start index of a ramp sweep. Assumes that there is a test pulse followed by the stimulus ramp. ### Parameters - **i** (numpy.ndarray): Current trace of the stimulus. - **t** (numpy.ndarray): Time trace of the stimulus. ### Returns - **stim_start** (float): The start time of the ramp stimulus. - **start_idx** (int): The start index of the ramp stimulus in the trace. ``` -------------------------------- ### Reset Long Squares Start Time Source: https://allensdk.readthedocs.io/en/latest/_modules/allensdk/ephys/ephys_extractor.html Resets the global start and end times for long square sweeps. ```APIDOC ## reset_long_squares_start(when) ### Description Resets the global start and end times for long square sweeps. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Main Execution Entry Point Source: https://allensdk.readthedocs.io/en/latest/_modules/allensdk/model/biophys_sim/bps_command.html Handles command line arguments or environment variables to determine the simulation command and configuration file path. ```python if __name__ == '__main__': import sys conf_file = None argv = sys.argv if len(argv) > 1: if argv[0] == 'nrniv': command = 'run_simple' else: command = argv[1] else: command = 'run_simple' if len(argv) > 2 and (argv[-1].endswith('.conf') or argv[-1].endswith('.json')): conf_file = argv[-1] else: try: conf_file = os.environ['CONF_FILE'] except: pass choose_bps_command(command, conf_file) ``` -------------------------------- ### GET /read_url_get Source: https://allensdk.readthedocs.io/en/latest/_modules/allensdk/core/json_utilities.html Retrieves JSON data from a specified URL using the GET method and converts it into a Python dictionary. ```APIDOC ## GET /read_url_get ### Description Retrieves JSON data from a specified URL using the GET method and converts it into a Python dictionary. ### Method GET ### Endpoint /read_url_get ### Parameters #### Query Parameters - **url** (string) - Required - The URL from which to retrieve the JSON data. ### Response #### Success Response (200) - **dict** (object) - The Python representation of the JSON data. ``` -------------------------------- ### Initialize Pipeline Module Source: https://allensdk.readthedocs.io/en/latest/_modules/allensdk/internal/pipeline_modules/run_demixing.html Entry point for the pipeline module execution. ```python def main(): mod = PipelineModule() ``` -------------------------------- ### Initialize LimsApi with Credentials Source: https://allensdk.readthedocs.io/en/latest/_modules/allensdk/internal/api/lims_api.html Initializes the LimsApi with provided database credentials. If no credentials are given, it attempts to use default credentials. ```python import pandas as pd from typing import Optional from allensdk.internal.api import PostgresQueryMixin from allensdk.internal.core.lims_utilities import safe_system_path from allensdk.core.auth_config import LIMS_DB_CREDENTIAL_MAP from allensdk.core.authentication import credential_injector, DbCredentials class LimsApi(): def __init__(self, lims_credentials: Optional[DbCredentials] = None): if lims_credentials: self.lims_db = PostgresQueryMixin( dbname=lims_credentials.dbname, user=lims_credentials.user, host=lims_credentials.host, password=lims_credentials.password, port=lims_credentials.port) else: # Currying is equivalent to decorator syntactic sugar self.lims_db = ( credential_injector(LIMS_DB_CREDENTIAL_MAP) (PostgresQueryMixin)() ) ``` -------------------------------- ### Reset long squares start time Source: https://allensdk.readthedocs.io/en/latest/_modules/allensdk/ephys/ephys_extractor.html Updates global long square start and end times while maintaining the duration. ```python def reset_long_squares_start(when): global LONG_SQUARES_START, LONG_SQUARES_END delta = LONG_SQUARES_END - LONG_SQUARES_START LONG_SQUARES_START = when LONG_SQUARES_END = when + delta ``` -------------------------------- ### Get Number of Cells Source: https://allensdk.readthedocs.io/en/latest/_modules/allensdk/core/brain_observatory_nwb_data_set.html Returns the total number of cells in the experiment by getting the length of cell specimen IDs. This is a property getter. ```python return len(self.get_cell_specimen_ids()) ``` -------------------------------- ### Setup Biophysical Model Environment Source: https://allensdk.readthedocs.io/en/latest/_modules/allensdk/internal/model/biophysical/make_deap_fit_json.html Configures the simulation environment by setting up morphology, loading cell parameters, inserting IClamp, and setting stimulus parameters. ```python def setup_model(self): morphology_path = os.path.realpath(self.top_level_description.manifest.get_path('MORPHOLOGY')) cwd = os.path.realpath(os.curdir) self.utils = Utils(self.fit_config) h = self.utils.h self.utils.generate_morphology(morphology_path) self.utils.load_cell_parameters() self.utils.insert_iclamp() self.stim_params = self.fit_config.data["stimulus"][0] self.utils.set_iclamp_params(self.stim_params["amplitude"], ``` -------------------------------- ### Find Stimulus Start Time Source: https://allensdk.readthedocs.io/en/latest/_modules/allensdk/internal/ephys/core_feature_extract.html Locates the index of the first non-zero jump in a stimulus array or calculates the start time for a specific sweep. ```python def find_stim_start(stim, idx0=0): """ Find the index of the first nonzero positive or negative jump in an array. Parameters ---------- stim: np.ndarray Array to be searched idx0: int Start searching with this index (default: 0). Returns ------- int """ di = np.diff(stim) idxs = np.flatnonzero(di) idxs = idxs[idxs >= idx0] if len(idxs) == 0: return -1 return idxs[0]+1 ``` ```python def find_sweep_stim_start(data_set, sweep_number): sweep = data_set.get_sweep(sweep_number) sr = sweep['sampling_rate'] stim_start = find_stim_start(sweep['stimulus'], TEST_PULSE_DURATION_SEC * sr) / sr logging.info("Long square stims start at time %f", stim_start) return stim_start ``` -------------------------------- ### Configuration Loading and Application Source: https://allensdk.readthedocs.io/en/latest/_modules/allensdk/config/app/application_config.html Methods for applying configuration from different sources. ```APIDOC ## Internal Argparser Call ### Description Simply call the internal argparser object to parse arguments. ### Method Internal ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **Namespace** (object) - Parsed parameters. #### Response Example None ``` ```APIDOC ## Apply Configuration from Command Line ### Description Read application configuration variables from the command line. Unassigned variables are left unchanged if previously assigned, set to their default values, or None if no default is specified at init time. Assigned variables will overwrite the previous value. ### Method Internal ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **parsed_args** (dict) - The arguments as parsed from the command line. ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` ```APIDOC ## Apply Configuration from Environment ### Description Read application configuration variables from the environment. The variable names are upper case and have a prefix defined by the application. ### Method Internal ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` ```APIDOC ## Read Configuration from JSON File ### Description Read an application configuration from a JSON format file. ### Method Internal ### Endpoint N/A ### Parameters #### Path Parameters - **json_path** (string) - Required - Path to the JSON file. #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **string** (string) - An application configuration in INI format #### Response Example None ``` ```APIDOC ## Read Configuration from JSON String ### Description Read a configuration from a JSON format string. ### Method Internal ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **json_string** (string) - Required - A JSON-formatted string containing an application configuration. ### Request Example None ### Response #### Success Response (200) - **string** (string) - An application configuration in INI format #### Response Example None ``` ```APIDOC ## Convert to Configuration String ### Description Create a configuration string from a dictionary. ### Method Internal ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **description** (dict) - Required - Configuration options for an application. ### Request Example None ### Response #### Success Response (200) - **string** (string) - Equivalent configuration as an INI format string #### Response Example None ``` ```APIDOC ## Apply Configuration from File ### Description Read application configuration variables from a .conf file. Unassigned variables are set to their default values or None if no default is specified at init time. The variables are found in a section named by the application. ### Method Internal ### Endpoint N/A ### Parameters #### Path Parameters - **config_file_path** (string) - Required - Path to an INI (.conf) or JSON format application config file. #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### HocUtils.initialize_hoc Method Source: https://allensdk.readthedocs.io/en/latest/_modules/allensdk/model/biophys_sim/neuron/hoc_utils.html Explains the `initialize_hoc` method, which performs basic setup for NEURON simulations. ```APIDOC ## Method initialize_hoc ### Description Performs basic setup for NEURON. ### Usage This method is called automatically during the initialization of the `HocUtils` class. It iterates through the specified HOC files, loads them using `HocUtils.h.load_file()`, and sets simulation parameters like `celsius`, `v_init`, `dt`, and `tstop` based on the provided description data. ``` -------------------------------- ### get_square_stim_characteristics Source: https://allensdk.readthedocs.io/en/latest/_modules/allensdk/ephys/extract_cell_features.html Identifies the start time, duration, amplitude, start index, and end index of a square stimulus, assuming a test pulse precedes it. ```APIDOC ## get_square_stim_characteristics ### Description Identifies the start time, duration, amplitude, start index, and end index of a square stimulus. This assumes that there is a test pulse followed by the stimulus square. ### Parameters - **i** (numpy.ndarray): Current trace of the stimulus. - **t** (numpy.ndarray): Time trace of the stimulus. - **no_test_pulse** (bool, optional): If True, skips the initial test pulse. Defaults to False. ### Returns - **stim_start** (float): The start time of the square stimulus. - **stim_dur** (float): The duration of the square stimulus. - **stim_amp** (float): The amplitude of the square stimulus. - **start_idx** (int): The start index of the square stimulus in the trace. - **end_idx** (int): The end index of the square stimulus in the trace. ``` -------------------------------- ### setup_table_for_epochs Source: https://allensdk.readthedocs.io/en/latest/allensdk.brain_observatory.nwb.html Sets up a table for epochs. ```APIDOC ## setup_table_for_epochs ### Description Sets up a table for epochs. ### Method Not specified (likely a utility function) ### Endpoint Not applicable (Python function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters #### Path Parameters * **table** - Required - The table to set up. * **timeseries** - Required - The timeseries data. * **tag** - Required - The tag for the table. ### Request Example ```python # Example usage (assuming necessary imports and data) # from allensdk.brain_observatory.nwb import setup_table_for_epochs # setup_table_for_epochs(_table=..., _timeseries=..., _tag=...) ``` ### Response #### Success Response (200) Not specified #### Response Example ```json { "example": "Not specified" } ``` ``` -------------------------------- ### Get Average Spike Feature Source: https://allensdk.readthedocs.io/en/latest/allensdk.ephys.ephys_extractor.html Retrieves an nparray of average spike-level features for all sweeps. Specify the feature key to get the desired average. ```python spike_feature_averages(_key_)[source]¶ ``` -------------------------------- ### Build Manifest File Source: https://allensdk.readthedocs.io/en/latest/_modules/allensdk/api/warehouse_cache/cache.html Creates a default manifest file at the specified path using the current configuration. ```python def build_manifest(self, file_name): '''Creation of default path specifications. Parameters ---------- file_name : string where to save it ''' manifest_builder = ManifestBuilder() manifest_builder.set_version(self.MANIFEST_VERSION) manifest_builder = self.add_manifest_paths(manifest_builder) manifest_builder.write_json_file(file_name) ``` -------------------------------- ### get_stim_characteristics Source: https://allensdk.readthedocs.io/en/latest/_modules/allensdk/ephys/extract_cell_features.html Identifies the start time, duration, amplitude, start index, and end index of a general stimulus, assuming a test pulse followed by the stimulus. ```APIDOC ## get_stim_characteristics ### Description Identifies the start time, duration, amplitude, start index, and end index of a general stimulus. This assumes that there is a test pulse followed by the stimulus square. ### Parameters - **i** (numpy.ndarray): Current trace of the stimulus. - **t** (numpy.ndarray): Time trace of the stimulus. - **no_test_pulse** (bool, optional): If True, skips the initial test pulse. Defaults to False. ### Returns - **stim_start** (float): The start time of the stimulus. - **stim_dur** (float): The duration of the stimulus. - **stim_amp** (float): The amplitude of the stimulus. - **start_idx** (int): The start index of the stimulus in the trace. - **end_idx** (int): The end index of the stimulus in the trace. ``` -------------------------------- ### Get Child Nodes Source: https://allensdk.readthedocs.io/en/latest/_modules/allensdk/core/simple_tree.html Retrieves the child nodes (as dictionaries) for a given list of node IDs. It first gets the child IDs and then retrieves the corresponding node dictionaries. ```python return list(map(self.nodes, self.child_ids(node_ids))) ``` -------------------------------- ### Module Entry Point Source: https://allensdk.readthedocs.io/en/latest/_modules/allensdk/internal/model/biophysical/run_simulate_lims.html Main function to execute simulation commands based on the provided LIMS strategy and response JSON files. ```python [docs]def main(command, lims_strategy_json, lims_response_json): ''' Entry point for module. :param command: select behavior, nrnivmodl or simulate :type command: string :param lims_strategy_json: path to json file output from lims. :type lims_strategy_json: string :param lims_response_json: path to json file returned to lims. :type lims_response_json: string ''' rs = RunSimulateLims(lims_strategy_json, lims_response_json) RunSimulateLims._log.debug("command: %s" % (command)) RunSimulateLims._log.debug("lims strategy json: %s" % (lims_strategy_json)) RunSimulateLims._log.debug("lims upload json: %s" % (lims_response_json)) log_config = resource_filename('allensdk.model.biophysical.run_simulate', 'logging.conf') lc.fileConfig(log_config) os.environ['LOG_CFG'] = log_config if 'nrnivmodl' == command: rs.nrnivmodl() elif 'copy_local' == command: rs.copy_local() elif 'generate_manifest_rma' == command: rs.generate_manifest_rma(input_json, output_json) elif 'generate_manifest_lims' == command: rs.generate_manifest_lims(input_json, output_json) elif 'generate_manifest_lims' == command: rs.generate_manifest_lims(input_json, output_json) else: rs.simulate() ``` -------------------------------- ### Launch Jupyter Notebook Source: https://allensdk.readthedocs.io/en/latest/install.html Starts the Jupyter notebook server in the current directory. ```bash jupyter notebook ``` -------------------------------- ### Calculate Latency to First Spike Source: https://allensdk.readthedocs.io/en/latest/_modules/allensdk/ephys/ephys_features.html Determines the time from a reference start point to the first detected spike. Returns NaN if no spikes are found. If `start` is not specified, it defaults to the beginning of the time series. ```python if len(spikes) == 0: return np.nan if start is None: start = t[0] return t[spikes[0]] - start ``` -------------------------------- ### Calculate Average Firing Rate Source: https://allensdk.readthedocs.io/en/latest/_modules/allensdk/ephys/ephys_features.html Computes the average firing rate in spikes per second over a given time interval. Spikes outside the `start` and `end` times are ignored. If `start` or `end` are not provided, defaults to the full time series. ```python if start is None: start = t[0] if end is None: end = t[-1] spikes_in_interval = [spk for spk in spikes if t[spk] >= start and t[spk] <= end] avg_rate = len(spikes_in_interval) / (end - start) return avg_rate ``` -------------------------------- ### Initialize MouseConnectivityApiPrerelease Source: https://allensdk.readthedocs.io/en/latest/_modules/allensdk/internal/api/queries/mouse_connectivity_api_prerelease.html Constructor for the API class, setting up the grid data API from a storage directory file. ```python def __init__(self, storage_directories_file_name, cache_storage_directories=True, base_uri=None): super(MouseConnectivityApiPrerelease, self).__init__(base_uri=base_uri) self.grid_data_api = GridDataApiPrerelease.from_file_name( storage_directories_file_name, cache=cache_storage_directories) ``` -------------------------------- ### get_gaussian_fit_single_channel Source: https://allensdk.readthedocs.io/en/latest/allensdk.brain_observatory.receptive_field_analysis.fit_parameters.html Gets the Gaussian fit for a single channel. ```APIDOC ## get_gaussian_fit_single_channel ### Description Gets the Gaussian fit for a single channel. ### Parameters #### Path Parameters - **rf** (any) - Required - The receptive field data. - **fit_parameters_dict** (dict) - Required - The dictionary containing fit parameters. ``` -------------------------------- ### Initialize FFmpeg Output Stream Source: https://allensdk.readthedocs.io/en/latest/_modules/allensdk/internal/brain_observatory/frame_stream.html Sets up the FFmpeg output stream with frame shape, FFmpeg binary path, and block size. Initializes the pipe and stopped status. ```python def __init__(self, frame_shape, ffmpeg_bin='ffmpeg', block_size=1): super(FfmpegOutputStream, self).__init__(block_size) self.ffmpeg_bin = ffmpeg_bin self.frame_shape = frame_shape self.pipe = None self.stopped = False ``` -------------------------------- ### GET /sessions Source: https://allensdk.readthedocs.io/en/latest/allensdk.brain_observatory.ecephys.ecephys_project_api.ecephys_project_api.html Retrieve a list of electrophysiology sessions. ```APIDOC ## GET /sessions ### Description Retrieves a list of electrophysiology sessions based on optional filters. ### Method GET ### Parameters #### Query Parameters - **session_ids** (ArrayLike) - Optional - List of session IDs to filter by. - **published_at** (str) - Optional - Filter by publication date. ``` -------------------------------- ### Apply configuration from file Source: https://allensdk.readthedocs.io/en/latest/_modules/allensdk/config/app/application_config.html Initializes a ConfigParser to read settings from an INI or JSON configuration file. ```python def apply_configuration_from_file(self, config_file_path): ''' Read application configuration variables from a .conf file. Unassigned variables are set to their default values or None if no default is specified at init time. The variables are found in a section named by the application. Parameters ---------- config_file_path : string path to to an INI (.conf) or JSON format application config file. Returns ------- see: https://docs.python.org/2/library/configparser.html ''' none_defaults = {} # defaults are set in environment # they are only overriden by the config file if present for key in self.defaults: none_defaults[key] = None logging.info("none_defaults: %s" % (none_defaults)) config = None try: config = ConfigParser(defaults=none_defaults, allow_no_value=True) except: logging.warn( ``` -------------------------------- ### GET /as_dict Source: https://allensdk.readthedocs.io/en/latest/_modules/allensdk/ephys/ephys_extractor.html Exports all features and spikes as a dictionary. ```APIDOC ## GET /as_dict ### Description Creates a dictionary representation of all sweep features and spike data. ### Response #### Success Response (200) - **output_dict** (object) - A dictionary containing sweep features, spike data, and optional ID. ``` -------------------------------- ### Initialize NEURON Hoc Environment Source: https://allensdk.readthedocs.io/en/latest/_modules/allensdk/model/biophys_sim/neuron/hoc_utils.html Sets up the NEURON environment by loading hoc files and configuring simulation parameters like celsius, v_init, dt, and tstop. ```python # Allen Institute Software License - This software license is the 2-clause BSD # license plus a third clause that prohibits redistribution for commercial # purposes without further permission. # # Copyright 2015-2016. Allen Institute. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Redistributions for commercial purposes are not permitted without the # Allen Institute's written permission. # For purposes of this license, commercial purposes is the incorporation of the # Allen Institute's software into anything for which you will charge fees or # other compensation. Contact terms@alleninstitute.org for commercial licensing # opportunities. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # import logging [docs] class HocUtils(object): '''A helper class for containing references to NEUORN. Attributes ---------- h : object The NEURON hoc object. nrn : object The NEURON python object. neuron : module The NEURON module. ''' _log = logging.getLogger(__name__) h = None nrn = None neuron = None def __init__(self, description): import neuron import nrn self.h = neuron.h HocUtils.neuron = neuron HocUtils.nrn = nrn HocUtils.h = self.h self.description = description self.manifest = description.manifest self.hoc_files = description.data['neuron'][0]['hoc'] self.initialize_hoc() [docs] def initialize_hoc(self): '''Basic setup for NEURON.''' h = self.h params = self.description.data['conditions'][0] for hoc_file in self.hoc_files: HocUtils._log.info("loading hoc file %s" % (hoc_file)) HocUtils.h.load_file(str(hoc_file)) h('starttime = startsw()') if 'celsius' in params: h.celsius = params['celsius'] if 'v_init' in params: h.v_init = params['v_init'] if 'dt' in params: h.dt = params['dt'] h.steps_per_ms = 1.0 / h.dt if 'tstop' in params: h.tstop = params['tstop'] h.runStopAt = h.tstop ``` -------------------------------- ### Get Experiment ID Source: https://allensdk.readthedocs.io/en/latest/_modules/allensdk/internal/api/lims_api.html Retrieves the experiment ID. ```APIDOC ## Get Experiment ID ### Description Retrieves the experiment ID associated with the current API instance. ### Method GET ### Endpoint /api/lims/experiment_id ### Parameters This method does not take any parameters. ### Request Example ```python api = LimsApi() experiment_id = api.get_experiment_id() print(experiment_id) ``` ### Response #### Success Response (200) - **experiment_id** (int) - The ID of the experiment. ``` -------------------------------- ### Setup Interval Map Source: https://allensdk.readthedocs.io/en/latest/_modules/allensdk/internal/mouse_connectivity/interval_unionize/interval_unionizer.html Builds a map from structure IDs to intervals in a sorted flattened reference space. Requires a segmentation label array as input. ```python def setup_interval_map(self, annotation): '''Build a map from structure ids to intervals in the sorted flattened reference space. Parameters ---------- annotation : np.ndarray Segmentation label array. ''' logging.info('getting flat annotation') flat_annot = annotation.flat logging.info('finding sort') self.sort = np.argsort(flat_annot) logging.info('sorting flat annotation') flat_annot = flat_annot[self.sort] logging.info('finding bounds') diff = np.diff(flat_annot) bounds = np.nonzero(diff)[0] uniques = [ flat_annot[ii] for ii in bounds ] + [flat_annot[-1]] logging.info('building map') lower_bounds = [0] + (bounds + 1).tolist() upper_bounds = (bounds + 1).tolist() + [len(flat_annot)] self.interval_map = {sid: item for sid, item in zip(uniques, zip(lower_bounds, upper_bounds)) if sid not in self.exclude_structure_ids} ``` -------------------------------- ### GET /get_pupil_size Source: https://allensdk.readthedocs.io/en/latest/_modules/allensdk/core/brain_observatory_nwb_data_set.html Retrieves the pupil area in pixels. ```APIDOC ## GET /get_pupil_size ### Description Returns the pupil area in pixels. ### Response #### Success Response (200) - **timestamps** (array) - (Nx1) array of timestamps in seconds. - **areas** (array) - (Nx1) array of pupil areas in pixels. ``` -------------------------------- ### Initialize GridDataApiPrerelease Source: https://allensdk.readthedocs.io/en/latest/allensdk.internal.api.queries.grid_data_api_prerelease.html Initializes the GridDataApiPrerelease client. Optional parameters include storage directories, resolution, and base URI. ```python class GridDataApiPrerelease(GridDataApi): def __init__(_storage_directories_ , _resolution =None_, _base_uri =None_): pass ``` -------------------------------- ### GET /stimuli Source: https://allensdk.readthedocs.io/en/latest/_modules/allensdk/core/brain_observatory_nwb_data_set.html Lists all stimuli presented during the experiment. ```APIDOC ## GET /stimuli ### Description Return a list of the stimuli presented in the experiment. ### Response #### Success Response (200) - **stimuli** (list of strings) - List of stimulus names ``` -------------------------------- ### Main Module Entry Point Source: https://allensdk.readthedocs.io/en/latest/_modules/allensdk/internal/model/biophysical/run_optimize.html The main entry point for the RunOptimize module, which routes commands to specific optimization tasks. ```APIDOC ## main(command, input_json, output_json) ### Description Executes specific optimization tasks based on the provided command string. This function initializes the RunOptimize object and routes the execution flow. ### Parameters - **command** (string) - Required - The operation to perform (e.g., 'nrnivmodl', 'simulate', 'make_fit', 'generate_manifest_lims'). - **input_json** (string) - Required - Path to the input configuration JSON file. - **output_json** (string) - Required - Path to the output JSON file where results will be written. ``` -------------------------------- ### GET /screen_gaze_data Source: https://allensdk.readthedocs.io/en/latest/_modules/allensdk/brain_observatory/ecephys/ecephys_session_api/ecephys_session_api.html Retrieves gaze data from the screen. ```APIDOC ## GET /screen_gaze_data ### Description Retrieves gaze data from the screen. ### Method GET ### Endpoint /screen_gaze_data ### Parameters #### Query Parameters - **include_filtered_data** (bool) - Optional - Whether to include filtered data in the response. ### Response #### Success Response (200) - **data** (pd.DataFrame) - The screen gaze data. ``` -------------------------------- ### Module Entry Point and Command Execution Source: https://allensdk.readthedocs.io/en/latest/_modules/allensdk/internal/model/biophysical/run_optimize.html Defines the main entry point for the module, handling logging configuration and routing commands to the appropriate RunOptimize methods. ```python [docs]def main(command, input_json, output_json): ''' Entry point for module. :param command: select behavior, nrnivmodl or simulate :type command: string :param lims_strategy_json: path to json file output from lims. :type lims_strategy_json: string :param lims_response_json: path to json file returned to lims. :type lims_response_json: string ''' o = RunOptimize(input_json, output_json) if 'LOG_CFG' in os.environ: log_config = os.environ['LOG_CFG'] else: log_config = resource_filename('allensdk.model.biophysical', 'logging.conf') os.environ['LOG_CFG'] = log_config lc.fileConfig(log_config) if 'nrnivmodl' == command: o.nrnivmodl() elif 'info' == command: o.info(input_json) elif 'generate_manifest_rma' == command: o.generate_manifest_rma(input_json, output_json) elif 'generate_manifest_lims' == command: o.generate_manifest_lims(input_json, output_json) elif 'write_manifest' == command: o.write_manifest() elif 'copy_local' == command: o.copy_local() elif 'start_specimen' == command: o.start_specimen() elif 'make_fit' == command: o.make_fit() else: RunOptimize._log.error("no command") print('done') if __name__ == '__main__': import sys command, input_json, output_json = sys.argv[-3:] RunOptimize._log.debug("command: %s" % (command)) RunOptimize._log.debug("input json: %s" % (input_json)) RunOptimize._log.debug("output json: %s" % (output_json)) main(command, input_json, output_json) RunOptimize._log.debug("success") ``` -------------------------------- ### Prepare NWB Output File Source: https://allensdk.readthedocs.io/en/latest/_modules/allensdk/model/biophysical/runner.html Initializes an NWB output file by copying the stimulus file and clearing existing recorded voltages and spike times. ```python def prepare_nwb_output(nwb_stimulus_path, nwb_result_path): '''Copy the stimulus file, zero out the recorded voltages and spike times. Parameters ---------- nwb_stimulus_path : string NWB file name nwb_result_path : string NWB file name ''' output_dir = os.path.dirname(nwb_result_path) if not os.path.exists(output_dir): os.makedirs(output_dir) copy(nwb_stimulus_path, nwb_result_path) data_set = NwbDataSet(nwb_result_path) data_set.fill_sweep_responses(0.0, extend_experiment=True) for sweep in data_set.get_sweep_numbers(): data_set.set_spike_times(sweep, []) ``` -------------------------------- ### GET /atlases Source: https://allensdk.readthedocs.io/en/latest/_modules/allensdk/api/queries/ontologies_api.html Retrieves a list of available atlases. ```APIDOC ## GET /atlases ### Description Retrieves a list of all available atlases from the ontology service. ### Method GET ### Endpoint /atlases ```