sha256
stringlengths
64
64
language
stringclasses
27 values
size
int32
1
491k
lines
int32
1
21.8k
content
stringlengths
1
200k
d76058f782d57f1fd25189056721bba11ad81274bbdf2484d2f9940715912766
Python
4,229
125
import os import redis import time from param_default import redis_databases def _get_redis_connection(db_name: str): if "REDIS_SERVER" not in os.environ: return None redis_host = os.environ["REDIS_SERVER"] db_number = redis_databases[db_name] return redis.Redis(host=redis_host, db=db_number,...
4a23776f0cd1326b66a3a50e649fce9f270df90f8efb7d3ba927524c406bfb65
Python
4,261
177
# -*- coding: utf-8 -*- """Functions for simulations. """ import numpy as np __all__ = ["shepp_logan"] def shepp_logan(shape, dtype=complex): """Generates a Shepp Logan phantom with a given shape and dtype. Args: shape (tuple of ints): shape, can be of length 2 or 3. dtype (Dtype): data typ...
66504672c28c4d9eeccf2ed57cd14868edb0d1a9d97de05741d07c393045f2a2
Python
4,325
113
from common import ZonalComputeUrl, GenerateBootDisk, GenerateNetworkInterface, GenerateAirflowVar from common import INSTALL_DOCKER_CMD, INSTALL_NVIDIA_DOCKER_CMD, INSTALL_OPS_AGENT from workers import GenerateCeleryWorkerCommand, GenerateEnvironVar, GenerateDockerCommand def GenerateEasysegWorker(context, hostnam...
781b8c1a8f65ead001abf585a1625978deef9997a865f732dfbad1217cc93a74
Python
4,335
162
# -*- coding: utf-8 -*- """ Created on Mon Jul 7 19:32:53 2025 @author: Usuario """ #Run after main script #im = 4 import matplotlib.pyplot as plt masks_Tc2 = masks_Tc.copy() masks_Nuc2 =masks_Nuc.copy() image = imgs[im] name = fields[im] masks_Tc = masks_Tc[im] masks_Nuc = masks_Nuc[im] dummy...
bdd3e575307365f738bf422bbb20c9b9b7c7f744cbc99477691af1f3a4e0a1e4
Python
4,357
134
import unittest import numpy as np import numpy.testing as npt from sigpy import util from sigpy.mri import epi if __name__ == '__main__': unittest.main() class TestEpi(unittest.TestCase): def test_get_B(self): b_0 = np.zeros((1, 1)) b_1 = np.ones((6, 1)) b = np.concatenate((b_0, b...
03be0e0565c2ab4027424ba326b7d9f57c4b16ab60a798fe58b21cb4b6a6251a
Python
4,394
135
from __future__ import print_function from intern.remote.boss import BossRemote from intern.resource.boss.resource import ( ChannelResource, ExperimentResource, CoordinateFrameResource ) from .. import autocropfn, readonlyguard, ImageSourceInterface from ... import exceptions from ...lib import ( colorize, red...
f995e6febe6175905eeaa3eb22d9ea7b740b14117ffeb4b9bf4831d1835fa3f6
Python
4,405
113
import unittest import numpy as np from sigpy import config, interp if config.cupy_enabled: import cupy as cp if __name__ == "__main__": unittest.main() class TestInterp(unittest.TestCase): def test_interpolate_spline(self): xps = [np] if config.cupy_enabled: xps.append(cp)...
3e7061dda053de9e5dd987bee50dc80e4f6220df6cb9bb622c3c1018a0da98b6
Python
4,419
211
# -*- coding: utf-8 -*- """Thresholding functions. """ import numba as nb import numpy as np from sigpy import backend, config, util __all__ = [ "soft_thresh", "hard_thresh", "l1_proj", "l2_proj", "linf_proj", "psd_proj", ] def soft_thresh(lamda, input): r"""Soft threshold. Performs...
23c8ad0f7132028cb75b6d4f5c14fda02cb8aa0a52e3dc4c67b038165d7cf3db
Python
4,515
121
import asyncio import functools import logging import base64 import fasteners from slack_down import slack_md import markdown from bs4 import BeautifulSoup import contextvars from IPython.core.magic import (Magics, magics_class, line_cell_magic) from IPython.display import display, HTML, Image, IFrame from kombu_help...
e7c943d6e9f53c2f16eb086639d7dd0a243095002adcb14255fa579e8b1b3954
Python
4,516
107
import numpy as np import quantities as pq import neo from elephant.conversion import BinnedSpikeTrain def concatenate_spiketrains(spiketrains, interval): st = list(spiketrains.values())[0][0] trial_duration = (st.t_stop - st.t_start).rescale('s').magnitude + interval concat_spiketrains = [] for sts ...
8374415cecbd62c428c368e1930b26b54d22ec424beecef82dd17fefcd2884dc
Python
4,532
115
import argparse import os import sys import pathlib import radiomics import SimpleITK as sitk import csv import pandas as pd LABELS_FS = ['Left-Lateral-Ventricle', 'Left-Inf-Lat-Vent', 'Left-Thalamus-Proper', 'Left-Caudate', 'Left-Putamen', 'Left-Pallidum', '3rd-Ventricle', '4th-Ventricle', 'Brain-Stem',...
55eba56eb398e3aa1535cafba1e9ab380d2650c266c8f9cea852fb8df6a6a2c5
Python
4,600
132
from lightparam.gui.precisionslider import PrecisionSingleSlider import qdarkstyle from PyQt5.QtWidgets import ( QApplication, QWidget, QHBoxLayout, QGridLayout, QDoubleSpinBox, QLabel, ) from PyQt5.QtGui import QColor from PyQt5.QtCore import Qt, pyqtSignal, QPointF, QTimer class MotionContr...
ade5de04f03de8c47dae923ac4776e0e601bde949b85a3fd8cdaaef44af59414
Python
4,616
127
def health_check_info(image_name): from slack_message import slack_message image = pull_image(image_name) try: if 'Healthcheck' in image.attrs['Config']: slack_message(f':cool:Image `{image_name}` has builtin health check!') return True except: pass slack_me...
e50daf20955733a4463583ef70c663efc75641bb6e72be3da5179a1b0de6106b
Python
4,647
191
from collections import defaultdict from copy import deepcopy import time import re import json import socket from operator import mul from functools import reduce import numpy as np from cloudvolume import CloudVolume N = 3 CHUNK_SIZES = ( (128,128,1), (128,128,2), (128,128,4), (128,128,8), (128,128,16), (12...
7ff477e11d9c747a62dd5f2d0ff85e9fd86e9390cbf11a15c9da8f973f19eabf
Python
4,672
134
# -*- coding: utf-8 -*- """MRI pulse-design-specific linear operators. """ import sigpy as sp from sigpy import backend def PtxSpatialExplicit(sens, coord, dt, img_shape, b0=None, ret_array=False): """Explicit spatial-domain pulse design linear operator. Linear operator relates rf pulses to desired magnetizat...
aefc4e487e27892cf34392295b4cc6868da6b9760532f10d6dbd788423eccbff
Python
4,678
169
# -*- coding: utf-8 -*- """MRI preconditioners. """ import sigpy as sp __all__ = ["kspace_precond", "circulant_precond"] def kspace_precond( mps, weights=None, coord=None, lamda=0, device=sp.cpu_device, oversamp=1.25 ): r"""Compute a diagonal preconditioner in k-space. Considers the optimization problem...
27bb34ca7caf67358b5804a4a494135b4aa2c3b55a2fc7d431b98e275fb42383
Python
4,702
152
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Aug 1 16:07:14 2025 @author: camille """ # Packages #################################################################### from brian2 import * matplotlib.rcParams.update({'font.size': 12}) # %matplotlib qt # Parameters ###############################...
5de55a3c305d8a45bb222d815ab8e1dff8ccc26920a929d236a1f34166c57c93
Python
4,754
149
# -*- coding: utf-8 -*- """Functions for GRAPPA. This implementation makes use of the function "sp.array_to_blocks" to slide through calibration as well as undersampled k-space data to perform GRAPPA kernel fitting and reconstruction. Alternatively, one can also use other functions, e.g. "view_as_windows" in skimage....
7162c43f6ef58073b538148dc38af5a23d4bc4d8dfa6265f524d18350f883950
Python
4,758
141
import warnings warnings.filterwarnings("ignore") # GENERAL IMPORTS import os import sys # this is needed to limit the number of scipy threads # and let spikeinterface handle parallelization os.environ["OPENBLAS_NUM_THREADS"] = "1" import argparse import numpy as np from pathlib import Path import json import pickl...
01edfd086006e489b0a3ae3c8a210cd0f2b7a9066c83bfa360a7a4d60dc005ae
Python
4,762
140
#!/usr/bin/env python """ Utilities to convert sleepsign output files. """ import numpy as np from somnotate._utils import convert_state_vector_to_state_intervals from example_pipeline.data_io import ( ArgumentParser, load_dataframe, check_dataframe, export_hypnogram, ) SLEEPSIGN_KEY = dict([ ...
693e5c2bed85cdec87cf608d850fb27eb09c314ac35c9232f81cc28ad7bd8d3e
Python
4,770
142
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Module to resample image into atlas space @authors: Jorn Diedrichsen """ import nibabel as nib import numpy as np from numpy.linalg import inv import nitools.volume as ntv def reslice_image( source_image, deformation, ma...
c188f4dd149acf1ad5985c86de1ce6494bd181efb3d75fcde0bae29090cb2172
Python
4,785
123
"""Brain atlas tests""" import unittest from aind_data_schema_models.brain_atlas import CCFv3 class TestCCFStructure(unittest.TestCase): """CCFStructure tests""" def test_from_id_valid(self): """Test from_id method with valid IDs.""" # Test with a few known IDs structure = CCFv3.from...
4661ec0fe730f141f09b74ef4488aaed73512b7f94325c7cf6968f00a714fc9e
Python
4,823
142
#! /usr/bin/env python3 import pathlib import shutil import unittest from tetra.regression_manager import RegressionManager, TestFile, TestResult class TestRegressionManager(unittest.TestCase): KEEP_OUTPUT_DATA = False # Set to True to keep file for debugging def setUp(self): self.data_dir = path...
f21cadfe8b3e7c3ded00cc2cba5e11270e2261528947b41da32ba68a6616e5b8
Python
4,838
110
import pandas as pd import numpy as np import scipy.stats as stats import nibabel as nib import os import sys import csv import skimage.segmentation as segmentation import scipy.spatial as spatial import argparse # get cortical labels def get_labels(offset): lut = pd.read_csv('{}/fs_lut.csv'.format(os.path.dirnam...
813ca4caec56b857d8bf91d5e94277c584bb85ecdded1a214b225e04eac29d22
Python
4,841
152
""" losses.py Loss functions used in RESURF/MISRGRU training. Notes ----- - All losses assume spatial dimensions are the last two dims (..., H, W). This works for shapes like: (H, W) (C, H, W) (B, C, H, W) (B, T, H, W) because rfft2 operates on the last two dimensions by default. - `fourier_space...
55aaf34a77eaf5f54b16bebe9bb64df4770266bfce90c489ce7c8183a745dc90
Python
4,876
158
from typing import Optional import numpy as np import numpy.typing as npt from ..sharding import ShardingSpecification, ShardReader, synthesize_shard_files from ....skeleton import Skeleton from ..spatial_index import CachedSpatialIndex from ....exceptions import EmptyFileException from cloudfiles import CloudFiles ...
98b31a157bf21d479e10b76f4cf9f324bc4c2bc4e7ac437f53e30c368bd3399c
Python
4,913
129
import torch from torch import nn from torch.nn import functional as F class _NonLocalBlockND(nn.Module): def __init__(self, in_channels, inter_channels=None, dimension=3, sub_sample=True, bn_layer=True): super(_NonLocalBlockND, self).__init__() assert dimension in [1, 2, 3] self.dimensi...
fab7759c20ce6d76b0a84f05fcea08acdd79e931380537b1335cfe42ac00ce08
Python
4,941
125
from airflow.utils import db as db_utils from airflow.models import Variable from airflow import models from common.google_api import get_project_data, get_instance_data, get_instance_metadata, set_instance_metadata from param_default import param_default, inference_param_default, synaptor_param_default import os impor...
5090773a1cd9ebfd1022af5729aa922571f3a1b0bbd2e0532b86605af1e56fe9
Python
4,971
159
# -*- coding: utf-8 -*- """Methods for Echo-Planar Imaging (EPI) acquisition: * retrospectively undersampling phase-encoding direction * split shots within one diffusion encoding * find non-zero ky lines from Cartesian k-space data Author: Zhengguo Tan <zhengguo.tan@gmail.com> """ import numpy as np from .dims i...
43174c976dc45a85258b77e07b179404962cf3c07a2df925c1775033613b9812
Python
5,005
141
# -*- 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...
11b98669868e6c3924007cdd1836292233150c1242f3bbf058a76a7ed2627f14
Python
5,028
144
""" This dag autoscales your cluster. This only works with docker-compose (local) and Infrakit (swarm). For Infrakit, the following environment variables must be set: - INFRAKIT_IMAGE - what docker image to use for infrakit i.e.infrakit/devbundle:latest - INFRAKIT_GROUPS_URL - the location of the groups js...
f5d92ceec53225b25099473b5d5d09fd9dcdca6cd86208a04b1dad122c1ebd12
Python
5,042
140
import numpy import pandas def pretty_print_diffs(exp, act, tolerance=0): # First we check which rows/columns fail to match pretty_diffs = [] r_match, r_exp, r_act = row_match(exp, act) if r_exp: pretty_diffs.append( "SizeError({} Rows only in expected: {})".format( ...
7af7e794e6e7a25c8025b8a18a84d8bf7940f0b8a868796564f8790e4e131b54
Python
5,048
176
# %% [markdown] # # Notebook 01: Mesh generation from TIFF mask # # **Paper section:** Methods — Neural tube segmentation # **Paper figures:** Fig. 1c–d (segmented lumen meshes) # # This script converts two binary 3D TIFF segmentation masks (inner lumen and # outer basal surface) into smoothed, decimated triangulated s...
291cd60ba529e6f4d29e4d3c9375224639a2452f0d8cbb68105bd36f3c369474
Python
5,050
130
from googleapiclient import discovery import requests import json def get_project_data(key): apiurl = f"http://metadata/computeMetadata/v1/project/{key}" response = requests.get(apiurl, headers={"Metadata-Flavor": "Google"}) response.raise_for_status() return response.text def get_instance_data(key): ...
55f7e356c01ec6d846981c552cf5c30bac2ba1c3f01a5cc62bbfc4070558df7a
Python
5,050
149
import os.path from .. import exceptions, paths from ..lib import yellow, Bbox, Vec, toabs, xyzrange, min2 from ..secrets import CLOUD_VOLUME_CACHE_DIR, CLOUD_VOLUME_DIR import numpy as np NON_ALIGNED_WRITE = yellow( """ Non-Aligned writes are disabled by default. There are several good reasons not to use the...
fb0f563c3b6fc17651bc9a39700c1337a3f053966e4b49d4ccc552e7c3e386b0
Python
5,056
164
import time import json import functools import concurrent.futures from airflow import settings from airflow.models import DagBag, DagModel, Variable, Connection from airflow.models.dagrun import DagRun from airflow.api.common.mark_tasks import set_dag_run_state_to_success from airflow.api.common.trigger_dag import tr...
620cde5cee462fd4316bea5a5c7707cac5556d70572be311a3edb1b64b34e224
Python
5,060
136
"""Local OnsagerNet variant with optional regularization on the potential V. Hooks into the ``regu`` / ``regularization(x)`` interface that ``UIDD._losses.MLELoss`` already checks: when ``model.regu`` is truthy, ``MLELoss`` adds ``model.regularization(x)`` to the per-sample loss. We support two families that act on th...
7362e7e342a2c690b99b2a06a9a3e1a90a7c0f2b50aaa4bf6720e6522c901475
Python
5,085
167
# -*- coding: utf-8 -*- # # Configuration file for the Sphinx documentation builder. # # This file does only contain a selection of the most common options. For a # full list see the documentation: # http://www.sphinx-doc.org/en/master/config # -- Path setup ------------------------------------------------------------...
9a0e9993044a0164e045edc97b3aed3fb711c1baa3aaed8d7e07af4bec079e71
Python
5,085
134
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Cobra Compartment Duplicator This script takes a metabolic model and duplicates its reactions based on a set of predefined compartment transport rules. It is designed to create a new model where reactions are split to represent transport between different compartme...
b74d502f91031a084be28fc841abeb4cdf7432c8895639b04374dcfe68edcf57
Python
5,114
153
#!/usr/bin/env python3 """ This script creates a 3-minute synthetic recording and saves it to NWB for testing the pipeline. Each ElectricalSeries gets its own Device / ElectrodeGroup with an externally given name, so that the pipeline can be tested on the multi-probe NWB scenario (see issues #116 and #121): the NWB re...
34c793dd93d3f2497306d67d728efbe1befec1b6eefa8cab90ea542b7d8bade8
Python
5,178
155
import unittest import numpy as np import numpy.testing as npt from sigpy import backend, config, nlop, util, linop import torch from torch.autograd import Variable if __name__ == '__main__': unittest.main() devices = [backend.cpu_device] if config.cupy_enabled: devices.append(backend.Device(0)) class Test...
7cef84d961990be24136cbcf794efe509269ec8cf467da618621a41c19302baa
Python
5,183
168
#!/usr/bin/env python import numpy as np import matplotlib.pyplot as plt from ._utils import ( robust_normalize, truncate_signals, pad_along_axis, remove_padding_along_axis, ) def plot_signals(signals, sampling_frequency = 1, remove_outliers = True, ...
f3c81f656981ea6d609d077800e9438b98ed1c26b67c265d03ceb56a5cf2c820
Python
5,203
160
from __future__ import division import numpy as np from numpy import random from scipy.spatial.distance import pdist, cdist from scipy.stats import kstwobign, pearsonr from scipy.stats import genextreme __all__ = ['ks2d2s', 'estat', 'estat2d'] def ks2d2s(x1, y1, x2, y2, nboot=None, extra=False): '''Two-dimension...
9f898089c28fdd19e7d3a0e93795f462b9e404edfa949993dbce2b67dbfb74ef
Python
5,237
184
from typing import Optional, Iterator import datetime import os import posixpath import numpy as np import numpy.typing as npt from cloudfiles import CloudFiles from cloudvolume import lib from cloudvolume.exceptions import ( SkeletonDecodeError, SkeletonEncodeError, SkeletonUnassignedEdgeError ) from cloudvol...
fc018cb60e9c7f84c08302abcae50c9734a8e2764f8888f8d42b4cd1ee7df5ea
Python
5,242
136
""" Inference script to test the newest model on misclassified images. Shows the image and the model's classification. Example: python inference_on_disagreements.py \ --model-path ./outputs/20260127_120000_binary_batch4_div5_tuned.keras \ --disagreement-dir /dls/science/groups/i23/scripts/chris/GoniOwl_metri...
70979381634a78465e2bbf6e25834753ed9e07ff5d770c520a26ee53dabc1070
Python
5,289
139
# -*- coding: utf-8 -*- """ MUSSELS Diffusion MRI Reconstruction. Author: Zhengguo Tan <zhengguo.tan@gmail.com> """ import numpy as np import sigpy as sp from sigpy import backend from sigpy.mri import app, sms def MusselsRecon(y, coils, MB=1, lamda=0.05, max_iter=50, rho=0.1, reg...
2ae5bc8fed826b57bbd08111d0905921538bc665d43bd5375623557d8b1af1df
Python
5,325
179
#!/usr/bin/env python3 # # Test model downloads and smoke them. # import subprocess import sys from typing import Dict, List, Optional, Tuple from argparse import ArgumentParser from pathlib import Path from tempfile import TemporaryDirectory from fnmatch import fnmatch import json Job = Tuple[str, str, Optional[str...
7167ed4cb67fa7f18b1d7fce0f448c19848bbfb96231708c6793a71bf0f73564
Python
5,335
138
import unittest import numpy as np import numpy.testing as npt from sigpy import backend, config, linop, pytorch if config.pytorch_enabled: import torch if __name__ == "__main__": unittest.main() devices = [backend.cpu_device] if config.cupy_enabled: devices.append(backend.Device(0)...
cb1caaeadad59c44290e6a0d7c1d9abe1c98b03ac921d6f1148a1078a15c056f
Python
5,353
173
"""Coil compression functions. Author: Zhengguo Tan <zhengguo.tan@gmail.com> """ import numpy as np import sigpy as sp from scipy.linalg import eig __all__ = ['scc', 'gcc', 'rovir'] # %% def scc(kdat, P=10, coil_dim=-2, device=sp.cpu_device): r"""Coil compression based on SVD. Args: kdat (array): ...
ff49beb2ed9ff8d80970b3c49e62e2d53f34d29a2246a4d77b75fe33a466eb74
Python
5,374
160
# %% [markdown] # # Notebook 02: Surface curvature mapping # # **Paper section:** Results — Surface curvature mapping # **Paper figures:** Figs. 3 (Gaussian curvature), 4 (Mean curvature) # # This script computes the local Gaussian and Mean curvature at every vertex # of the basal surface mesh. # # **Method:** For each...
561a93581053f0dca74238210ae153edd7949c871807cc7b8da071f1b2c447cf
Python
5,393
159
import unittest import numpy as np import numpy.testing as npt from sigpy import app, linop, util, prox, nlop if __name__ == "__main__": unittest.main() class TestApp(unittest.TestCase): def test_MaxEig(self): n = 5 mat = util.randn([n, n]) A = linop.MatMul([n, 1], mat) s =...
4a33e9eb5101ef5f17e221d3ddbb0eef1c668a6955efcaa0a7e9413c20a5a1b9
Python
5,458
147
""" samplers.py Batch samplers that use Dataset grouping information. This module expects a dataset that exposes: dataset.pattern_to_indices : Dict[str, List[int]] In this repo, GroupedPatternDataset builds that mapping so we can sample batches that contain multiple pattern IDs (diversity per batch) and the # d...
7d23961db3794325fcf30dd6b6b7f9c64911d4eebf5fafd2c49c044ab1e2a388
Python
5,460
145
"""Tests classes in data_name_patterns module""" import unittest from datetime import datetime, timezone from aind_data_schema_models.data_name_patterns import ( DataRegex, DataRegexLegacy, RegexParts, build_data_name, datetime_from_name_string, datetime_to_name_string, ) class TestRegexPart...
327d5c23f7a44f481fdf023eb5cb03315eb41f573b1560051b7977bda8b54016
Python
5,535
196
import os import json import subprocess from collections import OrderedDict from bot_info import workerid fernet_key = os.environ["FERNET_KEY"] #airflow_cmd = "sudo docker run -e FERNET_KEY={fernet_key} \ # -it --rm {docker_image} airflow".format( # fernet_key=fernet_key, # docker_image="ranlu/air-tas...
50b3fc73550326471f495126a957fc9dec042d35f5874fba47e8d2ac1f6a7236
Python
5,580
150
#!/usr/bin/env python """ Using a pre-trained model, and given the preprocessed signal arrays, annotate the state for each sample in the signal array, and save out a 1) a hypnogram, and 2) the likelihood of the predicted state for each sample. The latter can then be used to manually refine annotation. """ import nump...
5b4e22e18522c60ade0906cadab84c1bce033b3a05dc5b16eec4e722e09c3fe0
Python
5,593
143
"""Tests classes with fixed Literal values match defaults""" import unittest from pydantic import BaseModel from aind_data_schema_models.harp_types import HarpDeviceType from aind_data_schema_models.organizations import Organization from aind_data_schema_models.species import Species from aind_data_schema_models.mou...
5b47c39b6a20b182febfd858d01ab01b49206f2aa77a0485603b0d8ec7e8a01b
Python
5,609
174
import unittest import numpy as np import numpy.testing as npt import sigpy as sp from sigpy.mri import linop, precond if __name__ == "__main__": unittest.main() class TestPrecond(unittest.TestCase): def test_kspace_precond_cart(self): nc = 4 n = 10 shape = (nc, n) mps = sp....
1117f72658164d0f9314fc84103b98e590f1cda442da1477cbea317418d71b77
Python
5,644
177
from typing import Dict, Tuple, Sequence, Union, Optional import re import os import numpy as np from cloudfiles import CloudFiles from .. import autocropfn, readonlyguard, ImageSourceInterface from ... import compression from ... import chunks from ... import exceptions from ...lib import ( colorize, red, mkdi...
d2dc88d06565c20b4ecefce2eb96a0a1f612072daaa58d50e1a894cdd2a406eb
Python
5,684
231
"""Modalities""" from typing import Literal, Union from pydantic import ConfigDict, Field from typing_extensions import Annotated from aind_data_schema_models.pid_names import BaseName class ModalityModel(BaseName): """Base model for modality""" model_config = ConfigDict(frozen=True) name: str abb...
673a0617b3c989469eb13bf8bf41830491a27138fce076164e979582cdd78970
Python
5,699
196
# -*- coding: utf-8 -*- """Adiabatic Pulse Design functions. """ import numpy as np __all__ = ["bir4", "hypsec", "wurst", "goia_wurst", "bloch_siegert_fm"] def bir4(n, beta, kappa, theta, dw0): r"""Design a BIR-4 adiabatic pulse. BIR-4 is equivalent to two BIR-1 pulses back-to-back. Args: n (i...
8dec963c423136fb811ffd9cc5c240d8f2532883d65579e60bfb57cd36073659
Python
5,727
155
"""Utilties for translating to/from dask arrays. NOTE: Using the thread-based dask scheduler is very inefficient with CloudVolume because CV is pure python and will cause substantial GIL contention between the dask worker threads. It is HIGHLY ADVISABLE to use a distributed process scheduler with on...
4ae878a7dd5d3fe5023c21dd70879945a04865ee848093ff25840ec1f9c3772a
Python
5,737
246
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Oct 21 18:22:23 2021. @author: spiros """ import numpy as np from pathlib import Path from scipy.signal import find_peaks from scipy.ndimage import gaussian_filter1d import pickle def my_style(): """ Create custom plotting style. Returns...
990d969444e4aba80c100898e99cb7bba63f991448e449e94d16005d8ebbdf57
Python
5,754
218
from typing import Optional import copy import re import weakref from ....lib import jsonify from ..sharding import ShardingSpecification, compute_shard_params_for_hashed import numpy as np SKEL_MIP_REGEXP = re.compile(r'skeletons_mip_(\d+)') class PrecomputedSkeletonMetadata(object): def __init__(self, meta, ca...
6b0c01c7285e3c98e5c0bd9abe93768af792e011920d39b8da8e5ebc24e639a3
Python
5,862
207
import cloudfiles.paths from collections import namedtuple from functools import lru_cache import os import posixpath import re import sys from .exceptions import UnsupportedProtocolError from .lib import yellow, toabs ExtractedPath = namedtuple('ExtractedPath', ('format', 'protocol', 'bucket', 'basepath', 'no_bu...
6b5ae304fff29c1b922c17a953590c051ea75c788673ac85fdd337df4975259f
Python
5,871
169
"""Utility functions for inspecting and exporting CaImAn CNMF results.""" from __future__ import annotations from pathlib import Path import cv2 import h5py import matplotlib.pyplot as plt import numpy as np import pandas as pd from scipy.sparse import csc_matrix def load_sparse_component(group: h5py.Group) -> csc...
8bed8d926d2f64165afa1f10395b8c8099ccce6c84eb7326c6c52d1b6b4e62ad
Python
5,885
180
import numpy as np import matplotlib.pyplot as plt from scipy.io import loadmat from sklearn import preprocessing eeg = loadmat(r"./temp/trajectories.mat") Y1 = eeg['x'] min_max_scaler = preprocessing.MinMaxScaler() Y = min_max_scaler.fit_transform(Y1) X1 = Y.copy() X = X1 memory_factor = 0.5 m = X.shape[0] n = X.s...
e8ea5c784aa6dba502ec800c0d4b58731c96957d1a1ff54ec59126e11c935f15
Python
5,891
160
import warnings warnings.simplefilter(action='ignore') import pycisTopic pycisTopic.__version__ import pandas as pd import scanpy as sc import scipy import pickle import numpy as np from scipy import sparse import os # Project directory projDir = '/home3/ciervo/scMULTIOME/Analisi/' # Output directory outDir = projDir...
3179a0a34eb6bbdb7f847b8a755d78987cf7be4c249bec3ea0eec33893b3b8d0
Python
5,940
161
import os import re from cloudvolume import paths from cloudvolume.paths import strict_extract, extract, ExtractedPath from cloudvolume.exceptions import UnsupportedProtocolError from cloudvolume import lib def test_path_extraction(): def shoulderror(url): try: paths.strict_extract(url) assert...
88a6b73ac9a3a3e30f358b3043263083d39ccedf384696758e36ff37a3bba6bc
Python
6,017
211
# -*- coding: utf-8 -*- """MRI waveform import/export files. """ import struct import numpy as np __all__ = ["signa", "ge_rf_params", "philips_rf_params", "siemens_rf"] def siemens_rf( pulse, rfbw, rfdurms, pulsename, minslice=0.5, maxslice=320.0, comment=None ): """Write a .pta text file for Siemens Pulse...
f496fba9ea63be02a3d6f0b5c969205e354942eb888c355cea45004aa07dbf2b
Python
6,029
181
""" # Dimensionality transformations This module contains classes for dimensionality transformations, such as encoders and decoders. These are to be used in the context where reduced dynamics is sought after, but only microscopic data is available. The main classes are `Encoder` and `Decoder`, which are abstract clas...
b6e5b0b53386c50fe197f6a0b4be3580ddfffd90d4ee503c16a9228bd72bcb26
Python
6,114
207
# -*- coding: utf-8 -*- """MRI simulation functions. """ import numpy as np import math from sigpy.mri import epi __all__ = ['birdcage_maps', 'gradient_echoes', 'diffusion', 'get_subspace'] def birdcage_maps(shape, r=1.5, nzz=8, dtype=complex): """Simulates birdcage coil sensitivies. Args: shape (t...
e3105069fe7ea5bfad37a65d5e3daa84a19948d0e2697996928729a2ac0bffef
Python
6,125
193
import unittest import numpy as np import numpy.testing as npt import sigpy as sp from sigpy.mri import linop, nlop if __name__ == "__main__": unittest.main() def check_linop_adjoint(A, dtype=float, device=sp.cpu_device): device = sp.Device(device) x = sp.randn(A.ishape, dtype=dtype, device=device) ...
23999bac6775b301b169eb4e02e0be6ecf426b519e806fc6f8fa44612872a39b
Python
6,144
180
import numpy as np import matplotlib.pyplot as plt from scipy.io import loadmat from sklearn import preprocessing eeg = loadmat(r"./temp/Bonn_eeg_E_100.mat") Y1 = eeg['eeg_data'] min_max_scaler = preprocessing.MinMaxScaler() Y = min_max_scaler.fit_transform(Y1) # Y = mylorenz(30) X1 = Y.copy() X=X1 memory_factor=0.5 ...
3e4a6bbf270ae70fe48feb3439e8384662674689a415d770bb6a0f980aa68f62
Python
6,155
199
import unittest import numpy as np import numpy.testing as npt import sigpy as sp from sigpy import util, linop, nlop from sigpy.mri import app, sim if __name__ == "__main__": unittest.main() class TestApp(unittest.TestCase): def shepp_logan_setup(self): img_shape = [6, 6] mps_shape = [4, ...
f3354218c4878638640485aa19bda669f14f1ff47fedc25b456d8cf8b6cccff4
Python
6,155
225
from typing import Optional import re import weakref from ....lib import jsonify from ..sharding import ShardingSpecification, compute_shard_params_for_hashed import numpy as np MESH_MIP_REGEXP = re.compile(r'mesh_mip_(\d+)') class PrecomputedMeshMetadata(object): def __init__(self, meta, cache=None, config=None...
1c0a09f4dc6692f85d4691b8f19de2493cd200bcc49b3f76bf1257efb072ac76
Python
6,197
167
from airflow.operators.python_operator import PythonOperator from airflow.utils.weight_rule import WeightRule from slack_message import task_retry_alert from igneous_and_cloudvolume import downsample, downsample_for_meshing, ingest_spatial_index, mesh, mesh_manifest, merge_mesh_fragments, create_skeleton_fragments, mer...
461d45db8586629a5639c5674ff6ab5d758400e49b69fe81f2eceed35cda8b26
Python
6,265
227
import copy from functools import partial import itertools import json import math import multiprocessing as mp import os import platform import posixpath import signal import traceback import numpy as np import concurrent.futures from tqdm import tqdm from ....lib import ( xyzrange, min2, max2, Vec, Bbox, sip, ...
6e50c2561faf0ea6da99691f6a6540cdd80e342742847395d7597df5181edf91
Python
6,292
233
import unittest import numpy as np import numpy.testing as npt from scipy.ndimage import gaussian_filter import sigpy as sp from sigpy.mri import linop, rf, sim if __name__ == "__main__": unittest.main() class TestPtx(unittest.TestCase): @staticmethod def problem_2d(dim): img_shape = [dim, dim]...
dc817ad8e424d06e6f8f604c83b76ce8a51ea3172d35f8aafbd9e66b3a692fb2
Python
6,292
157
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Cobra Biolog ID Aligner (3) This script aligns reaction IDs in an enzyme-constrained (ec) model with a reference list of reaction IDs from a Biolog data CSV file. It is designed to be run from the command line. The primary use case is to rename exchange reactions ...
378a7077bb52c9b242132015e43e8b98de0bbfec1d8f39d51ad7517498ea25a8
Python
6,307
185
from __future__ import annotations from seuronbot import SeuronBot from airflow_api import get_variable, set_variable, run_dag from bot_utils import replyto, download_json from bot_utils import extract_bbox, extract_point, bbox_and_center from nglinks import generate_link @SeuronBot.on_message("update webknossos par...
015361881c6338b250a9e0e414876dc46e7eccf7b7ae656f957562d89aa0a26a
Python
6,343
193
from airflow.operators.docker_plugin import DockerRemovableContainer from airflow.operators.docker_plugin import DockerWithVariablesOperator import unittest from tests.utils.mock_helpers import patch_plugin_file from datetime import datetime, timedelta from docker.errors import NotFound, APIError DAG_ARGS = { 'own...
830063e7cc9f276483ef0b4ae48ed852deb17c30451a692ed4469855a2042dbf
Python
6,345
188
""" Find all instances where GoniOwl disagrees with the human decision, run inference on those images, and save results with confidence-prefixed filenames. Example: python disagreement_inference.py \ --model-path ./outputs/checkpoints/20260219_094846_epoch99_binary_batch16.keras \ --img-height 152 --img-widt...
1e7c4af50c847ea0f7c9dcd770ca5a57ae4c05d6cece4a0d42e0700f56c8ad65
Python
6,359
161
# -*- coding: utf-8 -*- """ Created on Sun Oct 22 17:16:32 2023 @author: Camille Gontier """ # Packages #################################################################### # Importation of all the required packages import h5py import matplotlib.pyplot as plt import spikeinterface.extractors as se from probeinterfac...
c87bcf57bcf5514604adf1fd92e6e16aa3801dd0afb144e7a33cc246a056dfdd
Python
6,360
226
from typing import Optional, Union from .annotation import PrecomputedAnnotationSource from .image import PrecomputedImageSource from .metadata import PrecomputedMetadata from .mesh import PrecomputedMeshSource from .skeleton import PrecomputedSkeletonSource from .. import get_cache_path from ...cloudvolume import ( ...
9b74672b26cf421b9537ee7f3d9745a3446c3981e2262d9cfe9eb61fde98ee34
Python
6,398
189
import unittest import numpy.testing as npt from sigpy import backend, config, fourier, linop, util from sigpy.mri import nlop import sigpy as sp if __name__ == '__main__': unittest.main() devices = [backend.cpu_device] if config.cupy_enabled: devices.append(backend.Device(0)) class TestNlop(unittest.Test...
23efc9ceb0e4e4683544f6b587616c2afa9064a76ff552916e1ecebd59a3d2bf
Python
6,407
199
#! /usr/bin/env python3 import argparse import pathlib from dataclasses import asdict, dataclass from utilities import run_dorado DEBUG_PRINT = True SPEED_LOG_STRING = "> Basecalled @ Samples/s:" @dataclass(slots=True) class Benchmarker(object): input_file: str output_file: str device: str iteratio...
88d501ccbb3a47a6d878b02f8950832bb967cc9397ba39d5f918dbc2e0ffea26
Python
6,418
173
import numpy as np class Graph_pool(): """ The Graph to model the skeletons of human body/hand Args: strategy (string): must be one of the follow candidates - spatial: Clustered Configuration layout (string): must be one of the follow candidates - 'hm36_gt' same with ground t...
e776c413a4e3855d8b45c2aed7d637fb6c524be8656fd00fc76195408aa7020c
Python
6,520
227
"""Species""" from typing import Literal, Optional, Union from pydantic import BaseModel, ConfigDict, Field from typing_extensions import Annotated from aind_data_schema_models.registries import Registry class StrainModel(BaseModel): """Base model for a strain""" model_config = ConfigDict(frozen=True) ...
2455274fbb9bc3cda450ec3b0b2cfecaefeabcc0ba148896cd2a69388d635833
Python
6,547
202
# -*- coding: utf-8 -*- """ Created on Mon Jul 7 10:11:04 2025 @author: Usuario """ # Masks vs True positive import os #For importing images and saving figures import errno # for checking whether the montage direcotry already exists import matplotlib.pyplot as plt import numpy as np from skimage import...
745e99257d53307c610825261fbdedb4edac3e0b9b44c3404991f592ef7dbe61
Python
6,623
158
"""Test generator class""" import unittest from unittest.mock import patch, mock_open, MagicMock from pathlib import Path import pandas as pd from aind_data_schema_models._generators.generator import generate_code, check_black_version, load_data import os TEST_DIR = Path(os.path.dirname(os.path.realpath(__file__))) ...
637ea752230d9d7a9931026281d684dacf6f001e58ad1dbac1ce57b9d17cf513
Python
6,640
192
""" This module implements non-linear least square (nlls) algorithms. Author: Zhengguo Tan <zhengguo.tan@gmail.com> """ import numpy as np import sigpy as sp from sigpy import backend, alg, prox, util class NonLinearLeastSquares(alg.Alg): """Abstraction for non-linear least square (nlls) algorithms. Args: ...
3860d74bc3d59e82f9e5f47a66f37881cfc6b5e0da7297e9ace0437f880988b4
Python
6,668
209
from collections import defaultdict import errno import mmap import os import sys import time import multiprocessing as mp import numpy as np from .lib import Bbox, Vec, mkdir SHM_DIRECTORY = '/dev/shm/' EMULATED_SHM_DIRECTORY = '/tmp/cloudvolume-shm' EMULATE_SHM = not os.path.isdir(SHM_DIRECTORY) PLATFORM_SHM_DIR...
6b74520bd7ef6ee88e6a5fccb9a520b2db47466eb5e703d23c93fc674fb8f817
Python
6,698
208
# 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...
27a53a4a652aba18163a61f54db5cc0b4cd3ae607e5bd263a51b4593ee8397c1
Python
6,702
226
from typing import Optional, Union, Dict from collections import defaultdict import os import json from google.oauth2 import service_account from .lib import mkdir, colorize HOME = os.path.expanduser('~') CLOUD_VOLUME_DIR = os.path.join(HOME, '.cloudvolume') CLOUD_VOLUME_DIR = os.environ.get("CLOUD_VOLUME_DIR", CLO...
36edc5a1a59030ef81b79890e443dba037d5f7a85252c9678ce050fabd5a6afe
Python
6,727
170
from __future__ import absolute_import, print_function from setuptools import setup, find_packages, Extension from setuptools.command.build_ext import build_ext from numpy import get_include from os import path from glob import glob def get_numpy_include_dirs(): return [get_include()] class build_ext_openmp(bui...
36e3478ba7956df9b3bfcb93c364399a4a8a5551bab8de37dc6011b8aa3fa49e
Python
6,746
168
import random import base64 COMPUTE_URL_BASE = 'https://www.googleapis.com/compute/v1/' INSTALL_DOCKER_CMD = ''' echo ##### Set up Docker ############################################################# curl -fsSL https://download.docker.com/linux/ubuntu/gpg | apt-key add - apt-key fingerprint 0EBFCD88 add-apt-repositor...
fb5bfdef21a927a9e79d974073e8fe862431f9c1f0790f972a44e064112a1edb
Python
6,754
176
import copy import pathlib from ont_output_specification_validator import validate_file from ont_output_specification_validator.errors import ErrorContainer from ont_output_specification_validator.settings import ExperimentSettings from ont_output_specification_validator.specification import ( SpecificationBundle,...
c5e0ce8c4ca52ec67634078931596434888ae1501ce7ed393249545c8c1a3ea3
Python
6,756
191
import pytest import sys import numpy as np from cloudvolume.chunks import encode, decode from cloudvolume import chunks def encode_decode(data, format, shape=(64,64,64), num_chan=1, level=None): compression_params = { "level": level } encoded = encode(data, format, compression_params=compression_params) resu...
2654520dc26c736e4200a14765f0c397de0d5b1cf5eb58590d1643ad26e53fef
Python
6,781
203
from airflow.models import Variable from airflow.configuration import conf import os import time import traceback import socket import json import base64 import requests import shutil from datetime import datetime import redis import multiprocessing from concurrent.futures import ProcessPoolExecutor from collections im...
b93f7c759eb4582ef1fbd495c2b5e1c33b42110449b78d073ef8562f68b71458
Python
6,785
163
import unittest import numpy as np from sigpy import block, config if config.cupy_enabled: import cupy as cp if __name__ == "__main__": unittest.main() class TestInterp(unittest.TestCase): def test_array_to_blocks(self): xps = [np] if config.cupy_enabled: xps.append(cp) ...