sha256
stringlengths
64
64
language
stringclasses
27 values
size
int32
1
491k
lines
int32
1
21.8k
content
stringlengths
1
200k
de2b475d6f1bcf7a252274a0df46071018a6dd8aa08ac4d564134c6e520a7461
Python
950
38
import unittest import numpy as np import numpy.testing as npt import random import sigpy as sp from sigpy.mri import retro from sigpy.mri.dims import * if __name__ == "__main__": unittest.main() class TestApp(unittest.TestCase): def test_find_nonzero_ky_lines(self): kdat = np.zeros([1, 1, 40, 1, 1...
dbf24216747e1335daa6f945081cf3108383f2827808737ef393e441ef080b05
Python
953
28
# This script is part of mousebrains (http://www.github.com/schlegelp/navis-mousebrains). # Copyright (C) 2020 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...
8146e60d1e8e291174e2183cc84c786145ccc78033ac7941a825138fa9d0b499
Python
970
28
import pysam import argparse def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("in_bam") parser.add_argument("out_bam") parser.add_argument("--head-trim", type=int) parser.add_argument("--tail-trim", type=int) return parser.parse_args() if __name__ == "__main__": arg...
5baa51de788666d23b559d11178d4b0153f6e8ac3bc00965b7739737cdb74034
Python
990
25
#!/usr/bin/env python # -*- coding: utf-8 -*- # somnotate --- Automated polysomnography for experimental animal research # Copyright (C) 2019 Paul Brodersen <paulbrodersen+somnotate@gmail.com> # Author: Paul Brodersen <paulbrodersen+somnotate@gmail.com> # This program is free software; you can redistribute it and/o...
ee8f583176840dc2c1cac125e1e87267b61e368a0f4bbf367bed86907c566d65
Python
1,017
40
from argparse import ArgumentParser from . import __version__ import os import cothread from threading import Thread import cv2 import time from softioc import builder, softioc from GoniOwl.GoniOwl_controller import GoniOwlController __all__ = ["main"] print("Hello I am setting up") goniowl_controller = GoniOwlCo...
e4217da4e889d345f1df52451a145a03092012709f167e5dd78d882c7d0c45b6
Python
1,023
34
"""Tests classes in modalities module""" import unittest from pydantic import BaseModel from aind_data_schema_models.modalities import Modality class TestModality(unittest.TestCase): """Tests methods in Modality class""" def test_from_abbreviation(self): """Tests modality can be constructed from ab...
5f8179f9946d3ffbfa55fbf81bd676fc17929c806833684d9d9b14b8e1e99a0f
Python
1,036
33
import zmq from lightparam.param_qt import ParameterTree class ExternalCommunicationSettings(ParameterTree): def __init__(self): super().__init__() class ZMQcomm: def __init__(self, zmq_tcp_address="tcp://localhost:5555", timeout=2): self.zmq_tcp_address = zmq_tcp_address self.timeou...
9263a4f7bda86ee3dcc10c9129f2c42b9deecdbfab7efda20eee037b44896965
Python
1,047
31
from setuptools import setup, find_packages import os # Read the contents of your requirements.txt # This ensures GitHub and Colab install the same libraries you use locally with open("requirements.txt") as f: required = f.read().splitlines() setup( name="spatchcocking", version="0.1.0", author="nchah...
f2e6ac19d507995b7111e8c938ed0406407feb997a68ad7597162c5f5316cedd
Python
1,072
41
import json import sys def validate_json_stream(stream): try: json.load(stream) return True except json.JSONDecodeError as e: print(f"Invalid JSON: {e.msg}", file=sys.stderr) print(f"Line {e.lineno}, column {e.colno}", file=sys.stderr) return False def main() -> int: ...
b48e9b332d71ba7cd039d9c5e8a216d929c4b107093193033a6e47528b39cf83
Python
1,108
39
def abspath(path): import os base_path = os.path.abspath(os.path.dirname(__file__)) return os.path.join(base_path, path) def test_image_nuclei_2d(return_mask=False): """ Fluorescence microscopy image and mask from the 2018 kaggle DSB challenge Caicedo et al. "Nucleus segmentation across imaging e...
ad85119a4351c082fb40597022439318d7e9cf7523f4a6c0c406a4a9fe118a62
Python
1,115
50
from cloudvolume import CloudVolume import numpy as np from copy import deepcopy black = CloudVolume('gs://seunglab-test/test_v0/black') info = deepcopy(black.info) sizes = ( # [128,128,1], # [128,128,2], # [128,128,4], # [128,128,4], # [128,128,8], # [128,128,16], # [128,128,32], # [128,128,64], [128,128,1...
7b3ba07f8405de292e1f7f42c417152782b51ad87706556fd8dd54821c00b57f
Python
1,120
27
import os import pathlib from tetra.utilities import get_platform GPU_BUILD = os.getenv("BUILD_CUDA", "off").lower() in ("true", "1", "on") PLATFORM = get_platform() ROOT_DIR = pathlib.Path(__file__).parent.parent _input_folder_override = os.getenv("INPUT_FOLDER") if _input_folder_override is not None: INPUT_FOLD...
9f78e939fec25f1dcc83ab0eaaff00f119b1b60f5c5268036b8e0f8ea155a00b
Python
1,140
31
import sys import traceback import subprocess from seuronbot import SeuronBot from bot_utils import replyto, download_file from airflow_api import set_variable @SeuronBot.on_message(["update python package", "update python packages"], description="Install extra python packages before starting th...
f9d6548f9bf1328ad713b99ea73273df4cc0a1d74a1ff363cc3c0bc0c887bb62
Python
1,152
50
import unittest import numpy as np import sigpy as sp import sigpy.mri.rf as rf from sigpy.mri.rf import linop if __name__ == "__main__": unittest.main() def check_linop_adjoint(A, dtype=np.float32, device=sp.cpu_device): device = sp.Device(device) x = sp.randn(A.ishape, dtype=dtype, device=device) ...
e3770cabd2d198270153b8ca809969a106abccb672bc11ba8da47d154a26a9c0
Python
1,186
31
from seuronbot import SeuronBot from bot_utils import replyto, download_file from bot_info import broker_url from kombu_helper import drain_messages from airflow_api import set_variable, run_dag @SeuronBot.on_message(["run custom cpu task", "run custom cpu tasks"], description="Run custom cpu tas...
fd5f91e94b2dd165e1c8b854bb9ec77a3cb1c97cd3d42df69d29d559c2c0b7bd
Python
1,227
47
import math import unittest import numpy as np import numpy.testing as npt import sigpy.mri.rf as rf if __name__ == "__main__": unittest.main() class TestTrajGrad(unittest.TestCase): def test_min_gradient(self): t = np.linspace(0, 1, 1000) kx = np.sin(2.0 * math.pi * t) ky = np.cos(...
1e946ddc94cfe68ec24aea7c099ff8083911d1cdd1961a894aaf0bb7296c5df8
Python
1,233
30
import os # These options can be overridden by setting environment variables with # the same names before importing tetra. class ValidationOptions(object): _instance = None def __new__(cls): if cls._instance is None: cls._instance = super(ValidationOptions, cls).__new__(cls) c...
aea4f088f8398db99292c7a0f8364ec3e1bc6e85bdcb82f1fd02580d0339cf65
Python
1,274
45
import re import subprocess import sys def get_latest_version(): tags = str(subprocess.check_output('git tag', shell=True)) tags = re.sub("^b'", '', tags) tags = re.sub("'$", '', tags) tags = re.split(r'\\n', tags) tags = [ tuple(map(int, re.split('\.', tag))) for tag in tags if tag ] tags = sorted(tags, reverse...
3722419242ce2402803da9169ce9c4254e577318c99fc149baf8eb6680c249aa
Python
1,279
33
import os import pysam test_dir = os.path.dirname(__file__) seq_lengths = dict() with pysam.AlignmentFile(os.path.join(test_dir, "resources", "donor_read_sort.bam"), "rb") as in_bam: with pysam.AlignmentFile(os.path.join(test_dir, "resources", "donor_read_sort_mn_tag.bam"), "wb", template=in_bam) as out_bam: ...
8c3dd852096cb29ee9840f65872f7dc4bb54f077c616f9235106c5cd11f69d65
Python
1,293
31
import pandas as pd from rdkit import Chem from rdkit.Chem import AllChem import joblib class XGBoostPredictor: def __init__(self): self.xgboost_clf = joblib.load('xgboost_model1.pkl') self.variance_threshold = joblib.load('variance_threshold1.pkl') def smiles_to_morgan(self, smiles,...
8fedfb290f7de35a5d58b57e99d674f56ec18673e4aa60f6cee9229ca3d3001e
Python
1,302
42
from functools import wraps import os import re import inspect try: import unittest.mock as mock except ImportError: import mock norm_pattern = re.compile(r'[/|.]') def patch_plugin_file(*patch_args, **patch_kwargs): """ Decorator used to search for in items: """ root, filename = os.path.spli...
39fa24aab9c9ee9584bc9d971704c4e56a70c9cb2bb22e844cfe5c277abd821e
Python
1,342
27
import streamlit as st def show_mission(): st.markdown("## 🌍 Our Mission - SRTA City") st.markdown(""" ### 🔬 **Who We Are** We are a research-driven team at **SRTA City**, dedicated to advancing **drug discovery** using Artificial Intelligence. ### 🎯 **Our Goals** - **Predict IC50 & pI...
473ea44839d76d46a764472812b8a77fb8215f5e96cb8a83df11019d7c35f561
Python
1,343
53
"""Module for computer system and architecture definitions""" from enum import Enum class OperatingSystem(str, Enum): """Operating systems""" WINDOWS_8 = "Windows 8" WINDOWS_10 = "Windows 10" WINDOWS_11 = "Windows 11" MACOS_BIG_SUR = "MacOS Big Sur" MACOS_MONTEREY = "MacOS Monterey" MACO...
519d41ccc899f218f3090813030ace10ac104e5be7a064257edd4cd4deab6fa4
Python
1,345
31
import pandas as pd from rdkit import Chem from rdkit.Chem import AllChem import joblib class XGBoostIC50Predictor: def __init__(self): self.xgboost_clf_ic50 = joblib.load('xgboost_model1_IC50.pkl') self.variance_threshold_ic50 = joblib.load('variance_threshold1_IC50.pkl') def smiles...
b9186f63f7161bbd3e371cd2fb53a6cf7d4d2b0d8299b0f7433f91a92ee4cd47
Python
1,371
39
"""The core module contains functions and classes for signal processing. SigPy provides simple interfaces to commonly used signal processing functions, including convolution, FFT, NUFFT, wavelet transform, and thresholdings. All functions, except wavelet transform, can run on both CPU and GPU. These functions are wra...
0494a74014db13def37b6a119d6c43a0718cf151dcd7e68cc41bb5a4be0ce8c4
Python
1,397
65
import matplotlib.pyplot as plt import numpy as np import csv import sys from collections import defaultdict rows = [] filename = sys.argv[1] with open(filename, 'r') as csvfile: votereader = csv.reader(csvfile, delimiter='\t', quotechar=None) for row in votereader: rows.append(row) headers = rows.pop...
0b2a9699db064a28409dcc1a1ded668d374688c95b04113d004f5baea2e88516
Python
1,406
40
"""Dev utilities for constructing models from CSV files""" import re import yaml import requests import pandas as pd from pathlib import Path def to_class_name_underscored(name: str) -> str: """Convert a name to a class name by capitalizing and removing non-alphanumeric characters. Always prefixes the strin...
137f74b039107f14f128920f1d1fe290b4bb6e261f40b39621ba0c5cf409d1f6
Python
1,425
45
import unittest import numpy as np import numpy.testing as npt from sigpy.mri import samp if __name__ == "__main__": unittest.main() class TestPoisson(unittest.TestCase): """Test poisson undersampling defined in `sigpy.mri.samp.poisson`.""" def test_numpy_random_state(self): """Verify that ran...
768cbb312ba34fde09e82c723d3cc48ff5bf0c9d7930e6f88df4285095c7370a
Python
1,492
63
import json from pathlib import Path import os import glob from pathlib import Path from typing import List, Optional, Sequence def load_json(path: str | Path) -> dict: with open(path, "r") as f: return json.load(f) def find_setting_subfolders( main_path: str | Path, subname: str, setting_...
6e0d37aefc86f12f0ee5e911a1609d42af29f35b3625cfb342079c1f9b7ce0fd
Python
1,500
54
from typing import Optional from .sharded import GrapheneShardedMeshSource from .unsharded import GrapheneUnshardedMeshSource from .metadata import GrapheneMeshMetadata from ..metadata import GrapheneMetadata from ....cacheservice import CacheService from ....paths import strict_extract from ....cloudvolume import Sh...
e1911363b973308b2f26bdf428680e74056d147e4c41ae2c4cdc4dba241f79fc
Python
1,518
30
def worker_op(**kwargs): from custom.docker_custom import DockerWithVariablesOperator dag = kwargs['dag'] default_args = kwargs.get("default_args", dag.default_args) return DockerWithVariablesOperator( variables=kwargs["variables"], mount_point=kwargs.get("mount_point", None), ta...
0d966e55819fb6ea2a071b2204023ee372f371f575842e283c920d77e467b1bb
Python
1,523
48
import pandas as pd import numpy as np import argparse import sys import os import re def main(): parser = argparse.ArgumentParser(description='Generate FreeSurfer alike stats2table files from radiomics.csv (see radiomics_extractor).') parser.add_argument( '--file_prefix', type=str, ...
856ebb3c8506737d5f46da756c427fd6ebdacebc2d8119b9faaa897ad977d69a
Python
1,531
44
from kombu import Connection import requests def check_queue(queue): ret = requests.get("http://rabbitmq:15672/api/queues/%2f/{}".format(queue), auth=('guest', 'guest')) if not ret.ok: raise RuntimeError("Cannot connect to rabbitmq management interface") queue_status = ret.json() return queue_s...
2d2629409cbfcf75128d11cbfd8fdc988104714b8ed708e4489ce39a086e9828
Python
1,543
54
import argparse import pathlib import sys from ont_output_specification_validator import ( errors, settings, validate_file, validators, ) from ont_output_specification_validator.specification import ( load_local_specification_bundle, ) from ont_output_specification_validator.validators.fastq impo...
a14d9dc2660e83ff6b6a3fb21c25dc8ab9cc69e5dc39d56365d37260195600e9
Python
1,547
52
import unittest import numpy as np import numpy.testing as npt from sigpy import app, util from sigpy.mri import dce if __name__ == '__main__': unittest.main() class TestDCE(unittest.TestCase): def test_dce(self): # %% DCE Sample Time acq_time = 10 # total acquisition time (minute) t...
9dc97e4101212d1e1a946d715184d6bab8153559cb3a705d2165a5f95c28e3b5
Python
1,550
46
import os import pathlib import subprocess import typing DEBUG = os.getenv("BUILD_TYPE", "Release").upper() == "DEBUG" def run_dorado( cmd_args: list, timeout: int, outfile: typing.IO | None = None, errfile: typing.IO | None = None, ): print("Dorado command line: ", " ".join(cmd_args)) out = ...
4cb8f403c57fa4295be357240f0e35c21ad81bbf21aa5d827b5a679086dbf8a6
Python
1,571
53
import os import pathlib import platform import subprocess from datetime import datetime ROOT_DIR = pathlib.Path(__file__).parent.parent def get_env_or_raise(name: str) -> str: val = os.getenv(name) if val is None: raise Exception(f"Couldn't find environment variable {name}") return val def get...
1d9fca43771c59d1b6e1196a59296c66367d350dba44c455548fd072a00469ae
Python
1,593
47
import pathlib import unittest from contextlib import contextmanager from tetra.regression_manager import RegressionManager, TestResult from tetra.timestamped_context import TimestampedContext class TestContext(object): def __init__( self, test_name: str, manager: RegressionManager, output_folder: pathli...
0381378337435564d232384e29987fa64b5f8db3f1c1c35f3d83f87bd67e0d63
Python
1,596
48
import nibabel as nib import nibabel.processing as nib_processing import nibabel.orientations as nib_orientations import nibabel.funcs as nib_funcs import numpy as np import argparse if __name__ == '__main__': parser = argparse.ArgumentParser(description='Reorient to LIA and resample to 1mm iso-voxel resolution i...
f22d63f17db58450b48fc255a13249a2d463ffa7e36c44b68903aa3be76113c1
Python
1,596
19
#!/usr/bin/env python3 import pandas as pd, os, sys, argparse #for line in open(sys.argv[1], "r"): metadata = pd.read_csv(sys.argv[1]) for row in range(len(metadata)): SAMPLE = str(metadata.loc[row,"SRM_sample_number"]) + "_" + str(metadata.loc[row,"Submitted_sample_name"]) ID = str(metadata.loc[row...
09e089cabcbd267007a0800ec69a156d34040fdb29321af8637aad5fd3a0700d
Python
1,601
50
import time from seuronbot import SeuronBot from bot_utils import replyto, send_message from common.google_api import get_project_data, get_instance_data, get_instance_metadata, set_instance_metadata import tenacity @SeuronBot.on_message("redeploy docker stack", description="Restart the manager ...
f33100bc16a554409c7886450d33bcbc3c34e50a358035377184d5f537680030
Python
1,627
54
import os import pickle import gzip import argparse import mudata import warnings from scenicplus.simulation import simulate_perturbation def load_object(filename): with open(filename, 'rb') as f: return pickle.load(f) def save_object(obj, filename): with gzip.open(filename + '.gz', 'wb') as f: ...
879dc809f99de6cfc6b675cb9dc15dc300267c10b65caff304eda6490840e716
Python
1,630
62
import tenacity from tqdm import tqdm from cloudvolume.connectionpools import S3ConnectionPool, GCloudBucketPool from cloudvolume.threaded_queue import ThreadedQueue from cloudfiles import CloudFiles S3_POOL = S3ConnectionPool('s3', 'seunglab-test') GC_POOL = GCloudBucketPool('seunglab-test') retry = tenacity.retry...
5f768a697f7885725866c5cfee746396e052a2652ec3ed47cdb47fd7a8a91783
Python
1,645
51
from setuptools import setup, find_packages import re VERSIONFILE = "mousebrains/__version__.py" verstrline = open(VERSIONFILE, "rt").read() VSRE = r"^__version__ = ['\"]([^'\"]*)['\"]" mo = re.search(VSRE, verstrline, re.M) if mo: verstr = mo.group(1) else: raise RuntimeError("Unable to find version string i...
7cdcef040e87114ffed9dbd41b33df07d62da6a1b2aa252817e03e594559afc6
Python
1,674
48
import pytest import sys import numpy as np import cloudvolume # Basic test of sharded meshes # The following test files are used from https://storage.googleapis.com: # /neuroglancer-janelia-flyem-hemibrain/v1.0/segmentation/info # /fafb-ffn1-20190805/segmentation/mesh/info # /neuroglancer-janelia-flyem-hemib...
55d3a8f886de2bcd62f6f3c67f9829ecbb58c325a550523e666dd2b9b1461be1
Python
1,701
60
from typing import Optional import os from .metadata import PrecomputedSkeletonMetadata from .sharded import ShardedPrecomputedSkeletonSource from .unsharded import UnshardedPrecomputedSkeletonSource from ..metadata import PrecomputedMetadata from ....cacheservice import CacheService from ....paths import strict_ext...
bba3fba1f8c5608e2ab4bec5cfcf91ddcb86918d22c16655ececfddf15d028a8
Python
1,701
61
import time import pendulum from airflow.decorators import dag, task @dag( schedule=None, start_date=pendulum.datetime(2021, 1, 1, tz="UTC"), catchup=False, tags=["maintenance, segmentation, inference"], ) def easyseg_dag(): @task(queue="cluster", priority_weight=1000) def start_worker(): ...
1bf476337050a2a46b379a8bd51936bcfb2d52e72f05f459bc0c0775367ad511
Python
1,718
65
# -*- coding: utf-8 -*- """ Created on Wed Jul 30 15:51:23 2025 @author: Usuario """ # -*- coding: utf-8 -*- """ Created on Tue May 20 13:11:58 2025 @author: Usuario """ #Librarires import os #For importing images and saving figures import errno # for checking whether the montage direcotry already exi...
54509592f635cbd177acf0ef386ac4212f2a4e1e7c60d4bf1dd8554a66687921
Python
1,729
70
# -*- coding: utf-8 -*- """Methods for computing the geometry factor (g-map) Author: Zhengguo Tan <zhengguo.tan@gmail.com> """ import copy import numpy as np from sigpy import backend, util from sigpy.mri import app def pseudo_replica(app, y, mps, normalize=True, replicas=10): r""" Per...
a98438fbd22a6445641e655ad44984e57d70d64a8fb0147e6457a4f023b43ab1
Python
1,733
56
"""This MRI submodule contains functions and classes for MRI pulse design. It contains functions to design a variety of RF pulses for MRI, such as SLR, adiabatic, parallel transmit, multibanded, and others. The submodule also includes other functions to assist with pulse design, such as I/O functions, trajectory/gradi...
7e89c233068a12edb2a7464d0477383c79999ab83c5ab298c314ad8e676f635a
Python
1,740
30
from __future__ import absolute_import, print_function import warnings def format_warning(message, category, filename, lineno, line=''): import pathlib return f"{pathlib.Path(filename).name} ({lineno}): {message}\n" warnings.formatwarning = format_warning del warnings from .version import __version__ # TODO:...
88842f2a3fa0e698304a396d40615e1bbe5cbdd44c04e88dcd8aa7d7d9bfd5a8
Python
1,747
70
"""Coordinate enums for data schema""" from enum import Enum class Origin(str, Enum): """Origin positions for coordinate systems""" ORIGIN = "Origin" # only exists in Atlases / Images BREGMA = "Bregma" LAMBDA = "Lambda" BETWEEN_C1_C2 = "Between_C1-C2" BETWEEN_C2_C3 = "Between_C2-C3" BET...
042ab3b8f6966032b66fc1011245b6732427188d51c5fd2bbd37f96cdaeda596
Python
1,759
59
import unittest import numpy as np import numpy.testing as npt from sigpy.mri import sms if __name__ == '__main__': unittest.main() class TestSms(unittest.TestCase): def test_slice_order(self): list_NS = [15, 94, 114, 60, 159, 141, 117] list_MB = [ 1, 2, 3, 2, 3, 3, 3] f...
d98bc43e80f199a15c493f6c79ad5edb211844414b7c9f92444f5b506467f46b
Python
1,771
54
"""Configuration file for the Sphinx documentation builder.""" # # For the full list of built-in configuration values, see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html from datetime import date # -- Path Setup -------------------------------------------------------------- from o...
dbbb57db17cd81fcdc1fbd2d940d848f20eb9270a129258fc1275218c9c5d3a2
Python
1,775
62
# -*- coding: utf-8 -*- """Configuration. This module contains flags to turn on and off optional modules. """ import warnings from importlib import util import torch cuda_avail = torch.cuda.is_available() cupy_enabled = (util.find_spec("cupy") is not None) and cuda_avail if cupy_enabled: try: import cup...
e591c2563024ab87f1dd621efdd7e7c43ab946cae79bb039b8096d42db111c26
Python
1,788
60
import pathlib from pandas import concat, read_csv from pandas.errors import EmptyDataError from tetra.error_display import pretty_print_diffs TOLERANCE = 0.0008 # 0.08% def load_sorted_data_frame(path: pathlib.Path): df = None try: df = read_csv(path, sep="\t", index_col="read_id", keep_default_n...
426a677a023b06d9f5d205d4e5ca1cb8121e06821ccbd1bf40784b19efdb7267
Python
1,833
70
from airflow_api import set_variable from bot_info import slack_token, slack_app_token from seuronbot import SeuronBot import os import logging import sys from bot_utils import send_message import subprocess if os.environ.get("VENDOR", None) == "Google": from common.google_api import gce_external_ip else: imp...
3c3a96db8e4b1d13b2c60d12dac0de4ae2b51f55143132e408c59b64f130e891
Python
1,834
54
"""Genes""" import re import requests from pydantic import BaseModel, ConfigDict from aind_data_schema_models.registries import Registry class NucleotideModel(BaseModel): """Nucleotide model""" model_config = ConfigDict(frozen=True) name: str description: str registry: Registry = Registry.GENB...
f6ff4cd59f5750c9879877c6a8f5f57db5e75c8b7b387cc593ec991fe7f620ee
Python
1,834
59
import streamlit as st def show_readme(): st.markdown("## 📖 ReadMe - Bioactivity Prediction") st.markdown(""" ### ℹ️ **Overview** This application predicts the bioactivity of chemical compounds using Machine Learning models. ### 📝 **Instructions** 1. Enter a **SMILES string** manually or **...
d8cbfaa7596160fcc50bd94bf955f648e744c2803b2ea0fe6f6df60c34406518
Python
1,837
68
import nibabel as nib import numpy as np import argparse def get_crop(volume): nonempty = np.argwhere(volume) top_left = nonempty.min(axis=0) bottom_right = nonempty.max(axis=0) return (top_left, bottom_right) def apply_crop(volume, crop): top_left, bottom_right = crop cropped = volume[...
f0e9156a7292c7882eb7bc77fdd7c3ae703bbb65554032ffd4d8d2ede475cfc5
Python
1,845
54
#! /usr/bin/env python3 import pathlib import shutil import unittest from tetra.compare_platforms import PlatformCompare, SpecialCase, compare_platforms class TestComparePlatforms(unittest.TestCase): def setUp(self): self.data_dir = pathlib.Path(__file__).parent / "data" self.input_data = self....
c2e63ef3fe1e287d8ce787ae695116207068cc82df75d3179544cf6a6b485f5e
Python
1,858
69
import unittest import numpy as np import numpy.testing as npt from sigpy.learn import app if __name__ == "__main__": unittest.main() class TestApp(unittest.TestCase): def test_ConvSparseDecom(self): lamda = 1e-9 L = np.array([[1, 1], [1, -1]], dtype=float) / 2**0.5 y = np.array([[1...
cebf8fd8005a6d53ca565595de37b8b65c4ff865af99aa7e6b8359fd5bdf803d
Python
1,869
65
import argparse import pathlib import sys from ont_output_specification_validator import ( errors, settings, validate_file, validators, ) from ont_output_specification_validator.specification import ( load_local_specification_bundle, ) from ont_output_specification_validator.validators.bam import...
7641a7894eecd7c01fde5b744d825fdeb54f5679242a52c721b5bbc75954cbf7
Python
1,876
74
"""Density compensation functions. """ from tqdm.auto import tqdm import sigpy as sp __all__ = ["pipe_menon_dcf"] def pipe_menon_dcf( coord, img_shape=None, device=sp.cpu_device, max_iter=30, n=128, beta=8, width=4, show_pbar=True, ): r"""Compute Pipe Menon density compensation ...
18fcb2ff46659ba88af65e61f8d882cb650d8132bcc1bb5996dba9526c9abb67
Python
1,885
40
"""Integration test for developmental stage ontology lookups (MMUSDV, HSAPDV, FBDV, WBLS).""" import sys from aind_data_schema_models.mouse_developmental_stage import MouseDevelopmentalStage from aind_data_schema_models.human_developmental_stage import HumanDevelopmentalStage from aind_data_schema_models.drosophila_d...
75a0c7c9cb3a97767b646c65859a26cc8b7e353d8946e0afda9d681bd1cfbb4c
Python
1,889
57
import os import re import subprocess from seuronbot import SeuronBot from airflow_api import get_variable from slackbot.bot_utils import replyto def extract_jupyterlab_token(): try: command_output = subprocess.check_output(["jupyter", "lab", "list"], encoding="utf-8") except FileNotFoundError: ...
14e35d7bf1bae9aa7b7b55f3238fa53c4f4a86528c9fad7b669b90b12e2f29e0
Python
1,894
65
from typing import Optional from .image import N5ImageSource from .metadata import N5Metadata from ...frontends.precomputed import CloudVolumePrecomputed from .. import get_cache_path from ...cacheservice import CacheService from ...cloudvolume import ( register_plugin, SharedConfiguration, CompressType, Paralle...
904b7dd413cf9bdcf57e2dcdbf21906126faf23bd9d73670a0b5c542162587c2
Python
1,913
67
import pathlib def reformat_txt(file: pathlib.Path) -> None: # Read it all rows = [] with open(file) as input: while line := input.readline(): rows.append(line) # Sort it, ignoring the header line rows[1:] = sorted(rows[1:]) # Save it with open(file, "w+") as output: ...
eb22f283d8a4799bd0ede639063b58c680a6b50e40907054e3d30ddb21786570
Python
1,922
62
from typing import Optional, Union from .image import BossImageSource from .metadata import BossMetadata from ...frontends.precomputed import CloudVolumePrecomputed from .. import get_cache_path from ...cacheservice import CacheService from ...cloudvolume import ( register_plugin, SharedConfiguration, CompressTy...
cef38de8eb8859abdfbd24cca9f074aa3b3f9c508486c805c2c2b033f47f8731
Python
1,959
65
from typing import Optional from .image import Zarr3ImageSource from .metadata import Zarr3Metadata from ...frontends.precomputed import CloudVolumePrecomputed from .. import get_cache_path from ...cacheservice import CacheService from ...cloudvolume import ( register_plugin, SharedConfiguration, CompressType, P...
e09789c0e7cacaeb05919023955e5e9fb52ae9d15131619c324d3494405348f2
Python
1,959
65
from typing import Optional from .image import Zarr2ImageSource from .metadata import Zarr2Metadata from ...frontends.precomputed import CloudVolumePrecomputed from .. import get_cache_path from ...cacheservice import CacheService from ...cloudvolume import ( register_plugin, SharedConfiguration, CompressType, P...
f4d2303d3ff3f36d3d03ec13d0ac261769be5280166f1efdb55c96b107388166
Python
1,960
57
from configparser import ConfigParser from seuronbot import SeuronBot from airflow_api import set_variable, run_dag from bot_info import broker_url from bot_utils import replyto, download_file, download_json from kombu_helper import put_message @SeuronBot.on_message("update synaptor parameters", ...
818e17b09c1db989ad4a5114ce28c8b5af626c4a8d57834dc643c54270b8833d
Python
1,964
56
import os from .metadata import PrecomputedMeshMetadata from .unsharded import UnshardedLegacyPrecomputedMeshSource from .multilod import ShardedMultiLevelPrecomputedMeshSource, UnshardedMultiLevelPrecomputedMeshSource from ..metadata import PrecomputedMetadata from ....cacheservice import CacheService from ....exce...
36dc572a99e0c74a695cac6da626ebb9f581681e0718881136b226923e187fab
Python
1,969
52
# test reslice """ test for reslice module Also test correctness of ANTS deformation file """ import SUITPy as suit import nibabel as nb def test_reslice_anatomical(): """This uses the forward deformation""" T1_file = 'docs/source/tutorials/sub-ex_T1w.nii.gz' def_file = 'docs/source/tutorials/sub-ex_T1w_to...
44b1af7912ae46c62c5b74712dae31697afc697e788c8dd9c5050602a2397173
Python
1,978
43
""" DropBlock, DropPath PyTorch implementations of DropBlock and DropPath (Stochastic Depth) regularization layers. Papers: DropBlock: A regularization method for convolutional networks (https://arxiv.org/abs/1810.12890) Deep Networks with Stochastic Depth (https://arxiv.org/abs/1603.09382) Code: DropBlock impl inspire...
099406432f789e509a767919df350f5a182d2776a3cafb58c6b69b9bb86ba62b
Python
1,986
62
import pytest import shutil import numpy as np import os from cloudvolume import Storage, CloudVolume from cloudvolume.lib import Bbox, Vec, min2, max2, find_closest_divisor TEST_NUMBER = np.random.randint(0, 999999) CLOUD_BUCKET = 'seunglab-test' layer_path = '/tmp/removeme/' def create_storage(layer_name='layer...
040a87cead40aeafc683b491519de5de7fcfbf72affc148958eea7cb8dc5fe8f
Python
2,007
69
"""Custom layers as equinox modules""" import jax import equinox as eqx from math import sqrt from ._utils import default_floating_dtype from jax import Array from jax.random import PRNGKey from typing import Optional from jax.typing import DTypeLike class ConstantLayer(eqx.Module): """Constant layer.""" we...
aaa2304129c34444039806ef128cd9e47807f97260b5b0d67b7b9137850fad80
Python
2,020
67
# -*- coding: utf-8 -*- """Wavelet transform functions. """ import numpy as np import pywt from sigpy import backend, util __all__ = ["fwt", "iwt"] def get_wavelet_shape(shape, wave_name="db4", axes=None, level=None): zshape = [((i + 1) // 2) * 2 for i in shape] tmp = pywt.wavedecn( np.zeros(zshape...
42941db095e044da10f0ada88299b734a1196623f0a4a1648be4082b6a9726cb
Python
2,032
76
import unittest import numpy as np import numpy.testing as npt import sigpy.mri.rf as rf if __name__ == "__main__": unittest.main() class TestMultiband(unittest.TestCase): def test_multiband(self): # slr pulse tb = 8 N = 512 d1 = 0.01 d2 = 0.01 p_type = "ex" ...
3cb988769f00631859b542e2ba59c4b12733ae3e24e9402e9b44118fcd177fe6
Python
2,038
101
import pytest from cloudvolume.lru import LRU import time import random import sys def test_lru_size_w_tuple(): lru = LRU(int(1e6), size_in_bytes=True) assert lru.nbytes == 0 val = (1, b'0' * 1000, b'1' * 1000) lru[1] = val ans = ( sys.getsizeof(val) + sys.getsizeof(val[0]) + sys.getsizeof(va...
c972a9c46b22e508222fbbf468d466f7eb140f53c0c9bcbf08555bd1e6c1045f
Python
2,051
63
import numpy as np from numba import jit @jit(nopython=True) def make_arc(cx, cy, radius, n_segments=12, is_left=True): """ Make an half-circle arc with the centre cx, cy with n_segments poic """ angles = np.linspace( (3 * np.pi / 2 if is_left else -np.pi / 2), np.pi / 2, n_segments ) ...
fc599ab04316116c1dca72dcc94afd9933ff4db0e693ba239543dd62cb094a5d
Python
2,055
93
# -*- 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 #######################################################...
aecace1315bd043f0fc75d612da87905eb5fc99873b50e018a1a246d7ebc2326
Python
2,064
91
from cloudvolume.threaded_queue import ThreadedQueue from functools import partial def test_threading(): execution_count = 1000 executions = [] def reset_executions(): return [ False for _ in range(execution_count) ] def addone(idnum, should_be_none): executions[idnum] = True assert should_b...
cc47022928f1327801bf5454418dd86f165991c0b62cb639a4176d76310b1a78
Python
2,072
53
import sys import torch import torch.nn as nn import torch.nn.functional as F import numpy as np class MLP(nn.Module): ''' Single layer MLP for either 3D joint angle prediction (regression) or action classification. Input: (N, M, T, J, C) ''' def __init__(self, task='regression', num_classe...
3d7bd6649314ac9e5465a4e9a97e9bae7b1d698da15c716116ccdb735312b0a5
Python
2,083
59
# -*- coding: utf-8 -*- """ Created on Fri Jan 20 16:31:34 2023 @author: simon """ from poisson_input import gaussian_filtered_poisson_spikes from poisson_input_interneurons import theta_filtered_spikes import pathlib import numpy as np import pandas as pd # Get the path of the current script base_pa...
e56c9b2e3401cdef7de512a95bd5ed6d7f059eef868d69945ff0e3c6235d633d
Python
2,091
57
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If ex...
14c5f88c65f8353f9865ead3ebca6e4ad2b60df0fa2b36027de2b2f4f841c3f2
Python
2,129
73
import unittest import numpy as np import numpy.testing as npt from sigpy import config, thresh if config.cupy_enabled: import cupy as cp if __name__ == "__main__": unittest.main() class TestThresh(unittest.TestCase): def test_l2_proj(self): x = np.ones(5) y = np.full(5, 1 / 5**0.5) ...
ed1e480adaecdd9f2183dfc81155e989b3b84940e2ae1f06e573987802859784
Python
2,182
63
#!/usr/bin/env python """ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % example script to generate simulated interacting brain regions and % perform Current-Based Decomposition (CURBD). Ref: % % Perich MG et al. Inferring brain-wide interactions using data-constrained % recurrent neural ...
94b290e217b0baec6bfd361d77685c1cff9b8ecf735115fcb04b16a0ac4e494a
Python
2,195
67
import unittest import numpy as np import numpy.testing as npt import sigpy.mri.rf as rf if __name__ == "__main__": unittest.main() class TestB1sel(unittest.TestCase): def test_b1sel_generic(self): dt = 2e-6 # sampling period d1 = 0.01 # passband ripple d2 = 0.01 # stopband rippl...
d087d955233591f596f8169d46814b94f9b11a61c4f25363053efce2d433add7
Python
2,195
70
"""Script to pull developmental stage ontology term names from the EBI OLS4 API. One-off/manual refresh script (like get_protocols.py) — not run automatically by run_all.sh. Re-run this and commit the resulting CSVs when an ontology release adds or renames terms. """ import pandas as pd import requests API_BASE = "h...
a1af4d73522fb1b91e1e10e2da72e965048bc7a70a93d1308d9a67fc25d3b60d
Python
2,290
69
""" This script creates a 2-minute synthetic NWB file with 3 electrical series for testing the pipeline. Requirements: - spikeinterface - pynwb - neuroconv """ import spikeinterface as si from pathlib import Path from pynwb import NWBHDF5IO from pynwb.testing.mock.file import mock_NWBFile, mock_Subject from neurocon...
9fa0ecd85108e927327f895f9f98443927b715c51101629f0476935f581cc6c1
Python
2,307
68
"""Data utilities.""" import jax.numpy as jnp from datasets import Dataset, Features, Array2D def shrink_trajectory_len(dataset: Dataset, new_traj_len: int) -> Dataset: """Reshapes a dataset to shrink trajectory length and increase number of examples This is to optimise GPU usage when the trajectory length ...
61ff3f71b472e6302acc5555dbb156b0a58b0c503c9a752aed1959b68059c7e9
Python
2,334
75
# Configuration file for the Sphinx documentation builder. # # For the full list of built-in configuration values, see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Project information ----------------------------------------------------- # https://www.sphinx-doc.org/en/master...
2035a216dbdad698228299b86af498ae97ff9a31fc45294e876dbfc84a8b5e5e
Python
2,379
82
from intern.remote.boss import BossRemote from intern.resource.boss.resource import ChannelResource, ExperimentResource, CoordinateFrameResource from ...secrets import boss_credentials from cloudvolume.datasource.precomputed.metadata import PrecomputedMetadata class BossMetadata(PrecomputedMetadata): def __init__(s...
a59f70543aef0dd1ef6ea0d539fb196cdac6ef8a424fb32f08113aa5a91413d9
Python
2,385
75
def read_chunks(f, s_i, t_j, p_ji): import struct unpack_count = struct.Struct('q').unpack unpack_seg = struct.Struct('qq').unpack unpack_seg_pair = struct.Struct('qqq').unpack while True: count_data = f.read(8) if count_data: count, = unpack_count(count_data) els...
aa3891d3c0cd74bacae126e779f9e5e0c1392d5c29c153aff01e032fad6f9d74
Python
2,402
67
# The based unit of graph convolutional networks. import torch import torch.nn as nn class ConvTemporalGraphical(nn.Module): r"""The basic module for applying a graph convolution. Args: in_channels (int): Number of channels in the input sequence data out_channels (int): Number of channels p...
609c5effcaf70731d70a505587f8ce340def7d4417a92a390f39f82b710b8c33
Python
2,410
67
#!/usr/bin/env python """Train a model on data sets for which manual annotations exist. This model can then be loaded at a later time point to automatically annotate new data sets. """ import numpy as np from data_io import ( ArgumentParser, load_dataframe, check_dataframe, load_state_vector, loa...
765250beac342c2437e9be264d40a88441053492dcfe9bbe31926c3dbc06274a
Python
2,410
55
"""Process names""" from enum import Enum class ProcessName(str, Enum): """Process names""" ANALYSIS = "Analysis" COMPRESSION = "Compression" DENOISING = "Denoising" EPHYS_CURATION = "Ephys curation" EPHYS_POSTPROCESSING = "Ephys postprocessing" EPHYS_PREPROCESSING = "Ephys preprocessing...
4f5e551e93884b57b1a3bfef5e1a5a04686f3e8f7569d0a844ff1b96194e0072
Python
2,422
80
""" Adjust brightness and contrast for images in a directory. Example: python adjust_brightness_contrast.py \ --input-dir ./outputs/disagreements \ --output-dir ./outputs/adjusted \ --brightness-delta 20 \ --contrast-delta 0.1 """ import argparse import os from pathlib import Path import numpy as n...
f01087cbe4789d421eb133a23b390cd1088fa058a5a53446ec8bdeca8374814d
Python
2,423
58
# -*- coding: utf-8 -*- """ Created on Fri Sep 20 15:41:24 2024 @author: simon """ def my_style(): """ Create custom plotting style. Returns ------- my_style : dict Dictionary with matplotlib parameters. """ # color pallette fsize = 12...