sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
4b3998b0d303090c0e0c9922867058d80c7e604c0a58755f4b9e5b0d57da20ff
Python
1,657
56
import glob, os import subprocess import vtk import vtk.util.numpy_support as VN import numpy as np import sys from pathlib import Path import json def diff(sim_path, test_path, verbose=False): # create a reader reader = vtk.vtkXMLImageDataReader() # read file0 reader.SetFileName(str(sim_path)) reader.Updat...
62370d4242e27e4d04fff3b80b9df20dde19105a857e50de04829369ce014679
Python
1,657
51
#!/usr/bin/python3 import numpy as np # evaluate a specific function a few times with one sample import cec2017.functions as functions f = functions.f5 dimension = 30 for i in range(0, 10): x = np.random.uniform(low=-100, high=100, size=dimension) y = f([x])[0] print(f"f5({x[0]:.2f}, {x[1]:.2f}, ...) = {...
eeda5519e3ddec56f248a078c8aeaf9e9945cd5e7b3a9351950126395b2e080d
Python
1,657
55
import networkx as nx import numpy as np import pandas as pd from brainways.utils.network_analysis import calculate_network_graph def test_calculate_network_graph(): region_1 = np.random.rand(100) region_2 = region_1 * 100 + np.random.rand(100) region_3 = np.random.rand(100) # Create synthetic data ...
5098d8089d353ead8076a28ea528af2097ccffe0e2baff989323d8661bc0415e
Python
1,658
40
""" Self-contained model-function variants for A/B speed benchmarking. Each sub-module exports the same public API:: layerlineModel(x, centerX, bg_line, bg_sigma, bg_amplitude, center_sigma1, center_amplitude1, center_sigma2, center_amplitude2, **kwargs) layerlineModelGM...
c4b41459de681e1cb78233bfb235363624d63cb195d1164bf52e071ff208e573
Python
1,659
46
import numpy as np from nems import Model from nems.layers.base import Phi, Parameter from nems.distributions import Beta def test_phi_bounds(): m = Model.from_keywords('wc.18x4.g') # 8 parameters phi = m.layers['wc'].parameters assert len(phi.get_bounds_vector()) == 8 lower1, upper1 = (0, 1) lo...
c8ae1fa6c25d26b9be15b8e4e5c07e15fd386bff05ac6f73cf51a7c49a42f0d9
Python
1,659
56
from typing import List, Union import numpy as np def normalize_array(arr: np.ndarray, v_min=None, v_max=None) -> np.ndarray: """ Normalize a numpy array. The array is normalized such that its values are normalized from [v_min, v_max] to [0, 1]. If min/max are not provided, will use the min/max ...
f4ec3c8b27bd4a7f6114e10d3a454be5e9f1997789dffba718ecf1e68426fc02
Python
1,659
57
from __future__ import annotations import pytest from labelme._shape_color import resolve_shape_color @pytest.mark.parametrize( ("config", "expected"), [ ( { "mode": "auto", "auto": {"shift": -1}, "uniform": {"color": [0, 255, 0]}, ...
0c03b532a96c1ee3325f82a365bb53037cdb9854d806327e6e58638077d9cea9
Python
1,660
39
"""Acquire and extract Schmidt supplements needed to interpret replication.""" import json from pathlib import Path from xml.etree import ElementTree from zipfile import ZipFile from src.acquisition.download import ROOT, acquire, sha256 WORD = '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}' def ex...
f15c6e3691466b382f8216320bc6744b4b6889a8ce2b2f4f485e1fbcc33a56a4
Python
1,660
61
import sys import getopt import numpy as np import pandas as pd def usage(): print(""" Usage: python3 s02.filter.py [-f filter threshold, default 0.05] [-o output folder, default ./] we will load data generate by s02 in output folder! """) def main(argv): ###############...
1d4e2d63266d4a999b7ff4a07c87550a87b894800b7f515416ac634e47d6bbd8
Python
1,661
48
#!/usr/bin/python # Create bitmaps to check defacing of all NIFTI images # python bids_deface_bitmaps.py from pathlib import Path import os import os.path import glob import sys import shutil import fnmatch def remove_after_final_underscore(input_string): # Find the last underscore index last_underscore_ind...
3911705db8868f2660d5a6c96f80ede7cc121951c58f10b20062537f22ac293d
Python
1,661
35
from brainscore_vision.model_helpers.activations.pytorch import PytorchWrapper from brainscore_vision.model_helpers.activations.pytorch import load_preprocess_images import ssl import functools import antialiased_cnns from brainscore_vision.model_helpers.check_submission import check_models ssl._create_default_https_c...
43cad4c0b11a94b4fa8ee6ef8615aac4458b90e5b0c6e45ca3c8b31824795786
Python
1,661
46
import torch class FastTensorDataLoader: """ A DataLoader-like object for a set of tensors that can be much faster than TensorDataset + DataLoader because dataloader grabs individual indices of the dataset and calls cat (slow). Source: https://discuss.pytorch.org/t/dataloader-much-slower-than-manua...
df6abf0b4216c52cf3f37a3bb42d1adba84a33996f4718784c057adf5cd79b60
Python
1,661
62
#!/usr/bin/env python # ## @file # # This parses log file series (i.e. log, log.1, log.2, etc..) to # make it easier to see which functions / methods call which other # functions / methods. It is used mostly to make sure that what # we expect to happen is actually happening, and to try and # identify unnecessary functi...
648343d78eef0df035d5db31851bf8a5069df6a3e3d8da6b3160543367ddb4a8
Python
1,662
44
import subprocess import yaml def save_initial_data(): version_name = 'v1' data_path = input('Data path:') print("Saving initial data") subprocess.run(["dvc", "add", "data_path"]) subprocess.run(["git", "add", ".gitignore", data_path + ".dvc"]) subprocess.run(["git", "commit", "-m", "data: Save...
85a06f785b9bddf00f74194f49fb360873581b73467ea8d2c34ce40a6877318e
Python
1,662
60
import pytest import numpy as np # Generic data fixtures for use by test_layers and others. spectrogram_seed = 12345 response_seed = 678910 state_seed = 111213 # TODO: Replace with either useful synthetic data or a short snippet of # real data. # TODO: These are based on LBHB's needs (i.e. sound spectrogram an...
cda42daa1b39e4b53e7ba28f0b8ca56927607b82af128b1ea8eb7ba660338b6b
Python
1,662
47
import torch import torch.nn.functional as F from torch import Tensor from torch.nn import Parameter class MessageNorm(torch.nn.Module): r"""Applies message normalization over the aggregated messages as described in the `"DeeperGCNs: All You Need to Train Deeper GCNs" <https://arxiv.org/abs/2006.07739>`_ ...
4a5aca0c35bdadcf2aea4d9fae8dc2bfd8b340c85e481f8a32c105c70e8063d8
Python
1,663
53
# myelinfccoupling/io.py import pandas as pd def load_inputs(edges_path, nodes_path=None) -> pd.DataFrame: """ Load edges (and optionally nodes) tables, and ensure required columns. Required edge columns after processing: - i, j (node indices) - FC (functional connectivity) ...
5980463d399af96203f50445895ae29d960f6a0adb10c7d437b82d91a16928be
Python
1,663
56
import numpy as np import pandas as pd from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, matthews_corrcoef, auc, roc_curve from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix from sklearn.mo...
9a0650b04e42c217392275428676538c07d61747c611ee996299b7212e4dbeea
Python
1,663
56
import numpy as np import pandas as pd from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, matthews_corrcoef, auc, roc_curve from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix from sklearn.mo...
d897764bed2894b401b89795904199e0bd766dfbe80ff0b85f605d6f2667e959
Python
1,663
51
from __future__ import annotations import re from loguru import logger from ._shape import Shape def compile_label_flags( *, label_flags: dict[str, list[str]] | None, ) -> dict[re.Pattern[str], list[str]]: # The patterns arrive unvalidated from ~/.labelmerc or --label-flags, so # neither a typo lik...
ff40b9a846ce1447fe6df32387643ce78506de46a893a7f1028cf93cbdc29751
Python
1,663
41
# Configuration file for the Sphinx documentation builder. # # For the full list of built-in configuration values, see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Project information ----------------------------------------------------- # https://www.sphinx-doc.org/en/master...
f3a5a1a96b2a97a5568623db31408c85a9e7bb72084c0b5c25fcaf63f220a08b
Python
1,664
62
# -*- coding: utf-8 -*- # python standard library inputs import os import sys # external inputs import numpy as np import nibabel as nb def average_layer(img_input, path_output, basename_output, mode="mean"): """Average layer. This averages data across different layers or sessions. Input arrays should ...
2ff4d06a71c9a480fa9fcf788c35921864792e828eb8ac01a621783aaa0df013
Python
1,665
58
#!/usr/bin/env python """ Reads a maf file from stdin and applies the mapping file specified by `mapping_file` to produce a sequence of integers. Then for each possible word of length `motif_len` in this integer alphabet print the number of times that word occurs in the block. usage: %prog motif_len mapping_file < m...
da3e689ae6e0e3b2238ac2b759dd7a48444ec38a8a323d10de82a14f73c06a2d
Python
1,665
45
"""Example code for plotting connectivity maps using the coherence from state/mode spectra. The spectra can be calculate with a multitaper (in the case of a state time course) or regression (in the case of a mode time course). See examples/spectra/hmm_multitaper.py for how to calculate a multitaper and examples/spect...
28fec17bbe26b5588cf60bb167ae7fd7f802d4719c24a15300f4872b87ffd99e
Python
1,666
55
from functools import partial import numpy as np from scipy import stats as stats import mne from mne.stats import permutation_cluster_test from scipy.io import loadmat from scipy.io import savemat data = loadmat('pac.mat') mask = loadmat('mask.mat') mask = mask['mask'] sigma=1e-3 #print(mask.shape) data_AD=data['pac...
cb8c9b7f99d9c1204bf5078a442e047dac593c8deafb15fdf2af0217ec810ed3
Python
1,666
52
import os import re from contextlib import redirect_stdout import io from sklearn.ensemble import RandomForestClassifier from xgboost import XGBClassifier import pickle from pstimutils import PertStimDataSimple from perturbation1 import * datasets = [] for filename in os.listdir(f'{os.getcwd()}/data'): ...
0253f1fe2b2d5f08e5e9675c500766b6e9a098ecd161cc95ebe2e9881c997780
Python
1,667
33
""" Author :Fan wang Time :2022. 9.8 """ # 1. Read the event.tsv file input_path = r'F:\HI-EEG_BIDS\sub-01\ses-01\eeg\sub-01_ses-01_task-SV-HI_events.tsv' # Replace with the actual path sub-01_ses-02_task-SV-HI_events.tsv' with open(input_path, "r", encoding="utf-8") as f: lines = f.readlines() # 2. Par...
5abc09e51dbc4b033005450b0aa6b37ba44d0bf4882e1fe98cc4b46af1fd0e62
Python
1,667
67
## ----- OS ----- ## import io import os import time import psutil import random from natsort import os_sorted, natsorted ## ----- MATH / STATS ----- ## import cv2 import heapq import mat73 import scipy.io import numpy as np from copy import deepcopy from itertools import combinations from collections import default...
6b6ad4ebd5eb5ccc5901a73e5c98df6b23f7de271853c71a474c4dd609a677e8
Python
1,668
33
#! /usr/bin/env python """Generate an area weighted 2D histogram of a [aor pf features] feature from a single mesh from a single segmentation Useful to get a sense of how your configuration for meshing and quantification looks. Also nice for responding to reviewer requests! Usage: python single_file_histogram.py input...
82456a15781f42ef012e0de058bb0e73cab53c345f599014d0826153771f9e9a
Python
1,668
56
# %% ### import modules from pathlib import Path import pandas as pd # %% read results table results_dir = Path(__file__).resolve().parents[1] / "results" df = pd.read_excel(results_dir / "cs_summary.xlsx") # %% # Define the new column names metrics = ["pad_brainageR", "pad_DeepBrainNet", "pad_brainage", "pad_enigma"...
c3eefdb690a117e94046242f92e3569960b90dd6d8a7db18585d8ce1e2df5ab9
Python
1,669
63
import torch.utils.data as data_utils import torch from PIL import Image import jpeg4py as jpeg import numpy as np import random import glob import os import math def seed_torch(seed=0): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) # np.random.seed(seed) torch.manual_seed(seed) torch...
d5c2677cf07683c94835190dbe2b068203381f8cc0f869a5b7948805116417df
Python
1,669
58
import torch from ogb.utils.features import get_atom_feature_dims, get_bond_feature_dims full_atom_feature_dims = get_atom_feature_dims() full_bond_feature_dims = get_bond_feature_dims() class AtomEncoder(torch.nn.Module): def __init__(self, emb_dim): super(AtomEncoder, self).__init__() ...
fc3c51a5caf1eb87c6393bc8b27260db5b6f76606f816d319a5882771354b49b
Python
1,669
56
"""Nottingham MEGUK: Fix structural MRI files. The sform header in the publicly available MEGUK data is incompatible with RHINO, we create a copy and fix the MRI files in this script. """ from os import makedirs from glob import glob from pathlib import Path from shutil import copyfile import numpy as np import niba...
f7d3ae202b8d58c76229d513df094ad938a104be3c86fe2bf56fb899aa3cf053
Python
1,671
52
# Generated by Django 4.2.26 on 2026-05-04 14:43 from django.db import migrations, models def initialize_chunk_type_for_audio_tasks(apps, schema_editor): Data = apps.get_model("engine", "Data") Data.objects.filter( task__media_type="audio", compressed_chunk_type="", original_chunk_type="" ).upda...
a6775aa3e8c94726677af7bd4beb3349c9225740be2ec8ffc509c3d45fdb69eb
Python
1,672
55
""" test_consolidate.py ------------------------------- Tests for the `consolidate.py` module """ import unittest import os import sys import shutil import utils # Include the parent directory in the PYTHONPATH for relative imports sys.path.append('..') import consolidate TEST_OUTPUT_PATH = 'output' TEST_DATA_FILE...
b1697ef44b2f4fe3846920c03adbe37f9f2f12d35af95c1e27e24ab4716dd173
Python
1,672
54
import os from skimage.metrics import structural_similarity as ssim from skimage import io def calculate_ssim(image1_path, image2_path): # 读取图像 image1 = io.imread(image1_path, as_gray=True) image2 = io.imread(image2_path, as_gray=True) # 计算结构化相似性指数 (SSIM) similarity = ssim(image1, image2) re...
b483607223003e8fd6c49a55eb453792aa63f416f244f6abe2a0be78d2695e99
Python
1,672
45
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import tempfile from scilpy import SCILPY_HOME from scilpy.io.fetcher import get_testing_files_dict, fetch_data # If they already exist, this only takes 5 seconds (check md5sum) fetch_data(get_testing_files_dict(), keys=['tractometry.zip']) tmp_dir = tempfile...
0f7cc6a986f35910e8ec956ee1b4562199d292831e81f02b4eac1a215aa4c834
Python
1,673
55
# -*- coding: utf-8 -*- # external inputs import numpy as np def apply_affine_chunked(aff, pts, chunk_size=10000): """Apply an affine matrix to points in chunks. This function is a copy of the routine `apply_affine` from the `affines` module of the `nibabel` package. The only difference is that this...
14caa61d0d2fc7a4099250b81176b255bffd6783275122a18e9f2bf7863eb690
Python
1,673
82
import numpy as np import zarr from numcodecs import Blosc from tqdm import trange import os # ====================== # CONFIG # ====================== path = "/media/sophie/Expansion1/UCL/datatest/videos/2screens/30/" npy_i = os.path.join(path, "dwt_videodata2_i.npy") npy_r = os.path.join(path, "dwt_videodata2_r.np...
467abb1d4a42b3cad9b291b5b99f2c3f76b0fa5043c6ef9e53628173bcb70c8b
Python
1,673
63
#!/usr/bin/env python # -*- coding: utf-8 -*- """The setup script.""" from setuptools import setup, find_packages with open('README.md') as readme_file: readme = readme_file.read() with open('HISTORY.rst') as history_file: history = history_file.read() requirements = [ 'setuptools', 'kipoiseq', ...
4c3c86ebb9bfe0b38da8e1b5e3aa0c07209d3713a2b025212bb01eb29a2e36be
Python
1,673
38
#!/usr/bin/env python3 # Author: Francois Aguet import pandas as pd import numpy as np import argparse import os parser = argparse.ArgumentParser(description='Combine covariates into a single matrix') parser.add_argument('expression_covariates', help='') parser.add_argument('prefix', help='') parser.add_argument('--ge...
68099f5fa2fc67e35cb4fe4441957f368fdb8b443442c19888c3cb5d2ccc0601
Python
1,673
55
from pathlib import Path from typing import Optional import click import numpy as np from simple_mri import SimpleMRI, assert_same_space, load_mri, save_mri def concentration_from_T1(T1: np.ndarray, T1_0: np.ndarray, r1: float) -> np.ndarray: C = 1 / r1 * (1 / T1 - 1 / T1_0) return C def concentration_from...
7c5c45a9f12eb709509cc091b588db849f5e8030f20d1b402627565b7f589e19
Python
1,673
73
# -*- coding: utf-8 -*- """File name utilities.""" import os import re import numpy as np __all__ = ["get_filename", "natsort"] def get_filename(file_in): """This function gets path, file name and file extension for an input filename. The loop checks for some given extension names. Otherwise it stops after...
ae632f588d9b7c0a9de9f327e29d02ed155db9fe6aab966062c1a7d181b68ef1
Python
1,673
55
from starter_code.utils import load_segmentation import numpy as np import nibabel as nib def evaluate(case_id, predictions): # Handle case of softmax output if len(predictions.shape) == 4: predictions = np.argmax(predictions, axis=-1) # Check predictions for type and dimensions if not isins...
b366c61df4a7c2ea62692c74ff7433fcaa87fd175e2a5e9f60e2da629a594552
Python
1,673
54
import unittest import logging from batchglm.api.models.numpy.glm_nb import Simulator import diffxpy.api as de class TestEnrich(unittest.TestCase): def test_for_fatal(self): """ """ logging.getLogger("tensorflow").setLevel(logging.ERROR) logging.getLogger("batchglm").setLevel(log...
0d965cfd216a15a6fafd9c5caf27bac73a8e1375d0f9bedc1639e014952535ad
Python
1,674
47
"""Tests for mrc2xyz.mrc_to_xyz (mrcfile/numpy/pandas; no pymeshlab).""" import os import tempfile import numpy as np import mrcfile import pandas as pd from surface_morphometrics import mrc2xyz def _write_labeled_mrc(path, voxel_size=10.0): # (z, y, x) volume; label 2 at three known voxels, label 1 elsewhere-i...
421dc605eb221a0e41a16ffe25499be24be929d14efa3a671d634f7709fb1353
Python
1,674
70
import re import os import spacy import zipfile #nlp = spacy.load('en_core_web_lg') def count_urls(tweets): total = len(tweets) unique =[] for text in tweets: urls = re.findall(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', text) unique += urls count...
7ce749bfd09c2006ccc05c1e9e8ef86b53065cbd91a95e04eb21b277f3228304
Python
1,674
67
import numpy as np from impedancefitter.particle_suspension import particle_bh_model, particle_model from impedancefitter.single_shell import single_shell_bh_model, single_shell_model omega = 2.0 * np.pi * np.logspace(0, 12, num=30) c0 = 1.0 kmed = 0.1 emed = 80 p = 0.1 Rc = 5e-6 # for single_shell_model dm = 0....
e1b3e98c076b57178ef9c0b43633dd7ea378e5343c55b10c386305ba78b37faf
Python
1,674
47
"""Background worker for the statistics and machine-learning step. Separate from :class:`~meanap.gui.pipeline_worker.PipelineWorker` because it runs something else entirely — :func:`meanap.stats.run.run_stats` against a finished run rather than the pipeline against raw recordings — and reports a different outcome (a r...
201d8fc3e0f80adf6ff104af04f8660fbc8f23c292bc91762167369ab083d605
Python
1,675
47
import json from copy import deepcopy from pathlib import Path from eir.experiment_io.input_object_io_modules.input_io_utils import ( load_input_config_from_yaml, ) from eir.setup.input_setup_modules.setup_sequence import ( ComputedSequenceInputInfo, set_up_computed_sequence_input, ) from eir.setup.schemas...
81c59c52fe3a5b46d9066f69b94afb1a93eb7736fe3d6943f5ba70a811e703ec
Python
1,675
54
import warnings from typing import Any, List import torch from torch import Tensor def get_embeddings( model: torch.nn.Module, *args: Any, **kwargs: Any, ) -> List[Tensor]: """Returns the output embeddings of all :class:`~torch_geometric.nn.conv.MessagePassing` layers in :obj:`model`. In...
b60063682a990e80bf3d152e82a0aa945352cdb197cef292d2a4ccca0f626ac7
Python
1,675
39
import numpy as np from pytest import approx from brainscore_core.supported_data_standards.brainio.assemblies import BehavioralAssembly from brainscore_vision import load_metric def test_score(): assembly = _make_data() metric = load_metric('error_consistency') score = metric(assembly.sel(subject='A'), a...
f513623118bdcf14fd6a7a857355540f2a13c3495a1d085d8b9bb719455f6bbe
Python
1,675
57
import numpy as np import pandas as pd from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, matthews_corrcoef, auc, roc_curve from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix from sklearn.mo...
2c8ad43c209dd72bccfc64890edf660dbcefd2fed085b1c15d336095e2a2291c
Python
1,676
52
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import tempfile import nibabel as nib import numpy as np import pytest from _pytest.outcomes import Skipped from scilpy import SCILPY_HOME from scilpy.io.fetcher import fetch_data, get_testing_files_dict try: tensorflow = pytest.importorskip("tensorflow")...
765d3ba1946397ce96c5c212732ca4f91f7e867f7aacc70a8cd511670ef74e87
Python
1,676
46
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import tempfile from scilpy import SCILPY_HOME from scilpy.io.fetcher import fetch_data, get_testing_files_dict # If they already exist, this only takes 5 seconds (check md5sum) fetch_data(get_testing_files_dict(), keys=['connectivity.zip']) tmp_dir = tempfile...
54a4ddabc0abcbf8beaeae4fefe0f055eb12b171d9774173586f50cfdf59e0c6
Python
1,677
44
import torch class Logger(object): def __init__(self, runs, info=None): self.info = info self.results = [[] for _ in range(runs)] def add_result(self, run, result): assert len(result) == 3 assert run >= 0 and run < len(self.results) self.results[run].append(result) ...
00ce185bc64bd09e3610aa2183a5bfeb871c0fc45bf761e5f5e69d28057cb7c7
Python
1,679
48
#!/usr/bin/python # ## @file # # Add the storm-control directory that this module is located in to # sys.path, remove any default storm-control directory (if it exists). # # Hazen 05/14 # import os import sys sc_directory = os.path.abspath(__file__) for i in range(3): sc_directory = os.path.split(sc_directory)[0]...
9ef81fb4f5eb736a1e6b86aa3923ea2722a84fd90f0bed4e514ccd97df78e665
Python
1,679
52
import pytest from qtpy import PYQT5, PYQT6, PYQT_VERSION, PYSIDE6 from tests.utils import using_conda @pytest.mark.skipif( PYQT6 and int(PYQT_VERSION.split(".")[1]) < 9, reason="QtStateMachine has been added to PyQt6 in version 6.9", ) @pytest.mark.skipif( PYSIDE6 and using_conda(), reason="Not avai...
a952b59f13c91dfbbb8f77f103635101c3f482ca641bf7af404c07793383eb6a
Python
1,680
43
# Copyright (c) 2026 Rohit Jena. All rights reserved. # # This file is part of FireANTs, distributed under the terms of # the FireANTs License version 1.0. A copy of the license can be found # in the LICENSE file at the root of this repository. # # IMPORTANT: This code is part of FireANTs and its use, reproduction, or...
c8e9849a631d2762c0fa604ff50506795ced4ade0cafacb793ee32cb134828c1
Python
1,680
43
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import tempfile from scilpy import SCILPY_HOME from scilpy.io.fetcher import fetch_data, get_testing_files_dict # If they already exist, this only takes 5 seconds (check md5sum) fetch_data(get_testing_files_dict(), keys=['bst.zip']) tmp_dir = tempfile.Temporar...
d8b01d0d008998f284c83afbc3542801b98c698634ab4d267f22c0623a50f8d2
Python
1,680
40
"""Tests for the pure parts of sample_density (numpy/scipy/mrcfile; no graph-tool).""" import os import tempfile import numpy as np import mrcfile from surface_morphometrics import sample_density as sd def test_interpolate_samples_along_normals(): # Volume whose value equals its first-axis index: data[i,j,k] = ...
b2af7d252b26ab71eb49bf0d23cb6b8ce334fb4c8c94009b0082462836325599
Python
1,681
48
import numpy as np import torch import torchio from torchio.transforms import Transform class AverageSignalsOfEqualXvals(Transform): def __init__(self, **kwargs): super().__init__(**kwargs) def apply_transform(self, subject): """ normalize signals Args: signals: ...
2e99ae2d9da2221b97b7fa3acff2a06fa8991eb11a509436a6598e5909be3d07
Python
1,682
45
# -*- coding: utf-8 -*- from dipy.io.stateful_tractogram import Space, Origin import numpy as np from scilpy.tracking.seed import SeedGenerator def test_seed_generation(): mask = np.zeros((5, 5, 5)) # Two seeds: mask[1, 1, 1] = 1 mask[4, 3, 2] = 1 # With n_repeats: it is our role to get seeds ...
7ceedca5999320e57fc6ccfb1dded8041ad85ce7e76f19647ff1458fdedbb2b0
Python
1,682
46
# This file is part of Mooney computational modeling project. # # Mooney computational modeling project 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, either version 3 of the License, or # (at your option) an...
abf31cd8acfd67bbff4028c6412d41c241e393e7523dd1d4baecf15b06e09978
Python
1,682
66
import argparse from datetime import datetime from deepreg.train import train name = "unpaired_ct_abdomen" # parser is used to simplify testing # please run the script with --full flag to ensure non-testing mode # for instance: # python script.py --full parser = argparse.ArgumentParser() parser.add_argument( "--...
e7f9aaff7b43cb0a783dfdec45e9a5c8b2743a0ec6d122dd60bde2c0dd16313b
Python
1,682
49
# -*- coding: utf-8 -*- import os import tempfile import nibabel as nib import numpy as np from scilpy.tests.arrays import fodf_3x3_order8_descoteaux07 def test_help_option(script_runner): ret = script_runner.run(['scil_fodf_threshold_by_amplitude', '--help']) assert ret.success def test_execution(script...
2693ef6c5e19ab98439cbd7a26cdf4f61e83f8b0005af1b9c41c87e929ffa6dc
Python
1,683
45
"""Use the benedict package to locate yaml files that are easy to translate to dictionaries in folders. Saving is handled by info inside the dicts and entries can be set recursively""" import os from benedict import benedict def handle_folder_dict(func): def wrapper(folder_dict, *args, **kwargs): if not ...
2b0de113269135f3d26cf90a50955eca5307b9c99eb6413e8fa07cc4ceff63d3
Python
1,685
51
import numpy as np from .normalizer_base import Normalizer from numpy.typing import NDArray class PercentileNormalizer(Normalizer): """ Normalizer subclass for percentile-based image normalization. """ def __init__( self, lower_percentile: float = 0.0, upper_percentile: float ...
4549d8495839b043869695f48ca5cb835ba5ef44b41a7a37033030f9abf13d41
Python
1,685
87
""" Create a mesh with multiple surfaces """ import SVMTK as svm import numpy as np from pathlib import Path if __name__ == "__main__": print("Start ",__file__) surf = svm.Surface(); outdir = Path("results") outdir.mkdir(exist_ok=True) sphere1 = svm.Surface() sphere2 = svm.Surface() spher...
095fd0529b9f3aab4108a173925ff4e25a56a7efb48fb87784e43dc5cd1ba7ce
Python
1,686
47
from brainscore_vision.model_helpers.check_submission import check_models import functools from brainscore_vision.model_helpers.activations.pytorch import PytorchWrapper from brainscore_vision.model_helpers.activations.pytorch import load_preprocess_images try: from .load_standalone_model import load_model except ...
4c195eada66ec44b57fd17fdcebf607b6cc1afc66ad5aaef1b1adacafb6c582e
Python
1,686
54
# Generated by Django 4.2.18 on 2025-02-10 11:29 import django.db.models.deletion from django.db import migrations, models def init_consensus_settings_in_existing_consensus_tasks(apps, schema_editor): Task = apps.get_model("engine", "Task") ConsensusSettings = apps.get_model("consensus", "ConsensusSettings")...
63114ec536b03d1ce635753a1e2eaecabda8fd7b5e8d12abda48264be87fedf9
Python
1,686
45
#@UIService uiService from ij import IJ, ImagePlus from ij.gui import Overlay, Roi from ij.plugin import ImagesToStack, Straightener """ This script straightens the pixels associated with Sholl sampling shells, so that the signal sampled during Sholl Analysis can be measured in a more straightforward way. For details,...
a0f8ff72eaa9e9b972d95de2c4b7841b055d2d949d52bdcf00a4b1e436dac5c5
Python
1,687
47
from brainscore_vision.model_helpers.check_submission import check_models import functools from brainscore_vision.model_helpers.activations.pytorch import PytorchWrapper from brainscore_vision.model_helpers.activations.pytorch import load_preprocess_images try: from .load_standalone_model import load_model except ...
c72877d7681b44e7775cfd3da3455817bef63fcc411d3b69582aa0d8adea6657
Python
1,687
46
from brainscore_vision.model_helpers.check_submission import check_models import functools import os import torchvision.models from brainscore_vision.model_helpers.activations.pytorch import PytorchWrapper from brainscore_vision.model_helpers.activations.pytorch import load_preprocess_images from pathlib import Path fr...
cc462b96658b71c49fe3c8f3993e17a61fe06648f68e76aa6e199ac42468fcd6
Python
1,687
39
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'button_editor.ui' # # Created by: PyQt5 UI code generator 5.7 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Dialog(object): def setupUi(self, Dialog): Dialog.setObj...
eb16490337bd9ec6935cb411d309cf3008c617615eb3617ed2562be271c13ca4
Python
1,687
47
import pandas as pd from pysnptools.snpreader import Bed from pysnptools.snpreader import Pheno from fastlmm.association import single_snp import argparse def main(): # Set up argument parser parser = argparse.ArgumentParser(description="Perform MLMA using FaST-LMM with PLINK SNP data.") parser.add_argume...
f3ef7e25a70fc4fd8e82803a928dfe0624eb9962d980e5120b86ec5d4dfcbd7b
Python
1,687
61
# Copyright (c) DP Technology. # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from torch.utils.data.dataloader import default_collate from . import UnicoreDataset class BaseWrapperDatase...
030cf7566388054988c894e4a4090d5b369343ef5d174d98288718ec1f10baf2
Python
1,688
52
from __future__ import annotations from PySide6 import QtCore from PySide6 import QtWidgets class IntegerSlider(QtWidgets.QWidget): value_changed = QtCore.Signal(int) def __init__( self, *, minimum: int, maximum: int, value: int, parent: QtWidgets.QWidget | No...
1461a78ed70cdc28a5455837a090b9ad73effa80b31b12d206a719b64ae08ffa
Python
1,688
64
"""Predict a continuous value using neuroimaging features. Note, this script doesn't require osl-dynamics, it uses scikit-learn to train a machine learning model. This script should achieve an R2 value of ~0.52. """ import numpy as np from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardSc...
b674024e64b0a7f5e0652f02f4cb877a76ba0f78d0d1d7143b5d9f81478634f6
Python
1,688
43
# -*- coding: utf-8 -*- import numpy as np from scilpy.connectivity.connectivity import \ compute_triu_connectivity_from_labels def test_compute_triu_connectivity_from_labels(): labels = np.asarray([[3, 4, 5, 6], [7, 8, 9, 10], [11, 12, 13, 14]]) labels =...
c7a3777fead4186df85b1e1c4cb5b1159be687ee9e93e81cd01d50b569f9c9e9
Python
1,688
44
import torch from torch import Tensor from .layer_norm import LayerNorm import torch.nn as nn import torch.nn.functional as F from typing import List, Optional, Tuple class UpSampleLayer3D(nn.Module): def __init__(self, in_channels: int, out_channels: int, method='nearest', ...
d1989eaea37c5e5c12273157f7a177f960848b49b0d4f9423da478d078cac88c
Python
1,689
55
import copy from distances import LpDistance from reducers import DoNothingReducer, MeanReducer, MultipleReducers from utils.module_with_records import ModuleWithRecords class ModuleWithRecordsAndReducer(ModuleWithRecords): def __init__(self, reducer=None, **kwargs): super().__init__(**kwargs) se...
e1c53b6efa57a5c2101db768e3119304938358e08ed55958229106cf7abef692
Python
1,690
72
import re import datetime import calendar def get_user_id(user): return user['id'] def get_longevity(user): create = user['created_at'].split(' ') month = list(calendar.month_abbr).index(create[1]) day = int(create[2]) year = int(create[5]) create_time = datetime.datetime(year, month, day) ...
e17b85c03092763e7997e7b2cf864c2913e40de2b6c9edd4d2bc334239f35ec0
Python
1,691
34
from model.utils import clustering import scanpy as sc import numpy as np from scipy.spatial.distance import cdist def location(option_list,source_data,target_data,tool,radius=0,random_seed=0,refinement=False): n_clusters = option_list['get_location']['n_clusters'] start = option_list['get_location']['start']...
f52debc04f480da7c1601044ec66a75e73a69e448fe4910656d7988c734012f2
Python
1,691
39
import numpy as np from sklearn.neighbors import kneighbors_graph, radius_neighbors_graph def Cal_Spatial_Net(adata, radius=None, n_neighbors=None, model='KNN', verbose=True, include_self=False): """ Construct spatial neighbor graph from spatial coordinates. Parameters ---------- adata : anndata.A...
4739776212883c044c9c499a6320edddd7a3cb6c847dd39880bb5894096a1f87
Python
1,692
70
from math import log from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer def ShannonEntropyAndNomalize(name): entropy = [] upper_list = [] lower_list = [] for s in name: word = {} upper_num = 0 lower_num = 0 ...
77aef0063737b8600862cad9216b964f53358bc9571693b34d56427de2281af3
Python
1,692
92
#! /usr/bin/env python # aponteeduardo@gmail.com # copyright (C) 2016 '''' Graphical tools ''' from copy import deepcopy import numpy as np from scipy.integrate import cumtrapz from scipy import stats from . import containers def generalized_fits_factory(trials): class GeneralizedFits(containers.TimeSeri...
fc1c567ad9bfa1eebfdafb93f65143e64b30aa155b32c24e36d6ea3afc910a18
Python
1,692
66
#! /usr/bin/env python # aponteeduardo@gmail.com # copyright (C) 2016 '''' Setup for sooner module. ''' import glob import platform from setuptools import setup, Extension, find_packages from Cython.Distutils import build_ext import numpy as np # Define the compilation flags extra_args = { 'extra_compile_ar...
3ddf6d26b54ce07f92291cf4a21a997a0a2a209711b31357759e2813f9d8db26
Python
1,693
51
# File: /scripts/preprocessing/clean_and_normalize.py """Data cleaning and normalization pipeline. Steps performed: 1. Load raw Excel file from ../../data/raw/ 2. Select final session (Sesja == 15) 3. Compute derived variables (RMS_pre/post, MF_pre/post, Delta_EMG, EEG_SUM, SILA_SUM) 4. Z‑score normalization within g...
6433a3a3dce4dcc0ae8362a8572d2f593518fca2b9d87bfc035608ade51531b9
Python
1,693
38
from brainscore_core.supported_data_standards.brainio.assemblies import BehavioralAssembly from brainscore_vision import data_registry, stimulus_set_registry, load_stimulus_set from brainscore_core.supported_data_standards.brainio.s3 import load_assembly_from_s3, load_stimulus_set_from_s3 BIBTEX = """@article{zhang20...
8d8318066d602e9f8a00024ef7058370a56261a1f54264112ee0070ed0684370
Python
1,693
51
from langchain_ollama import ChatOllama from chemgraph.models.supported_models import supported_ollama_models def load_ollama_model( model_name: str, temperature: float, base_url: str = None ) -> ChatOllama: """Load an Ollama chat model into LangChain. This function loads a local Ollama model and configu...
53ff447082cf19da03bb401b744fd8858f7e104b5a97bd6edf147185321a8ff4
Python
1,694
56
import shutil import subprocess import argparse from pathlib import Path def parse_arguments(): parser = argparse.ArgumentParser( description="Patch Arbor wheels built with scikit-build and corrected by auditwheel. Linux only." ) parser.add_argument( "path", type=dir_path, ...
f891b1c782d24dacd6227ffa047d90b5ee71c23e35daa4645bfce08145be8b99
Python
1,694
49
import sys import numpy as np import matplotlib.pyplot as plt def read_ecg_readings (input_file): data = np.genfromtxt(input_file) nlin, ncol = np.shape(data) timesteps = data[:,0] currents = data[:,1:] num_leads = ncol-1 return timesteps, currents, num_leads def plot_ecg_readings (t1, currents1, t2, current...
1c6606bac804bf24ae4c3850c2813c1564434a3fd979ac848e6f014d16611b77
Python
1,695
54
# Copyright (C) CVAT.ai Corporation # # SPDX-License-Identifier: MIT """Download a backup zip of an existing project. A backup contains the project's tasks, jobs, annotations, and settings. Pair this recipe with project_restore.py to migrate or clone a project. Steps: 1. Retrieve the project by id. 2. Download i...
93ad20aa0f74594e78ba659156f1c49795724e822c9af70fb11a43fa681fe1db
Python
1,695
56
import numpy as np import matplotlib # matplotlib.use('Qt5Agg') import matplotlib.pyplot as plt if __name__ == '__main__': Kd = 100 # muM^4 K1 = 0.5 # mM^-1 ms^-1 K2 = 0.0012 # ms^-1 K3 = 0.18 # ms^-1 K4 = 0.034 # ms^-1 # Square Pulse forcing function for Transmitter concentration def...
c8abe53431ecbbe01a8a59a1f8472c80a0a510207c6f2f67990911f910789684
Python
1,695
53
import shutil import subprocess import time from pathlib import Path import pytest @pytest.fixture(scope="module") def api_process(): file_target = "tests/test_modelling/test_streaming_modelling/setup_test_api.py" process = subprocess.Popen( [ "python", file_target, ] ...
22a2bb2d25ea1aefff8aea7290a518cbb2babdbc34ad64f54a87e70edb76674f
Python
1,696
51
import torch.nn.init as init import torch.nn as nn def apply_weight_init(module, init_name): if init_name is not None: if init_name == 'kaiming_uniform': module.apply(kaiming_uniform_init) elif init_name == 'kaiming_normal': module.apply(kaiming_normal_init) ...
23c6508e66ebbc4e8bbe6df77fadc457b96f4b7b0c8efea27b1487d309a71e60
Python
1,696
32
import os import shutil from nipype.interfaces.base import CommandLineInputSpec, File, TraitedSpec, CommandLine, BaseInterfaceInputSpec, BaseInterface from traits.api import Str, Int, Directory, Bool, Either from cvdproc.config.paths import get_package_path class EPIRegNipypeInputSpec(CommandLineInputSpec): epi =...
8fa0b3f01c2419d5cdf4a5227ae5fc9d78da69466b088539c6bf25b65ee4e71d
Python
1,696
62
import os, sys # https://stackoverflow.com/questions/8391411/how-to-block-calls-to-print # Alexander C class PrintingBlocked: """Context manager for temporarily blocking `sys.stdout`. Examples -------- >>> def test(i): >>> print(f'{i} not blocked') >>> >>> with PrintingBlocked(): ...
35196543dba3b998872019f6c9fbe3a08e2a2dae7ed8dd3ab638682c8d911e43
Python
1,697
68
import torch from torchmetrics import Metric from typing import Union, List import ecgxai.utils.exceptions as exceptions class BaseMetric(Metric): @property def batch_args(self): return [] @property def input_args(self): raise NotImplementedError() class TMW(BaseMetric): """ Tor...