sha256
stringlengths
64
64
language
stringclasses
27 values
size
int32
1
491k
lines
int32
1
21.8k
content
stringlengths
1
200k
668eb5165ceb4c44c57a234ad5abd1a727092403486992faaf444ab35cc8a6b7
Python
2,431
70
#!/usr/bin/env python3 """ This script creates a 3-minute synthetic recording and saves it to SpikeInterface format for testing the pipeline. Requirements: - spikeinterface """ from argparse import ArgumentParser import spikeinterface as si from pathlib import Path this_folder = Path(__file__).parent si.set_global_...
379899ce239ceac54c0c19f3b67fec74d2933bdf8a7accca697fcc91c1177f1c
Python
2,442
104
# -*- coding: utf-8 -*- """ Created on Sat Dec 23 18:42:59 2023 @author: CAG329 """ # Packages #################################################################### from brian2 import * # %matplotlib qt matplotlib.rcParams.update({'font.size': 13}) # Parameters #######################################################...
8a95e72f3979db08356fc343e84cb188aa5595b596c14dd82df34abaa84355bf
Python
2,462
81
import pyvisa from math import acos class LaserPowerControl: def __init__( self, port="COM4", baudrate=921600, parity=pyvisa.constants.Parity.none, encoding="ascii", device=1, *args, **kwargs ): super().__init__(*args, **kwargs) s...
bd0c9dca9d211b850f0062360dc96a895649ae54dbaf4f8e405c7b30fde282e4
Python
2,464
64
# test flatmap """ Unit test for flatmap unit @author: jdiedrichsen """ import unittest import SUITPy.flatmap as flatmap import numpy as np import plotly.graph_objs as go import nibabel as nb import matplotlib.pyplot as plt def test_flatmap_plot(render='plotly'): ax = flatmap.plot('docs/source/notebooks/MDTB08_Mat...
a32477edf50c31822e403a5f1cd3d4b33e1c4830f3239cacec34ab7670090423
Python
2,483
79
import unittest import numpy as np import numpy.testing as npt from sigpy.mri import rf if __name__ == "__main__": unittest.main() class TestAdiabatic(unittest.TestCase): def test_bir4(self): # test an excitation bir4 pulse n = 1176 dt = 4e-6 dw0 = 100 * np.pi / dt / n ...
b6b36b4d2ec50c47d8bde92449cd04c1626231d722ab31e616657f4679e7aa00
Python
2,500
66
import json from workers import GenerateWorkers from manager import GenerateManager from easyseg_worker import GenerateEasysegWorker from nfs_server import GenerateNFSServer from networks import GenerateNetworks def GenerateConfig(context): common_ext = f"{context.properties['zone']}.c.{context.env['project']}.in...
8f6eb0a7088c344e51dcd309cb99d79df923add96393981db1b091c4f00af577
Python
2,623
92
import torch import numpy as np import torch.nn as nn import torch.optim as optim from sigpy.mri import dce # %% class DCE(nn.Module): def __init__(self, ishape, sample_time, R1 = 1., M0 = 5., R1CA = 4.39, FA = ...
2909b2771a0217def75a4471f45b6d4de9c2a10a32966d3857e65e9ba1b40187
Python
2,641
79
import time from dags.google_api_helper import toggle_nfs_server from seuronbot import SeuronBot from bot_utils import replyto, extract_command, clear_queues from airflow_api import get_variable, set_variable, \ check_running, mark_dags_success, run_dag from bot_info import broker_url from kombu_helper import drain...
16015482b7a978555d5c538a6aa6e2fbdf3ff254f6cdf8e7d87df5ce8fbacfbc
Python
2,669
67
# -*- coding: utf-8 -*- """ Created on Sat Dec 9 19:49:52 2023 @author: CAG329 """ # From https://brian2.readthedocs.io/en/stable/user/plotting_functions.html # Packages #################################################################### from brian2 import * matplotlib.rcParams.update({'font.size': 14}) # Parame...
f2c7676ec705c54b99e36ebaa1f50671d10b7f73e3308592f7223cd605e95382
Python
2,681
93
# %% [markdown] # # Notebook 03: Tissue thickness mapping # # **Paper section:** Results — The cranial neural tube maintains a # dorso-ventral thickness gradient # **Paper figures:** Fig. 5 # # This script quantifies local tissue thickness by measuring the Euclidean # distance from each vertex on the **basal (outer) su...
4cc7e72b7d73a34042125fd94aba1b4106298ba48f1ae710d6404b28b5826627
Python
2,682
78
import streamlit as st import py3Dmol import base64 from rdkit import Chem from rdkit.Chem import AllChem, Draw from rdkit.Chem.Draw import rdMolDraw2D import streamlit_ketcher as sk def generate_3d_view(smiles, style="stick"): mol = Chem.MolFromSmiles(smiles) if mol: mol = Chem.AddHs(mol) # Add hydro...
b316673b962aacc0ecc0025ef8d38cbf344052c03e85bab1fffc8f7810e80f62
Python
2,706
85
# This script is part of mousebrains (http://www.github.com/schlegelp/navis-mousebrains). # Copyright (C) 2024 Philipp Schlegel # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, e...
7ad1e6194de4c254c0358417e6ef7a1652de14e74a0d746233b0a6abc7cdb5ac
Python
2,722
68
"""Unit tests for the Gene model, focusing on GenBank accession ID retrieval.""" import unittest from pathlib import Path from unittest.mock import Mock, patch from aind_data_schema_models.gene import Gene, NucleotideModel class TestGene(unittest.TestCase): """Tests for Gene model""" def setUp(self): ...
837e48fc88539e8c4565c81245a0607d614e906768464dc95916e0e670998c7a
Python
2,724
79
import os os.environ["JAX_PLATFORM_NAME"] = "cuda" os.environ["XLA_PYTHON_CLIENT_MEM_FRACTION"] = "0.95" import jax jax.config.update("jax_enable_x64", True) import equinox as eqx import sys sys.path.append('..') sys.path.append('../..') import hydra import logging from omegaconf import DictConfig from UIDD.traine...
4cee4d15b09cfe06c5f316e671974e82561edb689731777f5cb9a5b9e3fa22db
Python
2,744
87
# -*- coding: utf-8 -*- """Non-Linear MRI reconstruction applications. """ import numpy as np import sigpy as sp from sigpy import backend, nlls, fourier from sigpy.mri import nlop, app, epi class kinv(nlls.NonLinearLeastSquares): r"""non-linear mri reconstruction. Args: """ def __init__(self, y, im...
0fb03f4a2c48285f0af3a2275b9417d6342e99b1133586b8bd6d7928ab30970d
Python
2,782
79
from airflow.plugins_manager import AirflowPlugin from datetime import datetime import logging import types import collections from airflow.models import BaseOperator from airflow.models import DagBag from airflow.utils.state import State from airflow import settings class MultiTriggerDagRunOperator(BaseOperator): ...
c57835199030c76a36f8f6ffe28221121b2874ddc8e2b89664bba5c26581ae21
Python
2,782
74
from igneous_and_cloudvolume import submit_igneous_tasks, submit_custom_cpu_tasks, submit_custom_gpu_tasks from airflow import DAG from airflow.operators.python import PythonOperator from airflow.utils.weight_rule import WeightRule from datetime import datetime from slack_message import task_failure_alert from helper_o...
d6987ee82b5fcd1ff1234fd3ed37c312d2df909a263a524a68e041d90ca62b7c
Python
2,787
69
#!/usr/bin/env python """ Convert hypnograms to matlab array. """ import numpy as np from scipy.io import savemat from example_pipeline.data_io import ( ArgumentParser, load_dataframe, check_dataframe, load_state_vector, ) def convert_hypnogram_to_mat(file_path_hyp, file_path_mat, mapping, time_res...
15f15195820fc127b2b8d421f3d11819a45cf950f4dd0e71a6ee2b8a17afa91c
Python
2,803
91
def GenerateInternalFirewallRules(context, network, sourceRanges): return [{ 'name': f'{context.env["deployment"]}-firewall-internal', 'type': 'compute.v1.firewall', 'properties': { 'allowed': [ { 'IPProtocol': 'tcp', }, ...
da3bb646b7701ce8ae0e16e7c87cc3d6242e84b386e1047d2e765adc79676086
Python
2,804
93
#!/usr/bin/env python3 """ Make a .keras model compatible with older Keras 3 versions by stripping unsupported keys like 'quantization_config' from the saved config. A .keras file is a zip archive containing config.json and weight files. This script patches config.json in-place so the model loads on older Keras 3. """...
1146b467a807013c39a14d0be62e7b0c835ce1717dc35d2fa3bc220d17ba6056
Python
2,815
77
# %% # Set vedo backend to VTK — required for Jupyter notebooks from vedo import settings settings.default_backend = "vtk" # Import all spatchcocking utilities (includes getTightercmap, getAxis, etc.) from spatchcocking import * # %% # Discover all VTK mesh files in the meshes folder. # Files are sorted: 3 × HH17 (in...
a34597e9a9521fa6b127dd56dba4166d081d44ff9958f3932dd88bebc047e12c
Python
2,857
81
import os os.environ["JAX_PLATFORM_NAME"] = "cuda" os.environ["XLA_PYTHON_CLIENT_MEM_FRACTION"] = "0.95" import jax jax.config.update("jax_enable_x64", True) import equinox as eqx import sys sys.path.append('..') sys.path.append('../..') import hydra import logging from omegaconf import DictConfig from UIDD.trainer...
d24e78bf9f035f5434d3e238cf092dfd43cd24ee893182ab67a6e0fabb51d486
Python
2,860
173
"""Module for defining UnitWithValue classes""" from enum import Enum from typing import Union class SizeUnit(str, Enum): """Enumeration of Length Measurements""" M = "meter" CM = "centimeter" MM = "millimeter" UM = "micrometer" NM = "nanometer" IN = "inch" PX = "pixel" class MassU...
c9762ecacf2962ad094a4c4c23594b3a526de729bdb94660961ec593d07fa7db
Python
2,864
87
# -*- coding: utf-8 -*- """ Created on Sun Sep 10 07:49:50 2023 @author: CAG329 """ # Original code from # https://brian2.readthedocs.io/en/stable/examples/IF_curve_Hodgkin_Huxley.html # Packages #################################################################### from brian2 import * # %matplotlib qt matplotlib.rc...
0d4f5dcccb21d4766ab6e6c12236a770ad516884ffe34e98cecbf793994f02ac
Python
2,874
72
import sys import torch import torch.nn as nn import torch.nn.functional as F class ActionHeadClassification(nn.Module): def __init__(self, dropout_ratio=0., dim_rep=512, num_classes=60, num_joints=17, hidden_dim=2048): super(ActionHeadClassification, self).__init__() self.dropout = nn.Dropout(...
323e0408803b529ce25b6c4e841c15629f9b2120ab3e20471aca3fcc4481fb8f
Python
2,877
97
import mudata import os import scanpy as sc import anndata import matplotlib import matplotlib.pyplot as plt import adjustText import numpy as np import pandas as pd import pickle # Function to save an object def save_object(obj, filename): with open(filename, 'wb') as f: pickle.dump(obj, f) # Fun...
fbc6f8119c7b28187bf190b32899aa86512d5929c5b6954838d7d065d896ee0a
Python
2,933
92
"""Script to grab protocol information from protocols.IO using the official API. Requires you set PROTOCOLS_CLIENT_TOKEN environment variable with your API token, from protocols.io/developers """ import re import requests import pandas as pd import os OUTPUT_CSV = "src/aind_data_schema_models/_generators/models/pro...
5b4c9128002e550efd6d9883a95028601e7d51321e46a6da4305fcbb39dd7691
Python
2,939
85
# %% Imports import sys import numpy as np import matplotlib.pyplot as plt # %% Parse the command line arguments args = sys.argv if len(args) != 5: raise ValueError("Following arguments need to be given: session, epoch, trial type, quality threshold") session = args[1] epoch = args[2] trialtype = args[3] quality_...
a2a9ef9b499cb1d7c82a7c480f2874807efbccd7679d68309cdc4c047abd778f
Python
2,981
72
import pandas as pd from rdkit import Chem from rdkit.Chem import AllChem, Descriptors import joblib import tensorflow as tf from keras.layers import TFSMLayer class NeuralNetworkPredictor: def __init__(self): self.nn_model = TFSMLayer('multi_tasking_model_converted', call_endpoint='serving_defaul...
f7f1fef2375448146fe2ad96f8a43d1b84e24d74b7dbaae791341b234eb86228
Python
2,988
79
#! /usr/bin/env python """ Setup script for SUITPy, a python package for cerebellar neuroimaging. """ descr = """A python package for cerebellar neuroimaging.""" import sys import os from setuptools import setup, find_packages _SUITPy_INSTALL_MSG = 'See %s for installation information.' % ( 'https://suitpy.read...
5f89dc1856529ce782e31095aa29a8f687e28653b1adb5ff2f75ed7d7b6a2b27
Python
3,020
80
import unittest from numpy import nan from pandas import DataFrame from pandas.testing import assert_frame_equal from tetra.error_display import ( col_match, find_value_differences, pretty_print_diffs, row_match, ) class TestErrorDisplay(unittest.TestCase): def setUp(self): self.headers ...
c42f12f5734096ec01ba22aa1466d926b0fc4723bc37f3126abe50398089eb1d
Python
3,035
131
"""Diffusion Vector Sets (dvs) for the use of customized diffusion directions on the scanner Author: Zhengguo Tan <zhengguo.tan@gmail.com> """ import numpy as np from pathlib import Path list_CoordinateSystem = ['xyz', 'prs'] list_Normalisation = ['unity', 'maximum', 'none'] def _read_directions(line_str): lin...
972465a46fb0f0596c7c578348e319c979b656bb81bf06050e2957a9aed29d1a
Python
3,041
62
import streamlit as st def weto_ai_slider(value): weto_ai_slider = st.slider(label = "slider", help = """ Set the confidence range for the A.I. Classifier\n\nThe default confidence range is from 60 to 100.\n\n \n\nSamples will be classified a...
c173b70337df25be102431e340710e03269b04c0d73c7d8560882cf5eb0425af
Python
3,043
109
from datetime import datetime, timedelta def check_worker_image_labels(variable): from airflow.models import Variable from docker_helper import pull_image if variable == "param": image_name = "WORKER_IMAGE" default_path = default_seg_workspace elif variable == "inference_param": ...
6021f0bf7a6f055ab562a574a38f98792062bbfc6274feb5e58c92e62e8db8cb
Python
3,056
88
"""Module to publish models to docdb""" import csv import os from typing import Iterator, List from aind_data_access_api.document_db import Client as DocDBClient from requests import HTTPError DOCDB_HOST = os.getenv("DOCDB_HOST") DOCDB_DATABASE = os.getenv("DOCDB_DATABASE") DOCDB_COLLECTION = os.getenv("DOCDB_COLLEC...
bceb1fcd01f2d8b8d052ad2cdd42bd78e3d899e0f18cbd6e3e8720351a655aec
Python
3,064
117
"""Neuroglancer link functions.""" import json import urllib from typing import Optional, Union from collections import OrderedDict from dataclasses import dataclass from enum import Enum class LayerType(Enum): Image = "image" Segmentation = "segmentation" @dataclass class Layer: name: str cloudpath...
197890fefcc3b0d114181a40611232124a3771f22c7e2623e34581e7f902236e
Python
3,070
105
from airflow.utils.db import provide_session from cloudfiles.paths import to_https_protocol, ascloudpath, ExtractedPath def resolve_url(url: str) -> str: """Resolves protocol aliases and returns a https url.""" if url.startswith("gs://"): return url result = to_https_protocol(url) if isinstanc...
c383c568757b53004cdf318dd080d32dd0a11452ac92a38212e1fba928bc043d
Python
3,076
119
""" # Custom activations This module contains custom activation functions. """ import jax import jax.numpy as jnp # ------------------------- Typing imports ------------------------- # from jax import Array from jax.typing import ArrayLike from typing import Callable # --------------------------------------------...
73f92fc79fa9580e8b7f52ce2d83b7cda6f8e8dcf2b2773a0b7e70786a275a97
Python
3,099
113
import os import sys import numpy as np import cloudvolume.sharedmemory as shm def test_ndarray_fs(): location = 'cloudvolume-shm-test-ndarray' array_like, array = shm.ndarray_fs( shape=(2,2,2), dtype=np.uint8, location=location, lock=None, emulate_shm=True ) assert np.all(array == np.zeros(shape=(2,2,2), d...
eb0fbc23f555a280d145a7f40e85e3b24d92a49445b12e3808baa283808bf7ba
Python
3,103
98
# -*- coding: utf-8 -*- """ Created on Sun Sep 10 07:50:08 2023 @author: CAG329 """ # Original code from # https://brian2.readthedocs.io/en/stable/examples/IF_curve_Hodgkin_Huxley.html # Packages #################################################################### from mpl_toolkits.axes_grid1.inset_locator import z...
0bc64ab87a046719101e8b8b47fdb84eb2893cc9f601e30b6460da81ccefc052
Python
3,119
97
from typing import Optional, Union from .mesh import GrapheneMeshSource from .metadata import GrapheneMetadata from ..precomputed.image import PrecomputedImageSource from ..precomputed.skeleton import PrecomputedSkeletonSource from .. import get_cache_path from ...cacheservice import CacheService from ...cloudvolume ...
a57d02f4419070eaf2924e450a1f6822eb0dceb8cc1e4f061a7e6783b83689a8
Python
3,128
93
"""Check that sorter params in default_params.json match SpikeInterface defaults. For each sorter, the keys of its ``sorter`` block are compared (recursively) against ``spikeinterface.sorters.get_default_sorter_params``: - Keys present in the pipeline but unknown to SpikeInterface (typos, renamed or removed params)...
cc34ff45d70bf155cf626bd3966f2039d067f3c6bc185a1d0afdd5ac8535d322
Python
3,159
126
from cloudfiles.exceptions import CompressionError, DecompressionError from osteoid.exceptions import ( SkeletonUnassignedEdgeError, SkeletonDecodeError, SkeletonEncodeError, SkeletonTransformError, SkeletonAttributeMixingError, ) class AuthenticationError(Exception): """Incorrect credentials.""" pass ...
4d1431c8cef761a53940e2cef61c5a80205481ed7c18f154bea27091f7807621
Python
3,184
86
import numpy as np class RankItemEnv: def __init__(self, n_items: int) -> None: self.n_items = n_items self.micro_time = 1 self.code_book = np.eye(n_items,n_items+1) self.train_pairs = [(i,j) for i in range(n_items) for j in range(n_items) if i!=j] self.train_label...
6127568cf0a53028fe628180ec21c6c3355dd5b6dcf43726d9ea6164ce0bfcaa
Python
3,193
81
import numpy as np import scipy.special as scipy_special import nibabel as nib import os import sys import argparse import ants def save_img(img, dst, name, ref_img): fname = '{}/{}.nii.gz'.format(dst, name) niftiImg = nib.Nifti1Image(img, ref_img.affine) niftiImg.header['xyzt_units'] = 2 # mm nib.sa...
cfd2448887dd151e2d15e717ce6d3c971df6fc916533b601959a00015dcee11f
Python
3,204
94
import pytest import os import json from layer_harness import delete_layer from cloudvolume.provenance import DataLayerProvenance, DatasetProvenance from cloudvolume.storage import Storage def test_dataset_provenance(): fs = '/tmp/removeme/provenance/' delete_layer(fs) prov = DatasetProvenance() prov.data...
8e4a0d8bc1916fbb84195a64d62b926afcd689c82c29417def3cd9573653e942
Python
3,211
109
"""Code generator for data schema models.""" import argparse from jinja2 import Environment import pandas as pd from aind_data_schema_models._generators.dev_utils import to_class_name, to_class_name_underscored from pathlib import Path import subprocess SKIP_SORT = ["mouse_anatomy"] def check_black_version(): ...
71fe94d8097d79476f8f686f5224246ba0d22b86bd5a227957f3d2868943d68a
Python
3,228
106
# -*- coding: utf-8 -*- """ Created on Sun Sep 10 07:50:01 2023 @author: CAG329 """ # Original code from # https://brian2.readthedocs.io/en/stable/examples/IF_curve_Hodgkin_Huxley.html # Packages #################################################################### from brian2 import * # %matplotlib qt matplotlib.rc...
2232874083be482d9f51135a5b54b5cdd4f7aa0e71d5352832fb73d8e402279b
Python
3,240
97
""" A "serverless" Python client for reading and writing arbitrarily large Neuroglancer Precomputed volumes both locally and on cloud services. Precomputed volumes consist of chunked numpy arrays, meshes, and skeletons and can be visualized using Neuroglancer. Typically these volumes represent one or three channel ...
8648cf866137c54e79c1c06aff94cefa8d6e629debc5426584eda2bee5b2291b
Python
3,242
114
# ------------------------------------------------------------- # Subgrid Optimization # Copyright (c) 2026 # Dirk Keller, Nick Ramsey's Lab, University Medical Center Utrecht, University Utrecht # Licensed under the MIT License [see LICENSE for detail] # ----------------------------------------------------------...
d9b24d058e8a2d28ec90f5b7ab2bd43028744f6071b01d98e1530aa2ab51f424
Python
3,262
79
import pandas as pd import argparse import sys import glob import os import re REGEX_SUBCORT = '^(?!lh-|rh-).*' REGEX_LH = '(SUBJECT.*)|(^lh.*)' REGEX_RH = '(SUBJECT.*)|(^rh.*)' def collect_stats(directory, filename): df = None for f in sorted(glob.glob('{}/*/{}'.format(directory, filename))): df_su...
4adda0a71eb1fd0e13ebd6c78c70f7b279447c3adfb62a94499321301d63d377
Python
3,274
116
"""Module for defining our data naming conventions""" from datetime import datetime from enum import Enum class RegexParts(str, Enum): """Regular expression components to be re-used elsewhere""" DATE = r"\d{4}-\d{2}-\d{2}" TIME = r"\d{2}-\d{2}-\d{2}" DATETIME = r"\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}"...
58bdefaa5ce48e5e5dc4ff4e30200d159d00f2170a853dee0780dcbf38e71fa5
Python
3,304
119
import pyvisa class MotorControl: def __init__( self, port, baudrate=921600, parity=pyvisa.constants.Parity.none, encoding="ascii", axes=None, ): self.baudrate = baudrate self.parity = parity self.encoding = encoding self.port = p...
84155ef30c0bbdae7540f6fa92c009745bdae6b7a09ce0c55708d6514ade7600
Python
3,402
85
import os import shutil import zipfile import gdown # Configuration # Example URL: https://drive.google.com/file/d/1XyZ.../view # Extract the long string of letters and numbers; that is your FILE_ID. FILE_ID = "1UTYNFWWDvkyErYEemTks-va95H3-LqKP" ZIP_TMP_PATH = "temp_downloaded.zip" TARGET_DIR = "./" def download_and...
43f3a813d75c1baf5b5aadf668dda916d9319c608db29cf94d6730ce734f9712
Python
3,425
94
import os os.environ["JAX_PLATFORM_NAME"] = "cuda" os.environ["XLA_PYTHON_CLIENT_MEM_FRACTION"] = "0.48" import jax jax.config.update("jax_enable_x64", True) import equinox as eqx import sys sys.path.append('..') sys.path.append('../..') from utils.data import shrink_trajectory_len import hydra import logging from o...
0ddaa6f16885a287f5f552b65c30ccb5067d6ed235c2a660ee3aaf028fd04165
Python
3,438
95
import os import pytest import sys import numpy as np from cloudvolume import dask as dasklib @pytest.mark.skipif(sys.version_info[0] < 3, reason="Python 2 not supported.") def test_roundtrip_3d(): da = pytest.importorskip('dask.array') du = pytest.importorskip('dask.utils') a = da.random.randint(100, size=(3,...
df9da3b883f3af47669508170e8cb81f33841428972f58b6c24fcd2013792fd8
Python
3,447
112
import os import json import numpy as np from tqdm import tqdm from .lib import mkdir, save_images class VolumeCutout(np.ndarray): def __new__(cls, buf, path, cloudpath, resolution, mip, layer_type, bounds, handle, *args, **kwargs): return super(VolumeCutout, cls).__new__(cls, shape=buf.shape, buffer=np.asfo...
89ebe8f8ae179e103f52e08f2ad22fe0649c6be340114d37115fb192685192ad
Python
3,464
114
import os from http.server import BaseHTTPRequestHandler, HTTPServer import json import re import numpy as np from tqdm import tqdm from cloudfiles import CloudFiles from cloudvolume.lib import Vec, Bbox, mkdir, save_images, yellow from cloudvolume.paths import ExtractedPath DEFAULT_PORT = 8080 RANGE_RE = re.com...
c2b876b08c703e58cabdfe0353579022ca168557f3f35f97ed2617d6ccac3537
Python
3,510
122
# -*- coding: utf-8 -*- """MRI RF shimming. """ import numpy as np import sigpy as sp from sigpy import backend from sigpy.mri import rf as rf __all__ = ["calc_shims", "init_optimal_spectral", "init_circ_polar"] def calc_shims(shim_roi, sens, x0, dt, lamb=0, max_iter=50): """RF shim designer. Uses the Gerchber...
f102f71d79576b5ab8f0924c9f958b3b59ec22320f9388913467bebc742c0b9d
Python
3,510
135
import queue as Queue import threading import time from functools import partial import boto3 from google.cloud.storage import Client import tenacity from .secrets import google_credentials, aws_credentials from .exceptions import UnsupportedProtocolError retry = tenacity.retry( reraise=True, stop=tenacity.sto...
caa8589a4c576cf7546000f42b612210c5d63683e202cea6643c11b30e48c680
Python
3,524
125
# -*- coding: utf-8 -*- """MRI utilities. """ import numpy as np import sigpy as sp __all__ = ["get_cov", "whiten", "tseg_off_res_b_ct", "apply_tseg"] def get_cov(noise): """Get covariance matrix from noise measurements. Args: noise (array): Noise measurements of shape [num_coils, ...] Returns...
902bb974f9e2069aabe14c3379602f2639d6fdf07d3d2f1a5bcb1245d84031cb
Python
3,530
119
from typing import Optional, Union, Iterable from dataclasses import dataclass import os import posixpath from cloudfiles import CloudFiles import numpy as np import numpy.typing as npt from .metadata import PrecomputedAnnotationMetadata from ....cacheservice import CacheService from ....paths import strict_extract...
148dc42533b6be50c0f7036e6f98b18d3ed42275d8433f928585e3313af0de73
Python
3,545
92
import pendulum from airflow import DAG from airflow.operators.python import PythonOperator metrics_default_args = { 'owner': 'seuronbot', 'depends_on_past': False, 'start_date': pendulum.datetime(2019, 2, 8), 'catchup': False, 'retries': 3, } def format_uptime(dt): for attr in ["weeks", "day...
472138b842e5f2e489a0b46402288b6939b6cd1464f662fc580b662f05f9a035
Python
3,548
122
# ------------------------------------------------------------- # Channel Elimination # Copyright (c) 2024 # Dirk Keller, Nick Ramsey's Lab, University Medical Center Utrecht, University Utrecht # Licensed under the MIT License [see LICENSE for detail] # -----------------------------------------------------------...
c5b1ca29696f43b6ec95590abddfe2d613a78d785fbacc84baae5e0bb2ac0f3e
Python
3,550
122
import unittest import numpy as np import numpy.testing as npt from sigpy import linop, prox, util if __name__ == "__main__": unittest.main() class TestProx(unittest.TestCase): def test_L1Reg(self): shape = [6] lamda = 1.0 P = prox.L1Reg(shape, lamda) phase = np.exp(1j * np....
9916f41523527af97444dbcd648c8c54af07a5bddefaa2d7cff5b0163a914e89
Python
3,554
131
import pickle import unittest import numpy as np import numpy.testing as npt from sigpy import backend, util if __name__ == "__main__": unittest.main() class TestUtil(unittest.TestCase): def test_device(self): device = backend.Device(-1) pickle.dumps(device) def test_dirac(self): ...
8cd825a172dcd183285c342003cee0471597709638762c4d645f017fc9f2d2d5
Python
3,556
79
import torch import torch.nn as nn class SimpleTemporalModel(nn.Module): def __init__(self, num_joints_in, in_features, output_dim, filter_widths, dropout=0.25, channels=1024, task='classification'): """ A simplified temporal model with 1D convolutions and adaptive average pooling. ...
a220ab1481b5dbd34b988cb6bbf6d4fba34941bd540aa55df5a3c62463618808
Python
3,580
87
"""Test mouse anatomy class methods""" import unittest from unittest.mock import patch from aind_data_schema_models.mouse_anatomy import search_emapa_exact_match, get_emapa_id from aind_data_schema_models.mouse_anatomy import MouseAnatomy, MouseAnatomyModel, Registry class MouseAnatomyTests(unittest.TestCase): ...
6c8f3c6c963e591c73ea972167c98350939d2256a9713e91956bef1dca99939f
Python
3,590
120
# -*- coding: utf-8 -*- """Optimal Control Pulse Design functions. """ from sigpy import backend __all__ = ["blochsim", "deriv"] def blochsim(rf, x, g): r"""1D RF pulse simulation, with simultaneous RF + gradient rotations. Assume x has inverse spatial units of g, and g has gamma*dt applied and assume x ...
b889e9f14d3a736d34fb0cd219a1944882494e6802aba14275c7098c5019b844
Python
3,635
127
# -*- coding: utf-8 -*- """ Created on Mon May 27 14:28:36 2024 @author: CAG329 """ # Packages #################################################################### from brian2 import * # %matplotlib qt matplotlib.rcParams.update({'font.size': 13}) # Parameters #######################################################...
8164ff72d879cad6601b74b0194c4d3c5df2be26c8afbc37bd8259bdfab6e2aa
Python
3,665
165
import sys from tqdm import tqdm from .lib import totalfn from .threaded_queue import ThreadedQueue, DEFAULT_THREADS def schedule_threaded_jobs( fns, concurrency=DEFAULT_THREADS, progress=None, total=None ): if total is None: try: total = len(fns) except TypeError: # generators don't have...
0e876dbd4d041ae805e48470b9fecb200c593a12a6e63fe0bcb161765cfac296
Python
3,670
106
#!/usr/bin/env python """ Using a pre-trained model, and given the preprocessed signal arrays, compute the probability of each state for each sample in the signal array. """ import numpy as np import matplotlib.pyplot as plt from somnotate._automated_state_annotation import StateAnnotator from somnotate._utils impo...
f47bb1013bef770b40153a8b4c463d953e90830f31d2058d92c9f04b6d632b80
Python
3,671
124
import math import numpy as np from ...lib import Vec, Bbox def content_type(encoding): if encoding == 'jpeg': return 'image/jpeg' elif encoding == 'png': return 'image/png' elif encoding == 'jxl': return 'image/jxl' elif encoding in ('compresso', 'compressed_segmentation', 'fpzip', 'kempressed',...
e6ae217be7bbfaebffa01b2334e53143874850eba855535dfb52394eb955f669
Python
3,705
92
import nibabel as nib import numpy as np import os import argparse import torch from HD_BET.run import run_hd_bet if __name__ == '__main__': parser = argparse.ArgumentParser(description='Brain extraction (skull-stripping) using HD-BET.') parser.add_argument( '--mp2rage-inv2', type=str, ...
fa60210e196ab02c57922a940b0f793ab2be86b8ce2e9e1cd2314fc84585934d
Python
3,709
114
# -*- coding: utf-8 -*- """ Created on Sun Sep 10 07:49:50 2023 @author: CAG329 """ # Original code from # https://brian2.readthedocs.io/en/stable/examples/IF_curve_Hodgkin_Huxley.html # Packages #################################################################### from brian2 import * # %matplotlib qt matplotlib.rc...
49624692cd607af574d8cfdf815ac9e8e9aa1d8e3df0b9b2538b25c38dd9b685
Python
3,720
138
import os import setuptools import sys def read(fname): with open(os.path.join(os.path.dirname(__file__), fname), 'rt') as f: return f.read() def requirements(): with open(os.path.join(os.path.dirname(__file__), 'requirements.txt'), 'rt') as f: return f.readlines() EM_CODECS = [ "imagecodecs", "simpl...
a4b74ac94b7be58d5736f25048b0439594e49d0c1fa0dcc33e02110faad06bbc
Python
3,720
132
""" Methods for DICOM loading, extraction and saving. Author: Zhengguo Tan <zhengguo.tan@gmail.com> """ # %% import numpy as np import os import pydicom import os.path import sys sys.path.insert(0, os.path.join(os.environ['BART_PATH'], 'python')) import cfl from optparse import OptionParser # __all__ = ['extract_e...
87fa3cbdb020e995c9ecf6c3a05f48c736be8d1d511b6f3855c0c43bd00c9806
Python
3,724
100
import os import subprocess import sys from datetime import datetime psutil_available = True try: import psutil except ImportError: print("CPU monitoring unavailable") psutil_available = False VERBOSE = False def get_process_priority(pid: int) -> str: if psutil_available: return str(psutil.P...
f3c5b3237097eab9bb3f7b9d7a1906c9228e56b286e8f9efbf80cddb209be969
Python
3,729
127
"""SDE utilities""" import jax import jax.numpy as jnp import equinox as eqx from diffrax import ( diffeqsolve, ControlTerm, Euler, ItoMilstein, MultiTerm, ODETerm, SaveAt, VirtualBrownianTree, ) import sys sys.path.append('../..') from UIDD._utils import default_floating_dtype # ----...
5e29624d8076059fba92612075faeaaa115a26c106fc1f5021a950435b47072d
Python
3,760
91
from worker_op import worker_op from airflow.utils.weight_rule import WeightRule from datetime import timedelta from param_default import default_args, cmd_proto, default_mount_path, default_seg_workspace from slack_message import task_retry_alert import os def composite_chunks_wrap_op(img, dag, config_mounts, queue,...
00c888080c72a46009cb7d9837e714da18b1172c91d47077f7b31aaf0a53d828
Python
3,775
109
# %% [markdown] # # Notebook 04: pHH3+ mitotic cell density mapping # # **Paper section:** Results — Spatial patterns of mitotic activity are # preserved across global expansion # **Paper figures:** Fig. 6 # # This script maps the local density of pHH3+ mitotic cells onto the # basal surface mesh. # # **Method:** # 1. ...
088e7b49f27f690829be70980e52eb5df13310241920b7ba7552fbbc9b78eb1c
Python
3,782
181
"""Device enums for data schema""" from enum import Enum class ImagingDeviceType(str, Enum): """Imaginge device type name""" BEAM_EXPANDER = "Beam expander" SAMPLE_CHAMBER = "Sample Chamber" DIFFUSER = "Diffuser" GALVO = "Galvo" LASER_COMBINER = "Laser combiner" LASER_COUPLER = "Laser co...
68117a4dd12bb0fbf62dafa79f852f7eacd61ee048b278489744c58c3b798139
Python
3,792
89
import unittest from data_paths import ROOT_DIR, REFERENCE_FOLDER from tetra.compare_platforms import PlatformCompare, SpecialCase, compare_platforms class TestCompareData(unittest.TestCase): def test_compare_platforms(self): """ This compares test results from different platforms. As new tests a...
fbf0a51cef48a006835993c60a34a9184b249e86bca1574c6acf9bd1d165a332
Python
3,815
105
import pathlib from dataclasses import dataclass from tetra.data_frame_utils import load_sorted_data_frame from tetra.error_display import pretty_print_diffs @dataclass(slots=True) class SpecialCase: pattern: str tolerance: float | None @dataclass(slots=True) class PlatformCompare: reference_path: path...
c5846b6520005ae58df06957076edd1d952d510d2c93a4b1caead86f9dcbfde8
Python
3,846
91
"""Test human developmental stage class methods""" import unittest from unittest.mock import patch from aind_data_schema_models.human_developmental_stage import search_hsapdv_exact_match, get_hsapdv_id from aind_data_schema_models.human_developmental_stage import ( HumanDevelopmentalStage, HumanDevelopmentalS...
c2404e598748bf50b23e3318b9c7ee9127483108b075522ef65d90a249bac7ba
Python
3,856
159
import python_jsonschema_objects as pjs import orjson import json5 dataset_provenance_schema = { "$schema": "http://json-schema.org/draft-04/schema#", "id": "DatasetProvenance", "title": "Dataset Provenance", "description": "Represents a dataset and its derived data layers.", "required": [ "dataset_name"...
92403efe0fc3eeff41b22799f09a2d4692132d232a2eca79669ca7ef257c534d
Python
3,861
91
"""Test mouse developmental stage class methods""" import unittest from unittest.mock import patch from aind_data_schema_models.mouse_developmental_stage import search_mmusdv_exact_match, get_mmusdv_id from aind_data_schema_models.mouse_developmental_stage import ( MouseDevelopmentalStage, MouseDevelopmentalS...
860b065971540628976eb10d74edcfe7973bde43a0a583e12f9f0feacef122a8
Python
3,888
100
# Compute a version number from a git repo or archive # This file is released into the public dodls-python3-release. Generated by: # versiongit-2.1 (https://github.com/dls-controls/versiongit) import re import sys from pathlib import Path from subprocess import STDOUT, CalledProcessError, check_output # These will be...
eed77f4f5fed76b36d7515a0be0c43be8d0dab230ee0fa7cba75709fe0dc1003
Python
3,896
91
"""Test C. elegans developmental stage class methods""" import unittest from unittest.mock import patch from aind_data_schema_models.celegans_developmental_stage import search_wbls_exact_match, get_wbls_id from aind_data_schema_models.celegans_developmental_stage import ( CElegansDevelopmentalStage, CElegansD...
718e6f1d30410bb39f05d67d8dd4164b80f4dbfbf44d4c7b749d44213a8a86da
Python
3,907
101
from cothread import catools from softioc import builder import tensorflow as tf from tensorflow import keras import cv2 from io import BytesIO import urllib from time import sleep import numpy as np import datetime try: import epicscorelibs.path.cothread except ImportError: pass # 20250714-111015_epoch20_bi...
79aac8a1cb1a17cf7a8e9ffdab068782bc043c0db6c6d4f88e1a5bddb013d34f
Python
3,908
91
"""Test drosophila developmental stage class methods""" import unittest from unittest.mock import patch from aind_data_schema_models.drosophila_developmental_stage import search_fbdv_exact_match, get_fbdv_id from aind_data_schema_models.drosophila_developmental_stage import ( DrosophilaDevelopmentalStage, Dro...
6e3fb9b2b62d0f891ddecb2431453456bf905fcf4e7961f33c8ec1cce422aadf
Python
3,940
108
# -*- coding: utf-8 -*- """ Created on Wed Mar 18 15:25:03 2026 @author: simon """ import numpy as np import matplotlib.pyplot as plt from plotting_functions import my_style from matplotlib.gridspec import GridSpec import seaborn as sns; sns.set_theme() import pickle import pandas as pd import pingouin ...
55b647cae90855a481c5bb6662764b42907a28b8ae6e694fa4b0e333992cc660
Python
3,947
101
#!/usr/bin/env python """ Truncate manual state annotations and preprocessed datasets to a given (start, stop) interval. Truncated files will have the same name as the original apart from a suffix noting the start and stop time points. """ import numpy as np import matplotlib.pyplot as plt import pathlib from somnot...
c0c57881a6ed81205bf2d065f3c8b78687cbdee7f8123dce6d2dac2e00197e2f
Python
3,999
135
# -*- coding: utf-8 -*- """Functions for interoperability between sigpy and pytorch.""" import numpy as np from sigpy import backend, config __all__ = ["to_pytorch", "from_pytorch", "to_pytorch_function"] def to_pytorch(array, requires_grad=True): # pragma: no cover """Zero-copy conversion from numpy/cupy arra...
a6397a33e6460633b46dfaf5c229b4c4821e45c2641ebf3cdbda261ac56cd037
Python
4,016
135
import unittest import numpy as np import numpy.testing as npt import sigpy as sp import sigpy.mri.rf as rf if __name__ == "__main__": unittest.main() class TestSlr(unittest.TestCase): def test_st(self): # check to make sure profile roughly matches anticipated within d1, d2 N = 128 ...
7d2f0df3476b57a5788d7259354d517a00aae39d5aa3a396d6a255992ee41c29
Python
4,031
138
from cloudfiles import CloudFiles from cloudvolume.datasource.precomputed.metadata import PrecomputedMetadata from cloudvolume.lib import jsonify, Vec, Bbox from ...provenance import DataLayerProvenance class N5Metadata(PrecomputedMetadata): def __init__(self, cloudpath, config, cache, info=None): # some ...
5c3c6a04605f9cc9d4c1d7f333ab0e414a2ee69870178fc950242ad5be212e63
Python
4,058
126
# -*- coding: utf-8 -*- """ Created on Fri Nov 4 16:15:55 2022 @author: spiros """ import os import brian2 import numpy as np import pathlib # Get the path of the current script base_path = pathlib.Path().resolve().parent def theta_prob(spike, f_theta, phi_theta): """ Theta-like probab...
68237220c449fa6512f92b828aa1dc500b9cb1f5b23d2bd893c1d4f4f33d51ec
Python
4,096
126
""" Generate a histogram of average image intensity for all images in a directory tree. Also writes a CSV with per-image averages and summary statistics. Useful for determining high/low values for over/under exposed images Example: python intensity_histogram.py \ --input-dir ./outputs/disagreements \ --outpu...
86bf72c06841b7988daa4a751eb0a0392477ef86eabf4f0e6adea151f541c302
Python
4,197
109
import sys import re import logging import json import shutil import time from pathlib import Path import numpy as np from aind_data_schema.core.quality_control import QualityControl data_folder = Path("../data") results_folder = Path("../results") logging.basicConfig(level=logging.INFO, stream=sys.stdout, format...
4c5a4896128a2cbefa36640f98a0e04886eb60733d26415cca6d7d423dc8ad07
Python
4,219
89
import pandas as pd import glob import os import matplotlib.pyplot as plt import matplotlib.image as mpimg dodgy_data = [] dodgy_data.append("2024-08-01-09-02-27") dir = "/dls_sw/i23/logs/GoniOwl" start_date_cutoff = "2023-01-01" # Only process files from this date onwards (YYYY-MM-DD format) csvs = glob.glob(os.pa...