sha256
stringlengths
64
64
language
stringclasses
27 values
size
int32
1
491k
lines
int32
1
21.8k
content
stringlengths
1
200k
4a5bfd50f8571077c55e00e2f4b238de82ee077a8f85b8726756a118d23f77a8
Python
6,795
180
# -*- coding: utf-8 -*- """ Created on Mon Oct 20 16:18:57 2025 @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 shap imp...
66b7b90cdaa47f9e1a70a6a2a36322311a2e6bdafb4d016ff121b34ddd676394
Python
6,873
253
import unittest import numpy as np import numpy.testing as npt from sigpy import alg, linop if __name__ == "__main__": unittest.main() class TestAlg(unittest.TestCase): def Ax_setup(self, n): A = np.eye(n) + 0.1 * np.ones([n, n]) x = np.arange(n, dtype=np.float32) return A, x d...
8856c8c25dbee089d6154fda4d50e91d509f5adb4c189c919ce1f07d286c94f9
Python
6,876
229
# -*- coding: utf-8 -*- """MRI linear operators. This module mainly contains the Sense linear operator, which integrates multi-channel coil sensitivity maps and discrete Fourier transform. """ import numpy as np import sigpy as sp def Sense( mps, coord=None, weights=None, tseg=None, ishape=None,...
0d44dc4a03aea1bbc09267dc43047af7af5ad5d3adb25fb25c06033c487e40af
Python
6,888
182
from common import GlobalComputeUrl, ZonalComputeUrl, GenerateBootDisk, GenerateNetworkInterface, GenerateAirflowVar from common import INSTALL_DOCKER_CMD, INSTALL_OPS_AGENT, INSTALL_NVIDIA_DOCKER_CMD, CELERY_CMD, PARALLEL_CMD def GenerateEnvironVar(context, hostname_manager): if "postgres" in context.properties:...
8c430c8e82d2e476f5c1468b64020da975153b968f08efe6cc86a98a2bfceafc
Python
6,896
198
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from utils.tgcn import ConvTemporalGraphical from utils.graph import Graph class Model(nn.Module): r"""Spatial temporal graph convolutional networks. Args: in_channels (int): Number of channels in ...
d2d12ea36f074db7dd6ef438d7c1bb94261b35b4b19d3dddcf25bbdffd42c089
Python
6,928
212
"""Training commands.""" from __future__ import annotations import re from datetime import datetime from typing import Optional from seuronbot import SeuronBot from airflow_api import run_dag from bot_utils import replyto, download_json from airflow_api import get_variable, set_variable from common import docker_help...
75947f48f4d98c3de86dd88bccca11c1ce8ab7a257c1fd2764541ca531fd3eaf
Python
7,039
186
"""Dev utils tests""" import unittest from unittest.mock import patch, MagicMock from aind_data_schema_models._generators.dev_utils import to_class_name, to_class_name_underscored, update_harp_types class TestDevUtils(unittest.TestCase): """Tests for dev_utils module""" def test_to_class_name(self): ...
14a6ea73e4bd7b6c183585febb547c3dd5fac29d31ecaef0101664cd89bd1537
Python
7,093
255
import queue as Queue from functools import partial import threading import time from tqdm import tqdm DEFAULT_THREADS = 20 class ThreadedQueue(object): """Grant threaded task processing to any derived class.""" def __init__(self, n_threads, queue_size=0, progress=None): self._n_threads = n_threads self...
9587a7e5a056c6fbafbf01b4e4cb9b411b349a4488c6e4caa7511f6c4c2e2de3
Python
7,112
171
import pathlib from collections import defaultdict from tetra.data_frame_utils import check_pandas_equal, load_sorted_data_frame from tetra.regression_manager import TestData from tetra.sequence_utils import compare_alignment_files, compare_fastq_files try: from tetra.output_validation import setup_validator exce...
f92a98521d41dae12704ba33730b2ea498f558facc01377488271574fd082f69
Python
7,146
197
from common import ZonalComputeUrl, GenerateDisk, GenerateBootDisk, GenerateScratchDisk, GenerateNetworkInterface, INSTALL_DOCKER_CMD, INSTALL_OPS_AGENT, GenerateAirflowVar from workers import GenerateDockerCommand, GenerateCeleryWorkerCommand, GenerateEnvironVar def GenerateNFSServerStartupScript(context, hostname_m...
94ecd568339ba41ad096b489f16234ba40391b5def8baad2741d518b5ccaddea
Python
7,197
194
import sys import socket import logging import psutil from enum import Enum import os import redis from datetime import datetime, timedelta from time import sleep from kombu_helper import put_message from common.google_api import gce_hostname, get_project_id, get_zone, delete_instances, get_created_by class RedisHealt...
a005c75e1d58ae1548a589c092d643040800f3320f524ea185ede740a9cfd7ed
Python
7,231
232
import unittest from airflow.operators.custom_plugin import MultiTriggerDagRunOperator from airflow.utils.state import State from airflow import settings from tests.utils.mock_helpers import patch_plugin_file try: import unittest.mock as mock except ImportError: import mock from datetime import datetime, tim...
aa7fa569144fd043ba6e2e641af9293f7303b7713cf86d235b2845eed88ba045
Python
7,232
174
import sys import os import yaml from yaml import Loader import numpy as np import quantities as pq from elephant.conversion import BinnedSpikeTrain from elephant.spade import concepts_mining from utils import concatenate_spiketrains, compute_isi_based_bin_firing_probability, generate_simulated_spiketrains # Exampl...
df93b0551f210bdc0d0eaf0a67fb3cc8b1f6da87cdc133ee047b26700151f428
Python
7,277
181
#!/usr/bin/env python """Determine intervals with missing data in the raw time series data. If *any* signal appears to have missing values, the corresponding interval is marked as missing. EEG/EMG/LFP recordings often contain intervals with missing data. These events typically have one of two origins: 1) Missing va...
143b95caddf09b446c7ea1b776e58ffe7dd035c7900939d21fff2b4e45771b3d
Python
7,299
176
#!/usr/bin/env python """Train and test in a hold-one-out fashion on data sets for which a manual created state annotation exists. """ import numpy as np import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix as get_confusion_matrix from somnotate._automated_state_annotation import StateAnnota...
54a36402742277435ab68ddc015b1edc84617ebc21e88ac88dbf28ece104277f
Python
7,303
164
import torch import wandb import os import warnings from sklearn.model_selection import StratifiedGroupKFold from utils import get_count, get_TrainData, get_dataLoader, reset_wandb_env, get_balancedDF from train import train # Define sweep configuration train_dir_dict = {'parent_dir' : "Data", 's...
9c6a65bae02496fba00e4760e235e4e7fd50e0516fef58a2ec3565977f899427
Python
7,327
179
import numpy as np class Graph(): """ The Graph to model the skeletons extracted by the openpose Args: strategy (string): must be one of the follow candidates - uniform: Uniform Labeling - distance: Distance Partitioning - spatial: Spatial Configuration For more informa...
c82c13ca7475b4ec80057d7871181f0a74667f7a1fe66ebf1a203027693e428f
Python
7,329
276
import os import numpy as np import pytest from cloudfiles import CloudFiles from cloudvolume import Vec, Bbox, CloudVolume, Storage, Mesh @pytest.fixture def unsharded_vol(): test_dir = os.path.dirname(os.path.abspath(__file__)) test_dir = os.path.join(test_dir, "test_seg_unsharded") print(test_dir) return ...
5cad11f81d16d3f8c091a3fa9828afc07f88d402bcb396a12c3035879d7bc620
Python
7,349
208
import plotly.graph_objects as go def plotly_grid(file_dict, spp_code, spp_name, ai_range_dict, samp_key): ai_range = ai_range_dict[spp_code] fig = go.Figure() z_index_unhashable = list(reversed([list(range(i,i+5)) for i in range(0,60,5)])) z_index_hashable = [z for z_list in z_index_unhashable...
33b532e016e3728b15faa4786f42ac1ba5f95a50e89d696d6acc5ca9b23419eb
Python
7,355
259
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import argparse import numpy as np import pandas as pd import statsmodels.api as sm from pathlib import Path import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator def parse_args(): ap = argparse.ArgumentParser() ap.add_argument("--in-tsv", re...
7f917c976934f76438a2d38d9511b86782c1d402e23a3536b68de6b166769988
Python
7,437
215
from __future__ import print_function, unicode_literals, absolute_import, division import numpy as np import warnings from skimage.measure import regionprops from skimage.draw import polygon from csbdeep.utils import _raise from ..utils import path_absolute, _is_power_of_2, _normalize_grid from ..matching import _che...
655446b1abc35f731b962147e88535e085998a8f633a44cdc37275b7e09ea33e
Python
7,445
295
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Apr 13 17:07:10 2022 @author: spiros """ import numpy as np import matplotlib.pyplot as plt from scipy.ndimage.filters import gaussian_filter1d from matplotlib.colors import LinearSegmentedColormap def my_style(): """ Create custom plotting s...
460d3f888364e7b01bd2b68793875d9f8dc6c8167caff61c3b60e431f1e287a5
Python
7,446
241
# -*- coding: utf-8 -*- """ Created on Wed Jul 30 18:09:39 2025 @author: Usuario """ # -*- 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 direco...
23514de09d0ad9f92affa10f0fe22eeea2cfd435b555afd68eefbbfaf87e320a
Python
7,483
232
#!/usr/bin/env python """ User defined variables and functions that are used across all scripts. """ import numpy as np import matplotlib.pyplot as plt from scipy.signal import ( sosfilt, iirfilter, # cheby1, ) from functools import partial from somnotate._plotting import plot_signals, plot_states from so...
011c38d915a8383ae2b152986d3fe7b9ee6995d7f8ad6692f39fdad8b0ee3fc9
Python
7,506
276
import pytest import os import shutil import zarr from cloudvolume import CloudVolume, Bbox import numpy as np TEST_DIR = os.path.dirname("/tmp/removeme/cloudvolume/") def create_simple_dataset(): test_location = os.path.join(TEST_DIR, "zarr3_simple_unsharded.zarr") if os.path.exists(test_location): ...
6bc3046edb455c11e6889d0778b664aa844eb7b225c7de31ce7db1dffd5afbea
Python
7,557
212
# -*- coding: utf-8 -*- """ Created on Tue Jun 27 20:44:25 2023 @author: simon """ from neuron import h, gui from neuron.units import mV, ms from Class_CA1_Pyr_standardized import Cell import numpy as np import pandas as pd from scipy.spatial import distance_matrix from timeit import default_timer as tim...
04242e8c6a9f3a9d9bb7845a7d33742aca7843910c3bdcd131c659a521ad0475
Python
7,572
177
#!/usr/bin/env python import numpy as np import matplotlib.pyplot as plt from scipy.signal import welch import matplotlib matplotlib.rcParams['path.simplify'] = True matplotlib.rcParams['path.simplify_threshold'] = 1.0 matplotlib.rcParams['agg.path.chunksize'] = 10000 # import matplotlib.style as mplstyle # mplstyle....
73ef87db9df6186f2a26705c321dfe9b915d72ea6d957fefdb85342c6bf93d6f
Python
7,600
250
from airflow.operators.python import PythonOperator from airflow.utils.weight_rule import WeightRule from airflow.models import Variable from slack_message import slack_message from param_default import default_args if Variable.get("vendor") == "Google": import google_api_helper as cluster_api else: cluster_ap...
6df8c6681f7a2b8a88fc2c8640fbc1459c13d2d016171bc39150220ae6c08984
Python
7,602
253
"""Webknossos interface.""" from __future__ import annotations import json from datetime import datetime import requests from airflow import DAG from airflow.utils.weight_rule import WeightRule from airflow.operators.python import PythonOperator from airflow.models import Variable, BaseOperator as Operator from work...
24a9767a50304cf1e31a77cefc909b4130730003a5bd8b4e40d82f744aa5ec70
Python
7,707
263
"""Functions for Dynamic Contrast Enhanced (DCE) MRI Author: Zhengguo Tan <zhengguo.tan@gmail.com> """ import numpy as np import sigpy as sp from sigpy import backend def arterial_input_function(sample_time, A = [0.7668, 0.3309], T = [0.1710, 0.4079], ...
f9ec947bba16955a1becca885e3d2c5d03637ed7974db2584b4b5c88d63923c8
Python
7,808
171
from typing import Union, List, Optional, Literal import numpy as np import pynwb from spikeinterface import BaseRecording, SortingAnalyzer def _get_electrode_group_indices_by_channel(recording, nwbfile): """ Like neuroconv's _get_electrode_group_indices but returns one NWB electrode index per recording...
e1cbdeb09230341c1bbe6a9fc13877e44ae6b515ec211c859f9daee44677e9ac
Python
7,822
183
from matplotlib import pyplot as plt import numpy as np import os import time import sys import argparse import errno from collections import OrderedDict, defaultdict, Counter import tensorboardX from tqdm import tqdm import random import torch import torch.nn as nn import torch.nn.functional as F import torch.optim a...
b9df1d176506c4a53184438590d557c9a771df23116c34c8dea134838d69a2c9
Python
7,846
190
# %% Imports import os import sys import yaml from yaml import Loader import numpy as np import quantities as pq from elephant.spade import concepts_mining from elephant.conversion import BinnedSpikeTrain from utils import concatenate_spiketrains, compute_isi_based_bin_firing_probability # %% Parse the command line ...
c077971b63d230b4ff274667671c9b779bbe45a7e6e48fc6f632798467cba95e
Python
7,929
161
# -*- coding: utf-8 -*- """ Created on Tue Sep 5 12:44:32 2023 @author: simon """ import numpy as np import pandas as pd import matplotlib.pyplot as plt from collections import defaultdict import io class SWCExplorer(): def __init__(self, swc=None, df=None, eswc=False): self.eswc = eswc ...
5f35de4faab0bf78e3a9f08d08334e92864f934ffd92e28598663b2c223ccb82
Python
7,977
257
import os import pickle import jax import equinox as eqx import sys sys.path.append('..') from omegaconf import DictConfig from datasets import Dataset, Features, Array2D, load_from_disk sys.path.append('../..') from UIDD.dynamics import UIDD2 from UIDD.models import DiffusionCholeskyMLP, PotentialResMLP_scaleV2 ...
6069eec2d54c8380e139360d8afc755a4855b89c515bbb39970f58990bc9ca3a
Python
7,995
193
#!/usr/bin/env python """ Example script demonstrating how to preprocess a set of datasets and saving out the results. TODO: - provide different entry point by command line argument parsing using argparse - fix plotting (`time` encapsulated at the moment...) """ import numpy as np import matplotlib.pyplot as plt tr...
9c14dfb11555755fec3e7055955893a0ba3a461f2cebf1b2aab97e4985734b6d
Python
8,003
212
import cv2 import os from datetime import date import random from tqdm import tqdm from concurrent.futures import ProcessPoolExecutor, as_completed import multiprocessing import glob import shutil import argparse import logging # Logging def setup_logging(level: str = "INFO", log_file: str | None = None) -> None: ...
60941cff7d428d4634ca25228c675dece828c7f6937d95360430fc23e3324d0a
Python
8,031
209
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Cobra Reaction ID Cleaner (2) This script cleans and standardizes reaction IDs in an enzyme-constrained (ec) model, particularly one that has been processed by a preliminary fixing script. It is designed to be run from the command line. The script performs a serie...
2416dff3cc44c816f802318381bca2350fa64943b74c3d47512e7bf316427680
Python
8,081
183
import torch from tqdm import tqdm import wandb import torchmetrics import shutil from utils import EarlyStopping, get_model, ConfigureResnet def train(train_dataloader, valid_dataloader, config, sweep_id, sweep_run_name, fold, val_ratio, train_ratio, spp): #Fold name dict converter abc_dict = {'1':"a", ...
aed05a8f6ad04b208a0a75707f5d6b40a0fb6e041580e5c4caace20743464c5a
Python
8,139
284
import unittest import numpy as np import numpy.testing as npt from sigpy import fourier, util if __name__ == "__main__": unittest.main() class TestFourier(unittest.TestCase): def test_fft(self): input = np.array([0, 1, 0], dtype=complex) npt.assert_allclose( fourier.fft(input)...
6ad921fc13398df64220202195cf17cb36700af5f39665a6380b3983c99e660c
Python
8,206
254
""" # Custom loss functions This module contains custom loss functions for training the models. The case class `Loss` is an abstract class that defines the interface for loss functions. Sub-classes must implement the `Loss.compute_sample_loss` method. # """ import jax import equinox as eqx import jax.numpy as jnp f...
2df04988675a3d4d3b255aa5a4ebb5a1c1cc9c90a99311871ef7084f3be2b78d
Python
8,274
321
import pytest import numpy as np import cloudvolume.lib as lib from cloudvolume.lib import Bbox, Vec, xyzrange def test_xyzrange(): def xyz(*args): return np.array(list(xyzrange(*args))) assert list(xyzrange((0,0,0))) == [] assert list(xyzrange((1,0,0))) == [] assert np.all(xyz((1,1,1)) == [Vec(0,0,0)])...
334b06153cd0d4617e59945189cd1dc8e2ff10f739f5598016c267523ed1da64
Python
8,362
240
def slack_message(msg, notification=False, broadcast=False, attachment=None): from airflow import configuration as conf import kombu_helper msg_payload = { 'text': msg, 'notification': notification, 'broadcast': broadcast, 'attachment': attachment, } t...
d044d31bdd691696a9fdefff94d8ab6c61feb30fadb11359358220e72e9a2d94
Python
8,371
262
"""Training DAGs.""" from __future__ import annotations import json import os import uuid from datetime import datetime from airflow import DAG from airflow.utils.weight_rule import WeightRule from airflow.operators.python import PythonOperator from airflow.models import Variable, BaseOperator as Operator from airflo...
b32f433ac2bec1b961616934956921058a704f8fd80f986242b502448657f34a
Python
8,390
185
#!/usr/bin/env python import numpy as np import matplotlib.pyplot as plt from scipy.signal import welch import matplotlib matplotlib.rcParams['path.simplify'] = True matplotlib.rcParams['path.simplify_threshold'] = 1.0 matplotlib.rcParams['agg.path.chunksize'] = 10000 # import matplotlib.style as mplstyle # mplstyle....
0126cbaef6eb958002ce0e6c58711ca32f40ff2c9cf7963b9a2e38286557406d
Python
8,487
238
import torch import torch.nn.functional as F import os import numpy as np import torchvision.transforms as transforms import random from src.losses.losses import fourier_space_loss, l1_loss, l2_loss, grad_l2_norm_isolated from typing import Optional def set_seed(seed = 42): random.seed(seed) np.random.seed(see...
783d8c3ce35bcbd1811105c9df03b0892f12a79de4b2144250a9277136507bc4
Python
8,510
269
# -*- coding: utf-8 -*- """RF Pulse Simulation Functions. """ from sigpy import backend __all__ = ["abrm", "abrm_nd", "abrm_hp", "abrm_ptx"] def abrm(rf, x, balanced=False): r"""1D RF pulse simulation, with simultaneous RF + gradient rotations. Args: rf (array): rf waveform input. x (arra...
e614a97dbc567f13ad50e883c3a8a273a2f3125d83f289aa857af7933bfc6178
Python
8,513
349
from typing import Union import sys import threading import numpy as np def getsizeof(val:Union[int,str,bytes,list,tuple]) -> int: """does sizeof at arbitrary depth for tuples and lists""" nbytes = 0 if isinstance(val, (tuple, list)): for elem in val: nbytes += getsizeof(elem) elif isinstance(val, n...
15267532c0c85dea7eef70694d1ea2074cb4d1a7039d0858d258d09e28599e53
Python
8,519
206
from common import GlobalComputeUrl, ZonalComputeUrl, GenerateBootDisk, GenerateNetworkInterface, GenerateAirflowVar from common import INSTALL_DOCKER_CMD, INSTALL_NVIDIA_DOCKER_CMD, INSTALL_OPS_AGENT, DOCKER_CMD, CELERY_CMD, PARALLEL_CMD GPU_TYPES = ['gpu', 'custom-gpu', 'synaptor-gpu', 'deepem-gpu'] SYNAPTOR_TYPES ...
60bfad3b85b179784357a4914edd6e830407d1f97615de87eaeae3245294cde3
Python
8,540
257
import torch import torch.nn as nn from utils.tgcn import ConvTemporalGraphical from utils import Graph from nets.utils.graph_frames_withpool_2 import Graph_pool from nets.non_local_embedded_gaussian import NONLocalBlock2D inter_channels = [128, 128, 256] fc_out = inter_channels[-1] fc_unit = 512 class Model(nn.Mo...
2b1fca67d522fe5e80305d4d415fb9334ed4b291627e881a62a0b4351e0f34fd
Python
8,594
348
# -*- coding: utf-8 -*- """Methods for Echo-Planar Imaging (EPI) acquisition with an focus on diffusion tensor/kurtosis imaging. Author: Zhengguo Tan <zhengguo.tan@gmail.com> """ import numpy as np from sigpy import fourier MIN_POSITIVE_SIGNAL = 0.0001 def phase_corr(kdat, pcor, topup_dim=-11): """perform p...
9c6214b94e09b902ce8103db6e09bab575b00a94667c03eea465a5a3f8c5a341
Python
8,692
273
"""linear case.""" import os os.environ["JAX_PLATFORM_NAME"] = "cuda" os.environ["XLA_PYTHON_CLIENT_MEM_FRACTION"] = "0.18" import jax jax.config.update("jax_enable_x64", True) import jax.numpy as jnp import jax.random as jr import equinox as eqx import sys sys.path.append('..') from utils.sde import SDEIntegrator f...
933e40b554a744f58353ea5f521823190263eaee24452a6f3233b5c964bb2bfe
Python
8,698
221
# -*- coding: utf-8 -*- """ Created on Mon Nov 25 15:40:25 2024 @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 from matplotlib....
a17965d7447fee5807eaba0a030f662538bc6a354c2ec445a89feeb06f076038
Python
8,702
208
# Adapted from VideoPose3D (Facebook Research) # Source: https://github.com/facebookresearch/VideoPose3D/blob/main/common/model.py # # Pavllo et al., "3D human pose estimation in video with temporal convolutions and semi-supervised training", # CVPR 2019. import torch.nn as nn class TemporalModelBase(nn.Module): ...
85e1e274b917f1132c66a1724a4b99e449ad0078a18184b1c96baccd74f00b76
Python
8,720
281
import os import jax import equinox as eqx import sys sys.path.append('..') from tqdm import tqdm from omegaconf import DictConfig from datasets import Dataset, Features, Array2D, load_from_disk sys.path.append('../..') from UIDD.dynamics import UIDD2 from UIDD.models import DiffusionCholeskyMLP, PotentialResMLP_scal...
2b0de4d3cb5cdd8c280f44ae7e0107a7ed3e3c474ec6e13e59b107fbc53728d2
Python
8,722
211
import os import numpy as np import torch import torch.nn as nn from functools import partial from models.DSTformer import DSTformer class AverageMeter(object): """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 se...
4cfdd2ccbdd573199d45c3949de418accecf98e6ef469086d472d7407d3fc030
Python
8,909
256
"""Mouse developmental stage""" import requests from pydantic import BaseModel, ConfigDict from aind_data_schema_models.registries import Registry """Mouse developmental stage""" class MouseDevelopmentalStageModel(BaseModel): """Base model for mouse developmental stage""" model_config = ConfigDict(frozen=...
0f97d452b483b72c18c268a53eebd5b6788aa36cea5e363044a4b070920e28ee
Python
9,092
356
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Apr 13 17:07:10 2022 @author: spiros """ import numpy as np import matplotlib.pyplot as plt from scipy.ndimage.filters import gaussian_filter1d from matplotlib.colors import LinearSegmentedColormap from pathlib import Path from scipy.signal import find...
a04eace03653f54861309a5f2a72a34d3730b89829b502ddeeecc818d10cccc8
Python
9,194
255
from collections import defaultdict import itertools import json import os import posixpath import re import requests import numpy as np from tqdm import tqdm from cloudfiles import CloudFiles from ....lib import red, toiter, Bbox, Vec, jsonify from ....mesh import Mesh from .... import paths from ....scheduler impo...
145ec800bfe14daafd9ff138d0d97f2558a7eb0cbe57a9b371b215c5d768cee6
Python
9,210
245
import psycopg2 from psycopg2 import sql from datetime import datetime from tetra.utilities import get_env_or_raise # Wrapper around all DB interactions. class DBWrapper: def __init__(self, project: str): DB_HOST = get_env_or_raise("BENCHMARK_DB_HOST") DB_PASSWRD = get_env_or_raise("BENCHMARK_DB_P...
4aa344c9d3a8e0d10865793fce5852a4bea375af2a086200f914fadcb3367843
Python
9,247
233
# -*- coding: utf-8 -*- """ Created on Fri Nov 4 12:28:51 2022 @author: spiros """ import os import numpy as np from opt_ import gridfield from poisson_input import poisson_spikes, gaussian_prob import pathlib from scipy.stats import multivariate_normal # Get the path of the current script base_pat...
e36c68642cdf357107d35aed640c1c5e40c755fb6bfb5c8aabf5cb5d23113914
Python
9,350
280
""" 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...
15cb8f0c173d024f7367cb64d1e5f7ba39f2a72b2aaa289f8ddb548173cf3008
Python
9,401
330
# -*- coding: utf-8 -*- """Multiband RF Pulse Design functions. """ import numpy as np __all__ = ["mb_phs_tab", "mb_rf", "dz_pins"] from sigpy.mri.rf import slr as slr from sigpy.mri.rf.trajgrad import trap_grad def mb_rf(pulse_in, n_bands=3, band_sep=5, phs_0_pt="None"): r"""Multiband an input RF pulse. A...
88de069040537b838ca346dd475fed9e6def07627dc92ebe08c01f233c962d08
Python
9,410
263
# %% [markdown] # # Notebook 05: Spatchcocking — 3D to 2D projection # # **Paper section:** Methods — Spatchcocking transformation # **Paper figures:** Fig. 2 (coordinate system), Figs. 3–6 (heatmaps) # # This script flattens the 3D basal surface mesh into a 2D map using the # spatchcocking transformation, combining al...
524367661ca05372b1c2f04280916a1b0975f6c0a9a67d2ac216d53aac2d33db
Python
9,488
331
"""Functions for Simultaneous Multi-Slice (SMS) Acquisition Author: Zhengguo Tan <zhengguo.tan@gmail.com> """ import numpy as np import sigpy as sp __all__ = ['get_uncollap_slice_idx', 'get_ordered_slice_idx', 'reorder_slices', 'get_sms_phase_shift', 'readout_extended_fov',...
60d2ad7ba386dbf8dc3edef36587eaeffeeab78dd0762633b01414743c928396
Python
9,576
291
# from __future__ import print_function # from six.moves import range # import pytest # import re # import time # from cloudvolume.storage import Storage # from cloudvolume import exceptions, Bbox, chunks # from layer_harness import delete_layer, TEST_NUMBER # #TODO delete files created by tests # def test_read_wri...
ef4aea03e77ad72a4370b7d32b1c9a01defcd9bff5e4ae0b6341fd6aed8e6afb
Python
9,708
299
#!/usr/bin/env python """ TODO - consistent variable naming for p, min_percentile, max_percentile """ import numpy as np def robust_normalize(arr, p=1., axis=-1, method='standard score'): """ References: ----------- https://en.wikipedia.org/wiki/Normalization_(statistics) """ if method == 'm...
5a96c37f5711914803d4b8416c92b65cbea0b21e77217c592f69122e4b96b46b
Python
9,722
303
# -*- coding: utf-8 -*- """:math:`B_1^{+}`-selective RF Pulse Design functions. """ import numpy as np from sigpy.mri.rf import slr as slr from sigpy.mri.rf.util import dinf __all__ = ["dz_b1_rf", "dz_b1_gslider_rf", "dz_b1_hadamard_rf"] def dz_b1_rf( dt=2e-6, tb=4, ptype="st", flip=np.pi / 6, ...
b59e8b2056065cb4005c6919078c2ef8e67ee8903e81aadd8c1a00df28cc39da
Python
9,755
234
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Cobra Model Reversibility Fixer (1) This script identifies and resolves conflicting reaction reversibility between a conventional model and an enzyme-constrained (ec) model. The script performs the following steps: 1. Loads a conventional model and an ec-model fro...
0b4a21649e501acb440623fa6662709a25e8fa82d4032ac08390af73904d24e4
Python
9,773
279
"""Batch CaImAn processing for one-photon calcium imaging TIFF files. This script performs motion correction, CNMF source extraction, seeded CNMF refinement, component filtering, and export of fluorescence traces and spatial metadata. Paths, animal identifiers, and day ranges are provided on the command line so the pi...
c8e8dd10ac99ed1e0c55500da322b6ce4a698ab7c98036c04ab8b0814841a9b9
Python
9,800
322
# -*- coding: utf-8 -*- """MRI sampling functions. """ import numba as nb import numpy as np __all__ = ["poisson", "radial", "spiral"] def poisson( img_shape, accel, calib=(0, 0), dtype=complex, crop_corner=True, return_density=False, seed=0, max_attempts=30, tol=0.1, ): """Ge...
516e071311229ec9b4bf7497f4a6cedf268dda1c7ad22320244a50cdd41bf99f
Python
9,856
327
# -*- coding: utf-8 -*- """FFT and non-uniform FFT (NUFFT) functions. """ from math import ceil import numpy as np from sigpy import backend, interp, util __all__ = [ "fft", "ifft", "nufft", "nufft_adjoint", "estimate_shape", "toeplitz_psf", ] def fft(input, oshape=None, axes=None, center=...
01f1ac745c6abda1141d666ed3745db754efcc3f6982b2f1b244b3fe8627e3f9
Python
9,872
300
"""Convert MMD summary NPZ files to Excel workbooks. This script leaves the source ``.npz`` files untouched. For each input file it creates up to three ``.xlsx`` files next to the source file: * ``<stem>_timeseries.xlsx``: 1D arrays aligned by ``ts``. * ``<stem>_scalars.xlsx``: metadata, aggregate errors, and per-see...
1ef09a658e95dfc950eec02e2f2dbc4ab0623a937746128026402e003c49247e
Python
9,894
259
from copy import deepcopy from datetime import datetime from seuronbot import SeuronBot from bot_info import broker_url from bot_utils import replyto, extract_command, clear_queues, download_json, guess_run_type, latest_param_type, upload_param from kombu_helper import drain_messages, visible_messages, get_message, put...
115045a757ec860c0b6d96e339d5c43825e60dd1ad0f548fd5ac11f47c07140d
Python
9,927
197
# -*- coding: utf-8 -*- """ Created on Tue Aug 22 12:28:56 2023 @author: simon """ import numpy as np import matplotlib.pyplot as plt import seaborn as sns; sns.set_theme() import pickle import os,sys from scipy.signal import find_peaks from statannot import add_stat_annotation import pandas as pd from...
1e0d8f6b8b7d3933048f970da56b2777a3d751c234e224116756d381d816fb1e
Python
9,964
366
# -*- coding: utf-8 -*- """Functions and classes for getting and setting computing devices. """ import numpy as np from sigpy import config if config.cupy_enabled: import cupy as cp if config.mpi4py_enabled: from mpi4py import MPI if config.nccl_enabled: from cupy.cuda import nccl __all__ = [...
2782be83e5333993824ed8dd68bd976ea795080cad4b6e26de642d18ef734c82
Python
9,995
284
"""Non-technical user segmentation commands ("easy seg").""" from __future__ import annotations import re from typing import Any from datetime import datetime import time import humanize from seuronbot import SeuronBot from bot_info import broker_url from bot_utils import clear_queues, replyto, download_json from bot...
30446d710fab1be3314315deeb42fc47a8f2aa7f15cee1d5719a8f7fb1cdb1fd
Python
10,247
227
############################################################################### # This library provide utilities for building experimental datasets. # The library makes use of scipy, pandas, sklearn, pyDOE2, math, # For visualization, it makes use of seaborn and matplotlib # Two main tasks can be performed (examples ...
33c3059422acbe0797e03d0832d7a96dfe223f533748fb67efe56fbd611ef533
Python
10,336
307
# -*- 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...
a187ea16ee8aaeb61a3fc44310bcf0b58c6e41af4556c17a88dbce1ce5d8730e
Python
10,459
338
"""utils for reduced polymer dynamics.""" import os import pickle import jax import equinox as eqx import sys sys.path.append('..') from omegaconf import DictConfig from datasets import Dataset, Features, Array2D from sklearn.model_selection import train_test_split sys.path.append('../..') from UIDD.dynamics import ...
c9df833230d338ad9da0f7fdc21edb9a7874a5fe03c1d99c8c51b28f912adddb
Python
10,468
315
from multiprocessing import Process, Event, Queue from dataclasses import dataclass from pathlib import Path from typing import Optional from queue import Empty import flammkuchen as fl import numpy as np import shutil import json import yagmail from PIL import Image import os import time @dataclass class SavingParam...
5103775f5b9c16d2c16b2c99fa8960e3dc04b1a7ef47ee5e993c414db84c2414
Python
10,536
348
from typing import Optional import copy import re import os import numpy as np from cloudfiles import CloudFiles import cloudfiles.compression from .. import ( autocropfn, readonlyguard, ImageSourceInterface, check_grid_aligned, generate_chunks ) from ...types import CompressType, MipType from ... import com...
0721491df602fe0a4c2314dbdb58816a1dfdf40fcc4580e8b4bfc3b0d626322b
Python
10,559
228
import unittest import numpy as np import numpy.testing as npt from sigpy import backend, config, util, linop, prox # from sigpy.app import NonLinearLeastSquares as sp_nlls from sigpy.nlls import NonLinearLeastSquares as nlls from sigpy.mri import nlop, epi, nlrecon if __name__ == '__main__': unittest.main() dev...
ca71a09013f6ef79ef8051d15e15f6a2962206458e3139513415d17e7e8350ed
Python
10,613
302
# -*- coding: utf-8 -*- """MRI RF excitation pulse design functions, including SLR and small tip spatial design """ import numpy as np from scipy.interpolate import interp1d import sigpy as sp from sigpy import backend from sigpy.mri import rf as rf __all__ = ["stspa", "stspk"] def stspa( target, sens,...
fa0ac92138189ab001f2ae377485b5337caa06c1f6a908f604da2002e020b79f
Python
10,682
346
from __future__ import annotations import re import string import requests import json import json5 import base64 import traceback from functools import lru_cache from collections import OrderedDict from secrets import token_hex from kombu_helper import put_message, visible_messages import slack_sdk as slack from typi...
ba251b810c57677f1bb92738aa1b49d54a4c13e6b6a9979b4cca0a97e3631761
Python
10,696
369
# -*- coding: utf-8 -*- """This module contains an abstraction class Nlop for non-linear operators, and provides commonly used non-linear operator, including exponential. Author: Zhengguo Tan <zhengguo.tan@gmail.com> """ import numpy as np from sigpy import backend, linop class Nlop(): """Abstraction for non-li...
561c721cbe11e38851abd13f7950fd2b4116485329377a1c5fa36ad895ac6abd
Python
10,705
360
"""DAG definition for synaptor workflows.""" from typing import Optional from datetime import datetime, timedelta from dataclasses import dataclass from airflow import DAG from airflow.operators.python import PythonOperator from airflow.models import Variable, BaseOperator from dags.slack_message import slack_message ...
b8a1394b9fa9cbc2ea7a856c2597794b946df34f1cd72bd13aacef81941ad6fd
Python
10,746
432
"""Harp device types""" from typing import Literal, Union from pydantic import BaseModel, ConfigDict, Field from typing_extensions import Annotated class HarpDeviceTypeModel(BaseModel): """Base model for platform""" model_config = ConfigDict(frozen=True) whoami: int = Field(..., title="Harp whoami valu...
4435b9a149499d1f30cc60e8c1e0cc2e1d539bfe30bc2fb60497e2ff4efa193e
Python
10,762
267
# -*- 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 exists from cellpose import models, io #Cellpose ML model for single cell segmentation from c...
8f57b3ca36f9d7e87896a608df20fd5eccfaae22b75a6347336fd6fbda991e6e
Python
10,786
351
"""Operator functions for synaptor DAGs.""" from __future__ import annotations import os from typing import Optional from airflow import DAG from airflow.utils.weight_rule import WeightRule from airflow.operators.python import PythonOperator from airflow.models import Variable, BaseOperator from worker_op import work...
1dd296c1f19588414233564584f9606e1ee950f0d9fa8d5b29560f01e3dcaab5
Python
10,790
322
import argparse import csv import io import os import pathlib import re import dateutil.parser as dateutilparser from datetime import datetime, timezone from tetra.database import DBWrapper from tetra.utilities import get_env_or_raise # Split <preset>_<config> into parts. def extract_preset_config(name: str, for_lat...
3dd5456bdb373f4f5b8513856a53da899e477a5b89b07843b5556e92a480a86a
Python
10,825
321
""" MISR-GRU for multi-image super resolution """ import torch.nn as nn import torch from torch.autograd import Variable class ResidualBlock(nn.Module): def __init__(self, channel_size=64, kernel_size=3): """ Args: channel_size : int (c), number of hidden channels kernel_s...
0568d0c9f06641ad1d8511327419b115e2dbfcaa1a206be4c8c1b40e5e321a89
Python
10,957
297
#!/usr/bin/env python3 """ prepare_pt_from_tiff.py Convert simulated TIFF stacks into normalized PyTorch tensors (.pt) in parallel. Typical use-case in this repo: - You already generated simulations as TIFF movies (e.g., noisy stacks). - You want to convert them into `.pt` tensors so training/eval loads fast. This s...
5ddad8959c73b102bf62be653c8a0cab02aad98df98fcd53afd6c2d54aa3ddc0
Python
11,012
371
from typing import Union, Iterable, Optional from collections import defaultdict import itertools import simdjson import re import os import struct import numpy as np from tqdm import tqdm from cloudfiles import CloudFiles from .... import exceptions from ....lib import yellow, red, toiter, sip from ....mesh import...
6c301c5d9033fbc7df4260a9f2441731f4a0bff73802f07ece5cc311435b0b63
Python
11,036
287
import numpy as np import os, sys import pickle import yaml from easydict import EasyDict as edict from typing import Any, IO from scipy.stats import mode from collections import Counter ROOT_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..') class TextLogger: def __init__(self, log_path): ...
feeea2750cc37ac07ff6647bbd95d107b8adae012800fbf0dd9f6db47ddca8c8
Python
11,111
296
from multiprocessing import Event, Process, Queue import numpy as np try: import nidaqmx from nidaqmx import Task from nidaqmx.stream_readers import AnalogMultiChannelReader from nidaqmx.stream_writers import AnalogMultiChannelWriter from nidaqmx.constants import Edge, AcquisitionType, LineGrouping ...
2eb8eccaf925467b87dc856d1fc03ac234419a0a6d70cbe1305e960cee4e50b8
Python
11,126
303
import os import re import functools import json import itertools import difflib import concurrent.futures import logging import time import tenacity from threading import Event from slack_sdk.rtm_v2 import RTMClient from slack_sdk.socket_mode import SocketModeClient from slack_sdk.socket_mode.request import SocketMode...
2a8eb0409de3d960d7538d7bc99a5bde6fac2e19e13953c05bfc3a24cddcb7f5
Python
11,185
307
from multiprocessing import Event, Queue from lightparam import Param, ParameterTree from lightparam.param_qt import ParametrizedQt from scanning import ( Scanner, ScanningParameters, ScanningState, RoiParameters, ImageReconstructor, frame_duration, ) from pathlib import Path from streaming_save...
33a816d2e585d5a19b6a5728960279d477a6249ddc1e8f628664130bf491872b
Python
11,237
340
import abc import os import typing import unittest from dataclasses import dataclass, field from functools import cache from data_paths import INPUT_FOLDER, OUTPUT_FOLDER, ROOT_DIR from tetra.timestamped_context import TimestampedContext from tetra.utilities import get_platform, run_with_timeout def _get_benchmarkin...
63cbc569e3b324fea2fb1dc0310f07cfee152e7e13ba3bded9005cacfffe372b
Python
11,243
476
# -*- coding: utf-8 -*- """Utility functions. """ import numpy as np from sigpy import backend __all__ = [ "prod", "vec", "split", "rss", "resize", "flip", "circshift", "downsample", "upsample", "dirac", "randn", "triang", "hanning", "monte_carlo_sure", "axp...