sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
70265fe9ac3bb30e882971babf683671a1f80845a4ce9e3f782594d3089605d8
Python
3,468
106
# -*- coding: utf-8 -*- # python standard library inputs import os # external inputs import numpy as np from nibabel.freesurfer.io import read_geometry, write_geometry def remove_vertex_outliers(input_surf, input_ind, n=5, overwrite=True): """Remove vertex outliers. This function removes outlier ve...
1a7053a9323dbac42c4fc8c98e5e9898a12f4215e349f46e2da03e752bab1642
Python
3,469
80
"""Known-answer controls, and the threshold they set. A match rate means nothing without knowing what the pipeline scores when the answer is "no match". These controls supply the floor, and the floor is what the tracking threshold has to clear. **The shift control must move the ROIs only.** An earlier control transla...
6f5527fb7ada00925076d78f556fc17ddeeb3dc833c97d4c051a96a275f77921
Python
3,469
113
#!/usr/bin/env python import storm_control.sc_library.halExceptions as halExceptions import storm_control.hal4000.testing.testActions as testActions import storm_control.hal4000.testing.testing as testing import storm_control.test as test # # Check the default parameters. # class ParamTest1Action(testActions.GetPar...
445c8ac8042dfd185a07deb70c967d993585f7f195860a4da1de0068b75e2ed9
Python
3,471
93
# coding=utf-8 """ Tests for deepreg/dataset/load.py in pytest style """ from typing import Optional import pytest import yaml import deepreg.dataset.load as load from deepreg.dataset.loader.unpaired_loader import UnpairedDataLoader from deepreg.registry import DATA_LOADER_CLASS, REGISTRY def load_yaml(file_path: ...
940b8ae8ede53665be61999da8cf998a27502c9c535ce4ae6f4c79a845a8b317
Python
3,471
94
import json from chemgraph.agent.llm_agent import ChemGraph from chemgraph.utils.get_workflow_from_llm import get_workflow_from_state import argparse import datetime def get_query( reaction: dict, query_name: str = "enthalpy", temperature: float = 298, pressure: float = 101325, method: str = "mace...
1e563ee782b9a63a8f54e5a8467862b4b269c92ed86f24b5de0750e0c8b70f88
Python
3,472
111
""" SPDX-License-Identifier: MIT SPDX-FileCopyrightText: © 2022 Renaud Bastien, Stephane Sanchez <stephane.sanchez@ut-capitole.fr> Université Toulouse Capitole - Institut de Recherche en Informatique de Toulouse Real Expression Artificial Life (REVA) Research Team https://www.irit.fr/departement/calcul-intensif-simulat...
6972ade1db96212c223a824e014dafd8be2a08b02db4e08fcaa0be9d7527389c
Python
3,475
94
import json from chemgraph.agent.llm_agent import ChemGraph from chemgraph.utils.get_workflow_from_llm import get_workflow_from_state import argparse import datetime def get_query( reaction: dict, query_name: str = "enthalpy", temperature: float = 298.15, pressure: float = 101325, method: str = "m...
9a669437ccd32890a28f6ebd3c384ea1cb2601c01b9645979790f1a8f90931d8
Python
3,475
119
# -*- coding: utf-8 -*- # external inputs import numpy as np from numpy.fft import fft, ifft, fft2, ifft2, fftshift def regrid_zero_2d(data_array, nx_new, ny_new): """Regrid zero 2D. This function loads a two-dimensional numpy array and performs spatial interpolation using zero padding in spatial frequ...
bbf15a346ab5c85565011b839cdf3fe3208006562724abc5e2fa258509b413ff
Python
3,475
103
#@ File (label="Reconstruction file (Leave empty for demo)", style="file", required=false) recFile #@ Float (label="Area per point (spatially calibrated units)^2", value=100) boxArea #@ String (label="Color mapping:", choices={"mpl-viridis.lut", "mpl-plasma.lut", "mpl-inferno.lut", "cool.lut", "Cyan Hot.lut"}) lutName ...
7444205a20111d30b61f1497330bd9436e34051a788b6cfab0ac84dad255df68
Python
3,476
94
from ..base_loss import * from .tensor_models import * import torch as th import torch.nn.functional as functional logsigmoid = functional.logsigmoid softplus = functional.softplus sigmoid = functional.sigmoid class HingeLoss(BaseHingeLoss): def __init__(self, margin): super(HingeLoss, self).__init__(mar...
6c614ea901288cb97a0381fdc27815e5801a7dd9a3fdf8298065412ddabc558e
Python
3,477
100
"""OpenRouter endpoint (OpenAI-compatible). Owns ``openrouter:`` prefix stripping, the ``OPENROUTER_API_KEY`` credential (never ``OPENAI_API_KEY``), the higher default token budget, and the restricted optional-parameter set. Logic moved verbatim from ``models/openrouter.py``. """ from __future__ import annotations f...
cdb213869e66889b7e7a41160f9395d7d0975d59f476e58c45b0775587e341d4
Python
3,477
109
import sys from datetime import datetime from colorama import Fore from tqdm import tqdm class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' OKPURPLE = '\033[0;35m' OKADVISORY = '\033[1;36m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033...
1990be1dfca692d14cfcf27dffb89d8a9c9c6e45d996105cd6eb9d841e72f668
Python
3,478
96
from abc import ABC, abstractmethod from pathlib import Path from typing import Union, Optional import numpy as np from auxiliary.io import read_image, write_image class Defacer(ABC): def __init__( self, masking_value: Optional[Union[int, float]] = None, ): """ Base class for d...
3f70b1c0abe4e8dee009e61398be605f6ff924f51564987adb0a040b35934343
Python
3,478
113
from dataclasses import dataclass, field from typing import Literal class BaseConfig(dict): """Dict that also supports attribute access (recursively).""" def __init__(self, *args, **kwargs): super().__init__() self.update(*args, **kwargs) def update(self, *args, **kwargs): for k,...
7670585872577ded339036ff7318df4c2d52a3aac20ac529147d88b2ac3e73c9
Python
3,478
90
# -*- coding: utf-8 -*- """ Functions to remove background in images The main routine subtracts a morphological opening from the original image for background removal. """ #:copyright: Copyright 2015 by Christoph Kirst, The Rockefeller University, New York City #:license: GNU, see LICENSE.txt for details. impor...
968f2507b7d6d26e4d5aa2082f95eee9de30a84ea5d5c710b9e66cedda81c014
Python
3,478
92
import argparse import os import os.path as osp import time import numpy as np import torch import torch.nn.functional as F from sklearn.metrics import f1_score import pandas import json import torch_geometric.transforms as T from torch_geometric.nn import ChebConv, GCNConv # noqa from tqdm import tqdm parser = argpar...
da94de29613d495384ec8ae4a24031149798e1a541b96bca0d7323da6a70b098
Python
3,478
95
'''ResNeXt in PyTorch. See the paper "Aggregated Residual Transformations for Deep Neural Networks" for more details. ''' import torch import torch.nn as nn import torch.nn.functional as F class Block(nn.Module): '''Grouped convolution block.''' expansion = 2 def __init__(self, in_planes, cardinality=32...
91bc126ad3ca8efd0b544bdf729ab363f2fcbc57db59357d00e72f2c27e65bb9
Python
3,479
76
from brainscore_vision import load_dataset, load_metric from brainscore_vision.benchmark_helpers.neural_common import TrainTestNeuralBenchmark, average_repetition, filter_reliable_neuroids from brainscore_vision.metrics.regression_correlation.metric import ALPHA_LIST from brainscore_vision.utils import LazyLoad BIBTE...
d7300cff5e8c4a30040c8855637383b7314a52d90717a07eb1a7d5d7eb4a8044
Python
3,479
102
import pyBigWig import numpy as np def read_chrom_sizes(fname): with open(fname) as f: gs = [x.strip().split('\t') for x in f] gs = [(x[0], int(x[1])) for x in gs if len(x)==2] return gs def get_regions(regions_file, seqlen): # regions file is assumed to be centered at summit (2nd + 10th col...
fed91b86f92b51ede6dde3b73414dc3d390a540e3465c8c442cc36223222113d
Python
3,479
86
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license import numpy as np from ultralytics.utils import LOGGER def onnx_calibration_reader(dataset, transform_fn, input_name: str = "images", batch: int = 0): """Create an ONNX Runtime calibration data reader from an Ultralytics calibration dataloader...
3fe61c54202443c7f8886ee6cd8a4fda6358341e0038f2ddbc146e25364fd9f6
Python
3,481
74
# Copyright 2025 BDP Ecosystem Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
43e90e9ddc6c227f0bcf919254550c24a5c9d1efdbb117ec5ab6a3e6f9f4b1eb
Python
3,481
99
""" Convert the original SeisT detection/picking weights (https://github.com/senli1073/SeisT, ``pretrained/seist_*_dpk_*.pth``) into the SeisBench weights format. The original checkpoints were trained on the DiTing dataset at 50 Hz with windows of 8192 samples. The state dict layout of :py:class:`seisbench.models.Seis...
8d0ac97d065588287bffb7cbedee0e28e30c8cad692f2b1bf76eb1d8f283fa92
Python
3,481
129
import numpy import tqdm from sklearn.manifold import TSNE class _Transform: def __init__(self): pass def fit(self, X): return self.transform.fit_transform(X) class tSNE(_Transform): def __init__(self): super().__init__() self.transform = TSNE(n_components=2, verbose=1,...
96c3e340c42b4530ebbe1ea16dee0255890444a959db8d73da1e5650f0cff67b
Python
3,482
89
import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.svm import SVC from sklearn.metrics import accuracy_score, confusion_matrix, precision_score, recall_score, f1_score from sklearn.preprocessing import StandardScaler import time from sklearn.decomposition import PCA import torch cla...
b5e89666e8e46f1859c074dec3e3889bb06df2666d0c747510b444e31b7bf339
Python
3,482
103
import argparse import os from pathlib import Path import pandas as pd from tqdm import tqdm import seisbench.data as sbd def transcode(data_in, data_out): dataset_args = {"missing_components": "ignore"} try: # Check if dataset is available in SeisBench dataset = sbd.__getattribute__(data_in...
9e5d869454545fb3eab1940f1d5efd7b342d4f05ed4241b31ada4cc67ee2b846
Python
3,483
96
from importlib import resources from pathlib import Path import pandas as pd import pickle import numpy as np from sklearn.preprocessing import StandardScaler def get_base_path(): return resources.files('resources') def get_MIST_nii_path(): base_path = get_base_path() return Path.joinpath(base_path, 'MIST1...
a83ac8992aa98104ebe8b33976c873857900d7fedca90e8e1b7ebdae37b19883
Python
3,483
89
"""Get interpretation of PCs and cluster centroids. Figures 3A, 4A. """ import numpy as np import pickle from utils import get_closest_farthest_words, get_clusters_dicts, get_vector_top_bottom_word_projections, get_stimulus_word_embeddings, get_pssd if __name__ == "__main__": model_type = "fasttext" pssd = ...
d6bed62dce972fc1aa5abd4eede8a55bf89173ae5c318145a2b3ea54714aef1a
Python
3,483
135
""" Random Forest Regression with Train–Test Split (Cortical Region-wise Analysis) This script implements Random Forest Regression for EEG-based cognitive workload estimation using a stratified cortical-region-wise analysis, as described in the study: "Estimating Cognitive Workload in Robot-Assisted Surgery Using Tim...
24114cb12e2bd874a5268b3a990760d856049ce5a7d95b8894fa9671c9e9a46b
Python
3,484
38
import numpy as np from nilearn.image import load_img import fire from nilearn.plotting import view_img from rich.progress import track import matplotlib.pyplot as plt base = "../bids_dataset/derivatives/" theories = { "symbolic": "./derive_theoretical_RDMs/symbolic/symbolic_sym_diss_mat.csv", "IT": "...
4c705928f545d065ffa049266090247e311a4ec88c7d175e297636c148a610f8
Python
3,484
93
import glob import os import scipy from nilearn.image import load_img, new_img_like, smooth_img from nilearn.plotting import view_img, view_img_on_surf from nilearn.glm.thresholding import threshold_stats_img import numpy as np import pandas as pd from joblib import Parallel, delayed from scipy import ndimage impo...
e4cc5edeb1af7f1341d716b845de8c29c93af07be75e5533bb284ea4b509ff15
Python
3,485
99
from typing import Dict, List, Any, Optional from abnumber import Chain # conda install -c bioconda abnumber def _default_scheme(mt: str) -> str: return "imgt" if mt.upper() == "TCR" else "chothia" def _chain_letter(mt: str, which: str) -> str: mt = mt.upper() if mt == "TCR": return "B" if which ...
01ef2e809708da3a721697581cb9727b8e9bd7323a840a062e901ff9bb76e4ea
Python
3,486
111
import sys import yaml import os import h5py import numpy as np save_ratevec = True smoothingstyle = 'savgol' pathpath,recfilename,regstr = sys.argv[1:] regs_of_interest = [bla.strip() for bla in regstr.strip('[]').replace("'",'').split(',')] badtimesdir = 'ZENODOPATH/preprocessing/bad_times_manual' recid0 = os.pat...
20519bfdf088499605c9fe3e13492db03b608ffb8e28f41b57c4fbfe7dd4d11c
Python
3,487
96
import numpy as np import pandas as pd import matplotlib.pyplot as plt import scanpy as sc import ot from sklearn.metrics.cluster import adjusted_rand_score from typing import Optional, List, Union import logging class ClusterAnalysis: """Class for clustering analysis and evaluation.""" @staticmethod ...
20992043476e6ea2de70fb55d18d89c1ba359230f19830ad63241408e6cb4ef1
Python
3,487
135
#!/usr/bin/env python # # cleanup.py # # copyright F. Nedelec, December 14th 2007 """ Scan recursively from current directory, and clean up temporary cytosim files Syntax: cleanup.py [walk=1] [commit=1] directory-list Example: cleanup.py data* F. Nedelec, April 2013 """ import sys, os...
a05d175731ad3ad226b1d3a4c1750eaf440e436a73f2c8eb2a2b7b4208824234
Python
3,487
102
from __future__ import annotations from typing import Final import numpy as np import numpy.typing as npt from ._model import ORIENTED_RECTANGLE_POINT_COUNT from ._model import Shape def _is_full_oriented_rectangle(shape: Shape, /) -> bool: return ( shape.shape_type == "oriented_rectangle" and ...
98ac7154e88ec08f6ba998982bb5b3696ff5a7542c893e94cbe804f514088d17
Python
3,489
103
import ast import numpy as np from nems.registry import layer from .base import Layer class NumPy(Layer): """Applies a NumPy operation to inputs. Parameters ---------- operation : str Name of `np.{operation}` to apply to data, ex: 'concatenate'. op_args : N-tuple; optional. P...
1cfbbacff273d4612f9b67b47aed6a5ac7dbcc59aaa1e67d852281c414e1059d
Python
3,490
115
import numpy as np import brainscore_vision from brainscore_core.supported_data_standards.brainio.stimuli import StimulusSet from brainscore_core.supported_data_standards.brainio.packaging import package_stimulus_set_locally from brainscore_core.supported_data_standards.brainio.assemblies import DataAssembly from bra...
503bc02faceb0fd5ea9f7a264bca4743fc89012c987e261e93f6f64c9158b600
Python
3,490
114
#!/usr/bin/env python3 import arbor as A from arbor import units as U import numpy as np import pandas as pd import seaborn as sns # You may have to pip install these. class single_recipe(A.recipe): def __init__(self, dT, n_pairs): A.recipe.__init__(self) self.dT = dT self.n_pairs = n_pa...
5ec868883db64d31fb1397bcdf7d86056eea3093bc4fd8217fed3c3503b845fa
Python
3,490
106
# src/utils/early_stopping.py """ EarlyStopping 模块 ------------------ 封装训练过程中的早停机制,独立于其他工具文件,便于单独配置与调参。 类 EarlyStopping --------------- 监控单个指标(如验证集损失或验证集 MCC),在指标在 patience 个连续 epoch 内未改善时,触发 early_stop=True。 每当指标改善时自动保存当前最佳模型权重。 使用示例 -------- from src.utils.early_stopping import EarlyStopping early_stopper = Early...
832575322de6cf118932b9a99c2e892b0ffb32a6dbe6b13a89433cfdfdf799cd
Python
3,490
114
#!/usr/bin/env python """Direct EnsembleLauncherBackend demo on an HPC compute node. 5-molecule thermo screen via the EnsembleLauncher orchestrator, managed mode (the backend starts and tears down the orchestrator itself). Must run inside ``qsub -I`` on Polaris or Aurora, in a venv where ``ensemble_launcher`` is insta...
99916dcb0c7bc5ee43326c2155461920b997bf2aab5749d51d199d7addf53318
Python
3,490
110
#!/usr/bin/env python3 import os import gzip import urllib.request, urllib.error, urllib.parse import inspect import unittest import logging import bt2face import btdata import subprocess from optparse import OptionParser class TestLargeIndex(unittest.TestCase): """ Main fixture for large inde...
159c2ec2f0a78a1bea6d3e0f7066fb19f2c0205818f09fdb9fa9ecddb35cd846
Python
3,491
91
"""Tests for the `morphometrics validate` command.""" import numpy as np import pytest mrcfile = pytest.importorskip("mrcfile") from click.testing import CliRunner from surface_morphometrics.validate import validate_cli, _present_label_values def _write_seg(path, values): """Write a tiny segmentation MRC contai...
c225d8c776d931d582608f0740bbec1d8f10fadf093901110143db8c419ede97
Python
3,491
109
# -*- coding: utf-8 -*- # python standard library inputs import os import datetime # external inputs import numpy as np import nibabel as nb from nighres.registration import apply_coordinate_mappings # local inputs from ..io.get_filename import get_filename from ..utils.resample_volume import resample_volume def a...
d0637bcc9da36e18806a1e28f9a2947d2fccbeaba80f603320c317ac124afb77
Python
3,491
99
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license """Build and smoke-validate export test virtual environments from the exporter registry.""" from __future__ import annotations import argparse import os import shutil import subprocess import sys from pathlib import Path import psutil REPO = Path(_...
becd0740e2397e11007fa21a692d8a2fac3baa92a05b54a1264b91d06dc63e85
Python
3,492
78
# #!/usr/bin/env python # encoding: utf-8 ''' @author: Yang Sui @contact: yangsui@uw.edu @ Prerequisite: module load annotsv/3.4 AnnotSV -SvinputFile annotSV.input.bed -svtBEDcol 4 -candidateGenesFile NDDgene.txt -promoterSize 500 -REreport 1 -outputFile truvariSVsanno ''' import pandas as pd import numpy as np # r...
3c9b7bb3b8f6fbe4edcce39b278015a55a1bbff1314ad0d5b58c26efbc0070b9
Python
3,493
84
import torch from tqdm import tqdm from dataset_tool import fast_merge import numpy as np from transformers import pipeline, T5Tokenizer, T5EncoderModel import os user,tweet=fast_merge(dataset="Twibot-20") user_text=list(user['description']) tweet_text = [text for text in tweet.text] feature_extract=pipeline('featu...
57f783c949bea81c3b7ca907fbd9b7937827a881adcb9a6ae0c6208ede546af7
Python
3,494
93
import json from chemgraph.agent.llm_agent import ChemGraph from chemgraph.utils.get_workflow_from_llm import get_workflow_from_state import argparse import datetime def get_query( reaction: dict, query_name: str = "enthalpy", temperature: float = 298, pressure: float = 101325, method: str = "mace...
5bd295d592bd9b747d3b60a1b1019b2b42187f091d1ed4b40510ea719b91628b
Python
3,494
79
# A script to visualize the ERF. # Scaling Up Your Kernels to 31x31: Revisiting Large Kernel Design in CNNs (https://arxiv.org/abs/2203.06717) # Github source: https://github.com/DingXiaoH/RepLKNet-pytorch # Licensed under The MIT License [see LICENSE for details] # -----------------------------------------------------...
e93832a13e4f1b16304d61aa47f4e08d648995939419776d7c0532a8ddbb84e0
Python
3,494
116
from collections.abc import Sequence from typing import TYPE_CHECKING import pytest from eir import train from tests.test_modelling.test_modelling_utils import check_performance_result_wrapper if TYPE_CHECKING: pass def _get_survival_output_configs(type_: str) -> Sequence[dict]: if type_ == "discrete": ...
610acee4fdec1316d7caaf9f8f9a59e4cd27f61745a7add7f78769cbf18a6136
Python
3,496
191
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Process markers_MB-KCc-KCn files """ import os import mbflim.utils as ut import mbflim.image.image_processing as pro import mbflim.image.image_set_processing as setpro import mbflim.visualization as vis #%% Parameters study = 'MB-KCc-STn' # 'MB-KCc-KCn' or 'MB-KCc...
90da10365d7f56a59ec699fc949387c0bc1e7f2506b2bd93bf4ea95aaaeab60d
Python
3,496
112
from spine_fitter import SpineFitter from spine_metrics import SpineMetricDataset from typing import List, Tuple, Union, Callable, Set from ipywidgets import widgets from matplotlib import pyplot as plt from sklearn.cluster import DBSCAN, KMeans from sklearn.metrics import silhouette_score import numpy as np from sklea...
930d3ce1db50e47c6f4794c00a28a8373ed42875ef70b7d7f669d2ae420fbefb
Python
3,496
124
""" Download the demo data and sort them into train, val and test in h5 files """ import os import shutil import zipfile import h5py from scipy import ndimage from tensorflow.keras.utils import get_file PROJECT_DIR = "demos/grouped_mask_prostate_longitudinal" os.chdir(PROJECT_DIR) DATA_PATH = "dataset" ZIP_FILE = "d...
86f530b50537f283489b35efe2ce99d37b03875039244460ef0fc1855c97e08f
Python
3,497
116
#!/usr/bin/python # -*- coding: latin-1 -*- # ============================================================================================= # Librairies importation import numpy as np import nrrd import sys import os # ============================================================================================= ...
3a8b29e44077982d3ab4c450961cae6acf1dd29a229b1ba8b58bff58615acd18
Python
3,498
104
import torch import matplotlib.pyplot as plt def post_synaptic_weight(thetas, p_exc): n_e = int(thetas.shape[1] * p_exc) exc = thetas[:, :n_e] inh = thetas[:, n_e:] exc_sum = exc.sum(1) inh_sum = inh.sum(1) exc = torch.where(inh_sum > exc_sum, exc.T, exc.T * inh_sum / exc_sum).T inh = torc...
7caa1d83fdcfb8a2e536d091caa6c2f5ebef4903132a2febd9ab9e94a4f064e5
Python
3,499
112
import numpy as np import pandas as pd import pytest from pandas.testing import assert_frame_equal from eir.interpretation.interpretation_utils import get_long_format_attribution_df def test_get_tabular_attribution_df_basic(): input_data = { "feature1": [0.1, 0.2, 0.3], "feature2": [0.4, 0.5, 0.6...
3cfd6fbabf418720c3dbad72f8e0fc8838a2e5c5ab941f4d3d01d34925a528da
Python
3,501
80
# -*- coding: utf-8 -*- ################################################################################ ## Form generated from reading UI file 'new_annotation_dialog.ui' ## ## Created by: Qt User Interface Compiler version 6.4.2 ## ## WARNING! All changes made in this file will be lost when recompiling UI file! #####...
e56239c4d90f84f086478804ddb90a73fd3e9b84b972e6eff64f8cbf59f72263
Python
3,501
119
# Copyright 2017 Calico LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
0d503a794ae7c0c95ef456d591605771bb1437f9a294a71a044a36796978ffc5
Python
3,502
122
#!/usr/bin/python3 # import os import sys import argparse import shutil import numpy as np from uac import utils # Create the parser my_parser = argparse.ArgumentParser(description="Calculation of labels using laplace solves and landmarks") # Add the arguments my_parser.add_argument("target_path", metavar="path", ty...
2812afb1ae44fdeddf8d599eee94431f3ff85d91089cc3a748e29e30483b851b
Python
3,502
73
import numpy as np import OptimalBattery.util as ut import os import OptimalBattery.evaluate as ev import Functional_Fusion.atlas_map as am from Functional_Fusion.dataset import DataSetMDTB from IndividualParcellation.global_config import * import OptimalBattery.construct as ct import OptimalBattery.plot as plot import...
3c9883cbe93071f59f6cf6616b28cdf527c0f5ff430cbc855d83b6e6b50c6004
Python
3,502
84
# -*- coding: utf-8 -*- """ DoG filter module """ #:copyright: Copyright 2015 by Christoph Kirst, The Rockefeller University, New York City #:license: GNU, see LICENSE.txt for details. import sys from scipy.ndimage.filters import correlate #from scipy.signal import fftconvolve from ClearMap.ImageProcessing.Filter.F...
4774a3df3a250aeb9e75415027eb35592e81e76e6136ab7d10326840d95695d1
Python
3,504
93
""" AssociationStore: Persists input→output directory associations per user. Stored in ``~/.musclex/directory_associations.json``, keyed on the canonical absolute path of the input directory. Copyright 1999 Illinois Institute of Technology Permission is hereby granted, free of charge, to any person obtaining a copy ...
a8a378329ec17d9bec8c26e35a0ff53c83fd0247a53afb6286f281cd7a83c9fc
Python
3,505
104
#!/bin/python """ python Py_write_dPCA_assign_fortran.py all.txt Created by Diana Slough Created on 1-5-2017 This program reads all.txt (from dPCA) and writes Assign.f90 """ import sys,os import numpy as np import math ########################################################## def read_lines(f): lines=[] f...
b0b03bf7efb046d4d36b8cdc2dc852cf6eca2e7daaacbe76dcb98eb453245873
Python
3,505
93
""" Register stimulation data to anatomical images """ import nibabel as nb import numpy as np import subprocess import os import glob ROOT = "/Volumes/sDresBackUp/s1Anfunco/Nifti" # Set subjects to work on subs = ['sub-18'] # subs = ['sub-09', 'sub-10', 'sub-12', 'sub-14', 'sub-15', 'sub-16', 'sub-17', 'sub-18']...
c8af0eec21066955740dea148085317d1680549ef8ea2434f3c0a26a0bc4d0cc
Python
3,505
100
"""Connected clusters cluster size thresholding commandline interface.""" import os import argparse import numpy as np from nibabel import load, save, Nifti1Image from skimage.measure import label parser = argparse.ArgumentParser() parser.add_argument('filename', metavar='path', help="Path to ni...
3b6fdb78780f76d43377ef59728f87caecfe9602fe708f04de03f9eef2e579a0
Python
3,506
99
from __future__ import annotations import pytest from PySide6 import QtGui from pytestqt.qtbot import QtBot from labelme._widgets._label_dialog import LabelDialog def _make_dialog(qtbot: QtBot, /, *, flag_count: int) -> LabelDialog: flags = {f"flag_{i:02d}": False for i in range(flag_count)} dialog = LabelD...
88a89cb7ce8efd1b1f66092d618992edb4102eb188e5fa2368b378534e752c57
Python
3,506
75
"""Test the functions in the yasa/sleepstats.py file. The public ``transition_matrix`` and ``sleep_statistics`` functions are deprecated (see ``test_hypno.py::test_deprecated_functions``). These tests check the values of the shared implementation used by :py:meth:`yasa.Hypnogram.transition_matrix`. """ import unittes...
dd5413c62450fede9b72ef544c6ef9421742bba791c5c3d5d4d9241340003996
Python
3,506
116
from collections.abc import Sequence from typing import TYPE_CHECKING import pytest from eir import train from tests.test_modelling.test_modelling_utils import check_performance_result_wrapper if TYPE_CHECKING: pass def _get_survival_output_configs(type_: str) -> Sequence[dict]: if type_ == "discrete": ...
6539173c90863bc3afeacec43b8bfc37037585050f255b046bdb33ea4a441cc9
Python
3,507
83
from scipy import spatial import numpy as np def exponentiated_quadratic_kernel(xa, xb, sigma): # L2 distance (Squared Euclidian) sq_norm = (-0.5 / pow(sigma,2)) * spatial.distance.cdist(xa, xb, 'sqeuclidean') return np.exp(sq_norm) def _generate_gaussian_process_path(path_boundary, options, n_poll): ...
6ee7b287de1935895d51ab3865a1d563784d8036b0d4f1a43557c27b9d795ab3
Python
3,507
96
"""Load Gemini models using LangChain.""" import os from getpass import getpass from langchain_google_genai import ChatGoogleGenerativeAI from chemgraph.models.supported_models import supported_gemini_models from chemgraph.utils.logging_config import setup_logger logger = setup_logger(__name__) def load_gemini_mode...
ada91b733dd271bc8ca6768c1feeaed5b159b5b5b6f833295e4851a3ee9f9cd6
Python
3,507
85
import sys from pathlib import Path import os sys.path.append(str(Path(os.path.abspath(__file__)).parents[3])) import argparse import torch from torch_geometric.nn import Node2Vec from ogb.linkproppred import PygLinkPropPredDataset from torch.utils.tensorboard import SummaryWriter # limit load for the server os.enviro...
d07894087336b3808306d79ff02c90c49d97111092bf9843fee45b37463f8653
Python
3,508
104
# Copyright 2024 Google LLC # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # https://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, sof...
fe1b50fe8b8c89b09e79e9a0d34f7bbfb9e3d78a9794502da52f47550c28a8d2
Python
3,508
99
""" A dataset reader that extracts images from folders Folders are scanned recursively to find image files. Labels are based on the folder hierarchy, just leaf folders by default. Hacked together by / Copyright 2020 Ross Wightman """ import os from typing import Dict, List, Optional, Set, Tuple, Union from timm.util...
14b38d41d81a6b3a4bf9b41221d2101372c50490f6f0a03a7b7ad3e47a416790
Python
3,509
97
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Split a label image into multiple images where the name of the output images is the id of the label (ex. 35.nii.gz, 36.nii.gz, ...). If the --range option is not provided, all labels of the image are extracted. The label 0 is considered as the background and is ignored...
2c0b3fce074abd8b0be22142543a990fdc4117a7604f7d271b538d3649dd9ecf
Python
3,510
81
import sys import os import time import numpy as np import pandas as pd import matplotlib.pyplot as plt import torch import torch.nn as nn import torch.optim as optim from torch.nn import functional as F import random from sklearn import metrics from collections import Counter inpt_ = "mock_genomes.npy" #input genotyp...
70bebaf7635a6196098aa81eb0384271d17f884aebec17e2b379da61364fb21e
Python
3,510
66
import numpy as np import pickle import pandas as pd import fire from rsatoolbox.inference import eval_fixed from rsatoolbox.model import ModelFixed from nilearn.image import new_img_like, load_img from rsatoolbox.util.searchlight import evaluate_models_searchlight theories = { "symbolic": "./derive_theoretica...
f25429e134396979ca53c1763b75b09fcdb88613221453c4dd32ceb9cf9d1d09
Python
3,510
85
#!/usr/bin/env python3 """Simulate a closed control loop and record it to a ``.tha`` file. A *closed loop* is the defining Thalamus use case: a value is measured, a rule decides on an action, and that action feeds back and changes the value. In a live pipeline you'd wire it as ``sensor -> ALGEBRA/TOGGLE (decide) -> o...
3b6e30cd5df548985d359927dab24c0c7f0bc32611f0139f9b8a2d8ab6671079
Python
3,511
104
import os import lmdb import pickle from multiprocessing import Pool from tqdm import tqdm import numpy as np import argparse from multiprocessing import cpu_count nthreads = cpu_count() def inner_read(cursor): key, value = cursor data = pickle.loads(value) if "y_relaxed" in data: ret_data = { ...
70d156b8142dca5b4c1b51b0303c05816f8ecd381db4c7010fa71cd21d5e7dea
Python
3,511
101
import torch from torch.autograd import grad from knn_cuda import KNN import torchsort def gradient(inputs, outputs, create_graph=True, retain_graph=True): d_points = torch.ones_like(outputs, requires_grad=False, device=outputs.device) points_grad = grad( outputs=outputs, inputs=inputs, ...
4f4b5e85dca462894cf2b33c8f9f20d8220f6f27b3453d90351350f2991ea1e8
Python
3,512
111
import numpy as np import os from typing import Union, List # `List` instead of `list` for backwards compatibility import h5py import glob from PIL import Image import numpy as np import os __all__ = ['dump_npz', 'load_npz', 'tif_to_h5', 'tif_to_stack'] def dump_npz(filepath, data: dict, force=False, dry=False, compr...
fee407c255d4630c00194fbe8a0d0868a31b23388b42f20e6857a20dce4013b7
Python
3,512
97
import pdb import os import glob import matplotlib.pyplot as plt import sciplotlib.style as splstyle import matplotlib as mpl import natsort from PIL import Image import numpy as np def combine_plots_across_div(recording_div_folders, plot_names=['FiringRateByElectrode.png'], fig=None, axs=None): """ Parameter...
34fb268d643187897d12478442c6bd89fb06f512ecb0cef3aac98d9e148cea73
Python
3,513
104
import sys import os import time import numpy as np import pandas as pd import matplotlib.pyplot as plt import torch import torch.nn as nn import torch.optim as optim from torch.nn import functional as F import random from sklearn import metrics from collections import Counter from captum.attr import (IntegratedGradien...
5aed40ffd872bfce7337dd5f3a3440d4f21393712e5fd680be635a0f330f5ed0
Python
3,513
78
import librosa import matplotlib.pyplot as plt import numpy as np import soundfile as sf import noisereduce as nr class NoiseReduceFilter: def __init__(self, mode='stationary', n_fft=2048, hop_length=512, win_length=None, n_std_thresh_stationary=1.5, prop_decrease=1.0, time_consta...
29340d42df40220dc39e428ee415f06ced9e3673e80bcd0e536cd01e727c1efc
Python
3,514
89
# NOTE: 128-256GB CPU memory required to run this script. import os import time import argparse import os.path as osp from tqdm import tqdm import torch import numpy as np from torch_sparse import SparseTensor from torch_geometric.nn.conv.gcn_conv import gcn_norm from ogb.lsc import MAG240MDataset from root import RO...
399794018a5e6a87e3cecf8c62c29d1afbe1e0162edaf2ddd67baa157d96b048
Python
3,514
92
import torch from torch.utils.data import DataLoader from tqdm import tqdm class MinMaxScaler(): """Transform features by scaling each feature to a given range. Args: min (FloatTensor): Per feature adjustment for minimum. scale (FloatTensor): Per feature relative scaling of the data. ...
019ea83fc076f263bd3c7d0e215bbb66e6b391bb0fb72e2a8c7f55411cd2fac2
Python
3,515
111
import numpy as np import torch from torchvision.transforms import v2 class SelectChannels(object): """ Select subset of channels from image to be used. # object: list(P["SELECTED_CH"]) """ def __init__(self, selected_channels: list): self.selected_channels = selected_channels ...
127d907711f072f0b9a6311c5511fa024cfbd3c7b8cee0826cb4814c119ee384
Python
3,515
85
import os import glob import numpy as np import skimage.io as skio import torch from torch.utils.data import Dataset import random from natsort import natsorted import json class KidneyData(Dataset): def __init__(self, root='data/', mode='train', separation='90_10', fold=0, all_zero_involved=False, transforms=None...
5bc5137e5d41f597c6393f727342acc346b797b2d91d138bb2bcc7daf7e8028a
Python
3,515
59
import numpy as np import sys def pairwise_euclidean_distance(array_1, array_2): '''Calculates the pairwise Euclidean distance between two arrays of points.''' squared_distances = np.sum((array_1[:, np.newaxis] - array_2) ** 2, axis=2) return np.sqrt(squared_distances) def setup_stimulation_grid(pixel_size, stim_g...
dfbcd376dd207d20143ccb705e3660e665b1fe2b688c954534e0d8475875721d
Python
3,515
139
from .message_passing import MessagePassing from .simple_conv import SimpleConv from .gcn_conv import GCNConv from .cheb_conv import ChebConv from .sage_conv import SAGEConv from .cugraph.sage_conv import CuGraphSAGEConv from .graph_conv import GraphConv from .gravnet_conv import GravNetConv from .gated_graph_conv impo...
7d3a1697c781e8d8789196927714a6ab0153a4b5986ea3f876952cc9af6c52cb
Python
3,517
120
from pickle import FALSE from datagenerator_pd import DataGenerator from sklearn.metrics import confusion_matrix, accuracy_score, roc_curve, auc from tensorflow.keras.utils import to_categorical import matplotlib.pyplot as plt import seaborn as sns import SimpleITK as sitk import pandas as pd import numpy as n...
5fd3ed8c60cc5e39643a133fcbc8e8fd68330e6ff04c067274d4c9b300f83774
Python
3,518
108
import os import pandas as pd from sklearn.metrics import accuracy_score, roc_auc_score, f1_score, precision_score, recall_score def lcs(dna: str) -> None: global lcs_string global user_list global genes cnt = 0 for user in user_list.keys(): if dna in user_list[user]: cnt +=...
9e5a476166e5905918d45077fc1d4c9fc5556b99d0822ccbf27f3399fcc5afdb
Python
3,519
93
from model import DeeProBot from dataset import training_data,val_data,test_data import torch from torch import nn from utils import accuracy,init_weights from torch.utils.data import DataLoader from sklearn.metrics import f1_score from sklearn.metrics import matthews_corrcoef from sklearn.metrics import precision_scor...
c88d64d85d65f512f0fb34891e79680882189bf437e2e2d0dc7e215fff848e5b
Python
3,519
102
# Copyright 2024 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...
ecda4eb34b9ae474bdc7848db5e78de0e1e10b0b7b51ac95b1f35123e7e5640c
Python
3,519
99
import pytest import warnings import logging from ase import Atoms # Configure pytest-asyncio #pytest_plugins = ("pytest_asyncio",) # Test modules that require the optional ``academy`` extra guard themselves with # ``pytest.importorskip("academy")`` at module top, so they skip cleanly (rather # than erroring collecti...
fef30a22e06dad490c9c4658197426f3707386833e5802278a9c54d7c50e4de5
Python
3,519
115
import torch import torch.nn as nn from dataclasses import dataclass, field from dgl.nn import GCN2Conv, GraphConv @dataclass class Args: device: str = 'cpu' epochs: int = 1000 lr1: float = 1e-3 wd1: float = 0.0 lambd: float = 1e-3 n_layers: int = 9 der: float = 0.5 dfr: float = 0.3 ...
9f8433bff72d8334e2dc358ba8fe532eb44ae1ddb5da45a1e6625164c1aa91d2
Python
3,520
96
import numpy as np from src.wrappers.OsipiBase import OsipiBase from src.original.fitting.ETP_SRI.LinearFitting import LinearFit import warnings warnings.simplefilter('once', UserWarning) class ETP_SRI_LinearFitting(OsipiBase): """WIP Implementation and execution of the submitted algorithm """ # ...
6b2e99d136f20b6b38167e2ba764bca01eaa1437e9d7de4b0f9f73cfad39725e
Python
3,521
94
import sys import time import getopt from scipy.sparse import csr_matrix from slice_dataframe import slice_dataframe import anndata as ad import pandas as pd import numpy as np from anndata import AnnData ############################################################################# # usage def gem_to_h5ad_usage(): ...
a942a902cb33afceaa4c643f88fede2071549a8b948eb7eac88b7fd063f0c983
Python
3,521
111
#!/usr/bin/python # ## @file # # Qt Widget for displaying color scales # # Hazen 3/09 # from PyQt5 import QtGui, QtWidgets import sys ## QColorGradient # # This class handles displaying a color scale based on the current color table. # class QColorGradient(QtWidgets.QWidget): ## __init__ #...
d3ec7b3b48376ca8409c2c65db121e69ab41d1245f2c37dbc36b92155f40aec3
Python
3,521
103
import os import numpy as np import yaml import sys pathpath = 'PATHS/filepaths_IBLTuning.yml'# myrun = 'runIBLTuning_utypeP' layers_allowed = ['5','6'] nshuff = 2000 signif_levels = np.array([0.05,0.01,0.001]) tuning_attr_names = ['stimTuned','choiceTuned','feedbTuned','taskResp'] blk_condition = 'detail' pthr_cc...
1ebc1306c330fa7fa3701bd1cb996908d405cbb01dbcaed1a1286493401d4630
Python
3,522
94
import numpy as np from sklearn.metrics import pairwise_distances from tqdm import tqdm import pandas as pd import matplotlib.pyplot as plt import seaborn as sns def jaccard_distance_matrix(binary_matrix): """Compute sample-wise Jaccard distance matrix.""" return pairwise_distances(binary_matrix.T, metric='jac...
853b7a69768319d8a7e5400504f78d170eb83220d804f1c2acc3529012f0e1d8
Python
3,522
96
"""Plot projection onto the primary tuning shift dimension. Figure 4B. """ import matplotlib.pyplot as plt import numpy as np import os import pickle from utils import ( do_flip_colors_dict, get_pssd, get_voxel_to_fsaverage_mapper, load_model_results, num_fsaverage_vertices, participant_names,...