sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
cd557948513f1ad55cc90873aefbc76337da88719df2e9226f4295ce44c0e629 | Python | 1,322 | 36 | from argclz.commands import parse_command_args
from .main_align_map import AlignPeakMapOptions
from .main_cache_occ import PosBinActCacheBuilder
from .main_cache_sortidx import SortIdxCacheBuilder
from .main_ev_pos import EVOptions
from .main_place_field import PlaceFieldsOptions
from .main_population_matrix import Pop... |
f83fb6ea3568d60621c09c6497a678639e91a66008a2d9489eb5e5e1b5453c8c | Python | 1,322 | 55 | # -*- coding: utf-8 -*-
# python standard library inputs
import os
# external inputs
import numpy as np
import imageio as io
def get_gif(img_file, path_output, name_output, nsteps, duration):
"""Get GIF.
Create gif movie from n input images with fading from one image to the next
image.
Parame... |
2898804a5ba5a8ff95f4436113e06b28d5a9ae67a21882a1674471e302fff59c | Python | 1,323 | 46 | #!/usr/bin/env python
import click as ck
import numpy as np
import pandas as pd
import gzip
import logging
from toolkit.utils import NAMESPACES, Ontology, get_goplus_defs
from collections import Counter
import json
import os
import torch as th
logging.basicConfig(level=logging.INFO)
@ck.command()
@ck.option(
'... |
92233e8c0a17d42647c4a7b8fba0be4d29e928d1b8074fc8cc17004cf15e9961 | Python | 1,323 | 28 | import functools
import torchvision.models
from brainscore_vision.model_helpers.activations.pytorch import PytorchWrapper
from brainscore_vision.model_helpers.activations.pytorch import load_preprocess_images
BIBTEX = """@incollection{NIPS2012_4824,
title = {ImageNet Classification with Deep Convol... |
960d1080d6ef095628126730f7a8cb127ca9cd0c07dfc9b203e9d783c80db747 | Python | 1,323 | 34 | #!/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=['bundles.zip'])
tmp_dir = tempfile.Temp... |
ee65ffb420ef62d920bb9f12c7c8064455cb1d10c3cc7b13092aa0d805c9342f | Python | 1,323 | 38 | import sys
import time
import numpy as np
import pandas as pd
import anndata
import math
from scipy.sparse import csr_matrix
from anndata import AnnData
class h5ad_dataframe:
def __init__(self):
self.h5ad_dataframe=None
self.min_x=0
self.min_y=0
def h5ad_init(self,h5ad_file_name:str,mi... |
f62c0e01ef3468e26a5e12c02ceb602d6e942114415f4eecd13f16d3109654d1 | Python | 1,323 | 28 | import functools
import torchvision.models
from brainscore_vision.model_helpers.activations.pytorch import PytorchWrapper
from brainscore_vision.model_helpers.activations.pytorch import load_preprocess_images
BIBTEX = """@incollection{NIPS2012_4824,
title = {ImageNet Classification with Deep Convol... |
334e5e2a545e8ef9ca27e81ff69665cec85f07049ce87a8e4db4a8b93f7fb865 | Python | 1,324 | 42 | import os
import torch
from connectomics.utils.system import get_args, init_devices
from connectomics.config import load_cfg, save_all_cfg
from connectomics.engine import Trainer
def main():
args = get_args()
cfg = load_cfg(args)
device = init_devices(args, cfg)
if args.local_rank == 0 or args.local... |
ad0f3c4dc76f996f55ec27eb50ff5ae0e0fad17a86225ef060cb1cd75c97b61f | Python | 1,324 | 40 | from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, roc_auc_score
import numpy as np
from pathlib import Path
import torch
import csv
import argparse
parser = argparse.ArgumentParser(description='Random seed set:')
parser.add_argument... |
baf6b489dbdac9c61df9b8b78ae9536d743ebb4407ab8a23c58d2259ffbd4efc | Python | 1,324 | 51 | # import our previous code
from wilson_cowan import step, Params
from ring import recipe
from mpi import world, group
import arbor as A
from arbor import units as U
import numpy as np
assert world.size >= 2, "Need two or more ranks"
dt_arb = 0.005 # ms
dt_nmm = 0.01 # ms
dt_com = 0.5 # ms
T = 100 # ms
if __na... |
d27c25390e8f230f5863cd873609ef5927a0ad1c0daf5051148fe39261208f66 | Python | 1,324 | 49 | # This file is part of connectome-manipulator.
#
# SPDX-License-Identifier: Apache-2.0
# Copyright (c) 2024 Blue Brain Project/EPFL
from contextlib import redirect_stdout
import io
import os
import re
import logging
import pytest
from mock import patch
from utils import setup_tempdir
import connectome_manipulator.lo... |
dbb868d98ed4c2daf8a57080a90a3ff15347f764acecef074978f081f64356d0 | Python | 1,324 | 57 | """Public core API for metaprivBIDS."""
from .functions import (
CigResult,
PseudonymizationResult,
SudaResult,
add_gaussian_noise,
add_laplacian_noise,
add_noise,
bin_numeric_values,
calculate_k_anonymity,
calculate_k_combined,
calculate_k_global,
calculate_l_diversity,
... |
f0f3abda52f3982bc41137f9367789987ffa01a31d1565beb91f1ead730347e6 | Python | 1,324 | 39 | #!/usr/bin/env python3
import os
import logging
import subprocess
class BowtieSuite(object):
def __init__(self,bt2_path=''):
curr_path = os.path.realpath(bt2_path)
self.bowtie_bin = os.path.join(curr_path,'bowtie2')
self.bowtie_build = os.path.join(curr_path,'bowtie2-buil... |
1d80f99c9b13383dc31aa08f52ed8bdec5f85633454f26c76e3c27b52116062e | Python | 1,325 | 51 | """ Summary utilities
Hacked together by / Copyright 2020 Ross Wightman
"""
import csv
import os
from collections import OrderedDict
try:
import wandb
except ImportError:
pass
def get_outdir(path, *paths, inc=False):
outdir = os.path.join(path, *paths)
if not os.path.exists(outdir):
os.maked... |
300ba8fd88b267b1f80600c094281599306daf519a3ce59614ead26bd5de315a | Python | 1,325 | 48 | import dask.array as da
from distributed import Client, LocalCluster
from sklearn.datasets import make_regression
from sklearn.metrics import mean_squared_error
import lightgbm as lgb
if __name__ == "__main__":
print("loading data")
X, y = make_regression(n_samples=1000, n_features=50)
print("initializi... |
9818aef2f8bf9b409ef393a4875abd6f1fcfb4cae590465914584ad0ce540338 | Python | 1,326 | 41 | from dataclasses import dataclass
from typing import Literal
SurvivalLossNames = Literal["NegativeLogLikelihood", "CoxPHLoss"]
@dataclass
class SurvivalOutputTypeConfig:
"""
Basic configuration for survival analysis output.
:param time_column:
The name of the column in the label file that contai... |
ffb6ca4ac110f1a6faa8da290d26182a07979d47c984a08ae38df5144a4bc660 | Python | 1,328 | 33 | """Data loading and preparation.
The main entry point is the :py:class:`Data` class, which handles loading
time series data from various formats (NumPy, MATLAB, FIF) and preparing
it for model training.
Modules
-------
- :py:mod:`~osl_dynamics.data.base` — :py:class:`Data` class for loading
and preparing data, and ... |
bf65fb085df901d334804f746fdfbe0fc9ce4e7bb5e06348e7db00588bd42516 | Python | 1,329 | 39 | from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import List
import pandas as pd
@dataclass(frozen=True)
class SubjectFiles:
subject_id: str
so_coupling: Path
rem_fragments: Path
aperiodic_slope: Path
def discover_subjects(input_dir: str | Pat... |
3290a759b609017cea24024f0a55c052c74cb37a8596b505531c7676416554ce | Python | 1,330 | 33 | _base_ = [
'RepLKNet_upernet.py',
'../_base_/datasets/ade20k.py', '../_base_/default_runtime.py',
'../_base_/schedules/schedule_160k.py'
]
# compared to the default schedule, we used a smaller batchsize/GPU, more GPUs hence fewer training iters
# please adjust the batchsize and number of iterations acc... |
5123f08fdc1baa54d5b06fd422a1a14848d500adbfa550e06fcc6864e16794c6 | Python | 1,330 | 47 | # -----------------------------------------------------------------------------
# Copyright © 2019- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtChart classes and... |
5af9bcc41ccfc88d9fb5143959dfb43f59ff0c69d9c214f73de4c44daae39135 | Python | 1,330 | 64 | """Plot results.
"""
#%% Run ID and output directories
import os
from sys import argv
# We get the run ID from the command line arguments
if len(argv) != 2:
print("Please pass a run id, e.g. python 5_plot_results.py 1")
exit()
id = int(argv[1])
# Check results directory exists
results_dir = f"results/run{i... |
5d8765417dd4ce778eaae46fc8490c7198a846d32818a027be328dcf47a63d47 | Python | 1,330 | 72 | # -*- coding: utf-8 -*-
"""Test mesh utilities."""
import os
import pytest
from fmri_tools.surface.mesh import Mesh
# file name of sphere in data folder
FILE_SPHERE = os.path.join(os.path.dirname(os.path.dirname(__file__)), "data", "sphere")
def test_n_neighbors():
"""Assert number of vertex neighbors."""
... |
1b072864b11e66b98eee161d60e7fc6417f60344b0448b2e46da4b9ba3fca63d | Python | 1,332 | 28 | import functools
import torchvision.models
from brainscore_vision.model_helpers.activations.pytorch import PytorchWrapper
from brainscore_vision.model_helpers.activations.pytorch import load_preprocess_images
BIBTEX = """@incollection{NIPS2012_4824,
title = {ImageNet Classification with Deep Convol... |
47d28e466317396ddbbfd6293b237b322bd51c1833e31168eeab0b7bfd0a2fcd | Python | 1,332 | 28 | import functools
import torchvision.models
from brainscore_vision.model_helpers.activations.pytorch import PytorchWrapper
from brainscore_vision.model_helpers.activations.pytorch import load_preprocess_images
BIBTEX = """@incollection{NIPS2012_4824,
title = {ImageNet Classification with Deep Convol... |
b3d0c23b559efb19aa8d6573073bdb1cf6e24644ef7c31107cec958585a8589b | Python | 1,332 | 28 | import functools
import torchvision.models
from brainscore_vision.model_helpers.activations.pytorch import PytorchWrapper
from brainscore_vision.model_helpers.activations.pytorch import load_preprocess_images
BIBTEX = """@incollection{NIPS2012_4824,
title = {ImageNet Classification with Deep Convol... |
d0bfbc942ff81847d6a33da74774cd2b889938a5df4fb5e40311d9bfd44f42c9 | Python | 1,332 | 37 | import numba
import numpy as np
@numba.njit
def random_dropout(cell_expr,max_rate):
non_zero_mask = np.where(cell_expr!=0)[0]
zero_mask = np.random.choice(non_zero_mask,int(len(non_zero_mask)*np.float32(np.random.uniform(0,max_rate))))
cell_expr[zero_mask] = 0
return cell_expr
@numba.njit
def random_s... |
d77bb23b71ff3ad9eee98fe7a6013b6daa2f737e3822f92492d05b795f481fc7 | Python | 1,332 | 50 | from ._core import config as _config
def load(config_path: str = None):
"""
Load configuration from a YAML file or return default configuration.
If a path to a YAML configuration file is provided, the configuration is
loaded from that file. Otherwise, a default configuration is used.
Parameters
... |
49a09c5232cac916b9cc5080c6fda94623ba26090052bda5b1dd85e2896a30f8 | Python | 1,333 | 28 | import functools
import torchvision.models
from brainscore_vision.model_helpers.activations.pytorch import PytorchWrapper
from brainscore_vision.model_helpers.activations.pytorch import load_preprocess_images
BIBTEX = """@incollection{NIPS2012_4824,
title = {ImageNet Classification with Deep Convol... |
0ec6cd177d6f3381c2e68c29afa13d5e23a3a4a4283983cfe082cf81c2ade020 | Python | 1,334 | 28 | import functools
import torchvision.models
from brainscore_vision.model_helpers.activations.pytorch import PytorchWrapper
from brainscore_vision.model_helpers.activations.pytorch import load_preprocess_images
BIBTEX = """@incollection{NIPS2012_4824,
title = {ImageNet Classification with Deep Convol... |
8dfd269cee23d91ed3e844d28c910b3cb1067238cceea274cffc80caad7afcb3 | Python | 1,335 | 36 | import torch
from distances import DotProductSimilarity
from utils import common_functions as c_f
from utils import loss_and_miner_utils as lmu
from losses.base_metric_loss_function import BaseMetricLossFunction
class NPairsLoss(BaseMetricLossFunction):
def __init__(self, **kwargs):
super().__init__(**kw... |
7893a679f951e848d7dc129cd04b80c6b7fdb9b1bc997641a0ead7cef2f91c95 | Python | 1,336 | 34 | import numpy as np
from PIL import Image
from brainscore_vision import load_model
from brainscore_vision.model_interface import BrainModel
from .model import IDENTIFIER, LAYERS, preprocess_images
def test_preprocessing(tmp_path):
image_path = tmp_path / "solid_rgb.png"
Image.new("RGB", (360, 256), (64, 128,... |
7fe590787e152e2e479fd96b833b455024ab37f1489a38506ba0711737180b7f | Python | 1,338 | 41 | import warnings
from typing import Any, Callable, Optional, Union
import torch
import torch_geometric.typing
def is_compiling() -> bool:
r"""Returns :obj:`True` in case :pytorch:`PyTorch` is compiling via
:meth:`torch.compile`.
"""
if torch_geometric.typing.WITH_PT23:
return torch.compiler.i... |
88e3e3c357afc5115aec83b6b98db87d035d311391a4ca5cc9cd2b096109f023 | Python | 1,338 | 50 | import os
import shutil
import pytest
import numpy as np
@pytest.fixture(scope='function')
def test_data():
def prepare_data(shape=(3, 3), pos1=0, pos2=0):
data = np.reshape(np.arange(np.product(shape)), shape).astype("float")
data[pos1, pos2] = np.nan
return data
return prepare_data
... |
ae7f27cb66da59c3912c8e42e9a4026adcc13868f93f00fbf636a9629d3d5266 | Python | 1,338 | 37 | #!/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=['tractometry.zip'])
tmp_dir = tempfile.... |
f7d2de7170dd85bbb1c093320b4a4d08cfe0ed30b6a6f37446463a1d141d663c | Python | 1,338 | 59 | """ Creates a cone,cylinder,cube and sphere surface mesh """
import SVMTK as svm
from pathlib import Path
if __name__ == "__main__":
print("Start ",__file__)
outdir = Path("results")
outdir.mkdir(exist_ok=True)
surf = svm.Surface()
# Edge length of surface mesh
edge_length = 0.2
### Crea... |
b875be59910c0f278d08f6b30e6d11a09b27a1bfa91b3ad46d1c77f6688e6eab | Python | 1,339 | 39 | #!/usr/bin/env python
"""
HAL module for emulating an illumination filter wheel.
Hazen 04/17
"""
import storm_control.hal4000.halLib.halMessage as halMessage
import storm_control.sc_hardware.baseClasses.amplitudeModule as amplitudeModule
class NoneFilterWheelFunctionality(amplitudeModule.AmplitudeFunctionality):
... |
6827d38e476c704145eabfb2884c9e18a898d2fa17423bc50deb1e93eaab3c02 | Python | 1,340 | 57 | import sys
import os
import glob
import gzip
from optparse import OptionParser
USAGE = """
select-50.py --kdir <dir of kmer fasta files> --out <out file name>
counts kmer mapping positions
"""
###############################################################################
parser = OptionParser(USAGE)
parser.add_... |
0354130419ee23e09355a471fb606fb17cdb695bdf8fc0c2f10a3c58b8bc5607 | Python | 1,341 | 34 | import importlib
from pytorch_grad_cam import GradCAM
from pytorch_grad_cam.utils.image import show_cam_on_image
def get_detector_model(args):
model_module = importlib.import_module("builder.models.detector_models." + args.model)
model = getattr(model_module, args.model.upper())
return model
... |
7272fc8273a2eae7447aa0890bf86cd66a12b233b672f254f7e7820ab9bbbd25 | Python | 1,341 | 46 | import matplotlib.pyplot as plt
import pandas as pd
cases = 'Abel_ref2'
mmHg_to_Pa = 133.3616
cm = 1/2.54
# plot for the heart
models = 'heart_kim_lit'
nodes = ['p_LA1','p_LV1','aorta']
edges = ['R_la','R_lv_aorta']
c_nodes = ['y','b','r']
c_edges = ['b','r']
fig = plt.figure(figsize=(16*cm, 24*cm))
gs = fig.add_gr... |
98a88b36b621b4da80ed9f41a44ef5c977deee0b1f0e2886d9f14c5a2f29b420 | Python | 1,341 | 46 | # -*- coding: utf-8 -*-
"""
Created on Sat May 30 11:26:23 2020
@author: Yoshi
"""
import os
import shutil
import matplotlib.pyplot as plt
def r_histogram_creator(path,correlation_coefficients):
# Creates and changes to output directory
graph_output_path = path + "/Output/Debug/Histograms"
if os.p... |
1cafb997e9ee8c25c0c8a783870ac8cbdb0b7b4cc1cf2582af1e201774c67faf | Python | 1,342 | 32 | import logging
import os
import sys
import xarray as xr
from brainscore_core.supported_data_standards.brainio.assemblies import NeuroidAssembly
from brainscore_core.supported_data_standards.brainio.packaging import package_data_assembly
def create_xarray(savepath):
'''Packages the DataArray (stimulus set the sa... |
3d3b8c6b5df2c537b9ef4bb2b66e117932f0f498654412f476e67c87576e2238 | Python | 1,342 | 40 | import pandas as pd
import pytest
from openpyxl import Workbook
from src.audit.inventory import align_samples, require_unique, read_block
def test_alignment_uses_ids_not_row_order():
meta = pd.DataFrame({'ODCF_name': ['b', 'a'], 'condition': ['control', 'treated']})
assert align_samples(meta, ['a', 'b']).con... |
40ca8a4589e3f026e40291d003ee197f9fb1c4fb5148b40742eddb85b509250a | Python | 1,342 | 34 | import os
import nibabel as nib
from nipype.interfaces.base import (
TraitedSpec, CommandLineInputSpec, CommandLine,
File, traits, Str, Directory
)
class ChPSegInputSpec(CommandLineInputSpec):
in_t1 = File(exists=True, mandatory=True, desc='Input T1-weighted image', argstr='%s', position=0)
output_dir ... |
361a8a3ebcf988a5ae3202a9b2a6dae756df1932b18ab59fb526bf15d0a696bc | Python | 1,343 | 42 | from pathlib import Path
from typing import Optional
import pandas as pd
from brainways.project.info_classes import SliceInfo
from brainways.utils.cell_detection_importer.cell_detection_importer import (
CellDetectionImporter,
)
class BrainwaysCellDetectionsImporter(CellDetectionImporter):
def find_cell_det... |
5e6e839f5968391713e19a0c833c43edcf1fb297c7c008216a255f70fddde3fc | Python | 1,343 | 27 | """
Copyright 1999 Illinois Institute of Technology
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publis... |
81ea5f9db226f312104dbcde6ad59b6512096df8d723becb1396f44bb154ff44 | Python | 1,343 | 36 | from __future__ import absolute_import
import torch
from torch import nn
from torch.autograd import Variable
class TripletLoss(nn.Module):
def __init__(self, margin=0):
super(TripletLoss, self).__init__()
self.margin = margin
self.ranking_loss = nn.MarginRankingLoss(margin=margin)
de... |
ed7375d0ccf7995e7490007e131165b49588350a9e28300b91b9a2f022993db1 | Python | 1,343 | 38 | import pytest
from pytest import approx
from brainscore_vision import benchmark_registry, load_benchmark, load_model
class TestExist:
@pytest.mark.private_access
@pytest.mark.parametrize("identifier", [
'Hebart2023_fmri.V1-ridge',
'Hebart2023_fmri.V2-ridge',
'Hebart2023_fmri.V4-ridge'... |
58bf51e97e62a61d63966989a52e62929db56048706057191220952821b32e4e | Python | 1,344 | 42 | from pathlib import Path
import numpy as np
from eir.experiment_io.label_transformer_io import load_transformers
from eir.experiment_io.output_object_io_modules.output_io_utils import (
load_output_config_from_yaml,
)
from eir.setup.output_setup_modules.survival_output_setup import (
ComputedSurvivalOutputInf... |
856eda7da230256cdba20619cf6d1128f8cd3341015cf7d02fdbeb98c1e8e06d | Python | 1,344 | 53 | import scipy.io as sio
import numpy as np
def load_data(path, key):
d = sio.loadmat(path,struct_as_record=False)
dataset = vars(d[key][0][0])
# Data are loaded in this annoying structure where the array
# we want is at dataset[i][key][0,0], as a nested array of arrays.
# Simplify this structure (... |
5a317b1479982b81da6aa751438734add253d02d0f61643fffb6efee158a06db | Python | 1,345 | 42 | #!/usr/bin/env python
import click as ck
import numpy as np
import pandas as pd
from deepgo.utils import Ontology, NAMESPACES
from collections import defaultdict
@ck.command()
@ck.option('--data-root', '-d', default='data')
@ck.option('--in-file', '-i', help='Input file', required=True)
@ck.option('--out-file', '-o',... |
4e7ad4b1840742d6dcefa151e31eb99e492a2b83117a85c2cc9f7612d64a6506 | Python | 1,346 | 48 | import numpy as np
from nems import Model
from nems.layers import NumPy
# Picked a few numpy functions to test the general behavior, but this is not
# an exhaustive test of all possible numpy operations.
def test_numpy_ops():
x = np.arange(12).reshape(3, 4)
y = np.split(x, 3, axis=0)
split = NumPy('spli... |
5731345ad1e010c2201aec28f60313c67a96f948cee1fac93a609520287c5d7c | Python | 1,346 | 47 | '''
Takes logfile as input ant reads TR from trigger times.
Assumes keypress: 5 as trigger
'''
import re
import numpy as np
logfile = '/Volumes/extData/S1ANFUNCO/Nifti/derivatives/logFiles/sub-06_ses-001_task-stim_run-001_cbv.log'
f = open(logfile)
df = pd.read_csv(f, skiprows=2, sep='\t', lineterminator='\n',
... |
6104129a3674ff7027d25f6243ae8f4b572dba3a286c890215948bd4aba78929 | Python | 1,346 | 47 | import numpy as np
import sys
def main():
if len (sys.argv) != 3:
print ("Usage: python Py_calc_NIP_3D.py s1*.txt s2*.txt")
sys.exit (1)
global BINS
BINS = 50
PC_s1 = np.loadtxt(sys.argv[1])
PC_s2 = np.loadtxt(sys.argv[2])
PC_bound = np.concatenate((PC_s1, PC_s2))
bound_h =... |
88e456b5f8f08d5eb3627c57825b9560db6e29a86fdb3a11fcba669e85ec615e | Python | 1,347 | 57 | # Copyright (C) 2020-2022 Intel Corporation
# Copyright (C) CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT
import argparse
import logging
import sys
import urllib3.exceptions
from cvat_sdk import exceptions
from cvat_sdk.core.exceptions import AuthStoreError
from ._internal.commands_all import COMMANDS
from ._... |
aa3bd77418cbca0d80619449939c7fd998c86f4b33a6bcca3f46cc8923b42121 | Python | 1,347 | 37 | import FORCE
import numpy as np
import numpy.random as npr
import matplotlib.pyplot as plt
import os
from scipy.io import loadmat, savemat
if __name__ == '__main__':
data_types = ['control', 'APP']
ramp = [0.0]
for seed in range(30):
for r in ramp:
for d in data_types:
... |
b85eed11e544d325152a8a1c7477ef94ad8255db7574e6ee880eda1d7474b926 | Python | 1,347 | 35 | import pytest
from pytest import approx
from brainscore_vision.benchmark_helpers import check_standard_format
from brainscore_vision.benchmark_helpers.test_helper import StandardizedTests, VisualDegreesTests
from brainscore_vision.benchmarks.cadena2017.benchmark import AssemblyLoader
standardized_tests = Standardized... |
4c2f307548d57f872447c63f46bbc193c8903ef5e3132226b357228e6aa78ca8 | Python | 1,348 | 53 | """
Interpolation and smoothing for pose timeseries.
Ported from utils/processing.py (Chambers et al. 2020 pipeline).
"""
import pandas as pd
def interpolate_df(df: pd.DataFrame) -> pd.DataFrame:
"""Linearly interpolate missing x, y values (sorted by frame)."""
df = df.sort_values("frame")
df["x"] = df[... |
a7b3cb996538cbba47523d6961d19dcff7881d1338b7032246ffc699bdd6369c | Python | 1,348 | 43 | #!/usr/bin/env python
"""
QPushButton specialized to be a record button.
Hazen 4/17
"""
from PyQt5 import QtWidgets
import storm_control.hal4000.film.filmRequest as filmRequest
import storm_control.hal4000.halLib.halMessage as halMessage
class QtRecordButton(QtWidgets.QPushButton):
def __init__(self, parent =... |
eb7b2f46eb479985a22dcb95ccff778021d3fff2d28a739d688af7177b70bdff | Python | 1,348 | 36 | from .base_tester import BaseTester
class GlobalEmbeddingSpaceTester(BaseTester):
def do_knn_and_accuracies(
self, accuracies, embeddings_and_labels, query_split_name, reference_split_names
):
(
query_embeddings,
query_labels,
reference_embeddings,
... |
74bf6d6ac5cd33ec7634e311267f24eb3e02796e3a9d1ce86b8f48cc6e7cc28c | Python | 1,349 | 36 | from typing import Optional
from torch import Tensor
import torch_geometric.typing
if torch_geometric.typing.WITH_TORCH_CLUSTER:
from torch_cluster import graclus_cluster
else:
graclus_cluster = None
def graclus(edge_index: Tensor, weight: Optional[Tensor] = None,
num_nodes: Optional[int] = Non... |
6dfef89ef2d2ddfb103731868fe8fbe7d3f14f8ec23128ac7c87188091349400 | Python | 1,350 | 46 | """Utility functions for processing reflectance spectra."""
import numpy as np
import torch
from mcmlnet.utils.tensor import TensorType, tensor_conversion_decorator
def r_specular(
n1: float | torch.Tensor | np.ndarray, n2: float | torch.Tensor | np.ndarray
) -> float | torch.Tensor | np.ndarray:
"""
Co... |
59e9c0c9fc03cc0421b23dd321a49b5f7678f72f92fda255c4bab6038ec6cd9e | Python | 1,351 | 31 | from brainscore_vision.model_helpers.check_submission import check_models
import functools
import timm
import torch
from huggingface_hub import hf_hub_download
from brainscore_vision.model_helpers.activations.pytorch import PytorchWrapper
from brainscore_vision.model_helpers.activations.pytorch import load_preprocess_i... |
ac913bf6d762d618658133f243207c0df740d289dee8f0c81b3222b597464f44 | Python | 1,351 | 36 | import subprocess
import sys
import yaml
script_SOM = 'SOM/calc_SOM.py'
script_somplot = 'SOM/plot_SOM.py'
script_brainplot = 'SOM/plot_SOM_brain.py'
script_hitplot = 'SOM/plot_SOMhits_resolved.py'
script_clusterSOM = 'SOM/clusterSOM/cluster_SOM.py'
script_nclust = 'SOM/clusterSOM/identify_nclust_SOM.py'
script_exampl... |
fcf2c670edb3f9b4c3eecb49af1a79703141e4fcbacc9104e8751842447bd973 | Python | 1,351 | 28 | from pathlib import Path
import pytest
from pytest import approx
from brainscore_core.supported_data_standards.brainio.assemblies import BehavioralAssembly
from brainscore_vision import load_benchmark
from brainscore_vision.benchmark_helpers import PrecomputedFeatures
from brainscore_core.supported_data_standards.bra... |
753e83e0caebdb71809e8dd0b524d80e4b1b26a5f23eaedb9a715505841d9f1c | Python | 1,352 | 32 | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
import pytest
from tests import SOURCE
from tests.conftest import isolated_model_path
from ultralytics import YOLO
from ultralytics.cfg import TASK2MODEL, TASKS
from ultralytics.utils import WEIGHTS_DIR
from ultralytics.utils.checks import rocm_is_av... |
7d4b9dc4b75c87d0b2905ab070bf2caf189449344f91dff13c062085286e0422 | Python | 1,352 | 55 | import numpy as np
from scipy.constants import epsilon_0 as e0
from impedancefitter.single_shell import eps_cell_single_shell
from impedancefitter.single_shell_wall import eps_cell_single_shell_wall
omega = 2.0 * np.pi * np.logspace(0, 12, num=30)
# for single_shell_model
c0 = 1.0
em = 10.0
km = 1e-6
kcp = 0.5
ecp... |
93c1fde717000755b5e0c5c50e7fae88c8ef61b94ca6f30286a7b52c420e56d8 | Python | 1,352 | 37 | import os
import re
import shutil
import argparse
def organize_nemo_results(input_dir, output_dir):
# match format: sub-<subject_id>_ses-<session_id>
pattern = re.compile(r"sub-(?P<sub>[^_]+)_ses-(?P<ses>[^_]+)")
for filename in os.listdir(input_dir):
match = pattern.match(filename)
if mat... |
9487eab823278ed78e76d2dc506264877be0f8a7c46ae0c5364b63d492ebf633 | Python | 1,352 | 42 | import polars as pl
from argclz import AbstractParser, as_argument, try_int_type
from rscvp.statistic._var import PF_HEADERS
from rscvp.statistic.csv_agg.core import ParquetSheetSync, NeuronDataAggregator
from rscvp.util.cli.cli_statistic import StatisticOptions
__all__ = ['PFAggOptions']
class PFAggOptions(Abstrac... |
0125ea461f17391c11bf27768eef955ce9395c90ff9f6f9420e7c1bf35f474c0 | Python | 1,355 | 39 | # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
from typing import Type
import torch
import torch.nn as nn
class MLPBlock(nn.Module):
def __init__(
self,
embedding_dim: int,
mlp_dim: int,
act: Type[nn.Module] = nn.GELU,
) -> None:
super().__in... |
0376ccd77ea06bc5e6115f66f12c71edaef90f8c7edcd8f24fc9c3f970bec197 | Python | 1,355 | 46 | norm_cfg = dict(type='SyncBN', requires_grad=True)
model = dict(
type='EncoderDecoder',
backbone=dict(
type='RepLKNet',
large_kernel_sizes=[31,29,27,13],
layers=[2,2,18,2],
channels=[128,256,512,1024],
drop_path_rate=0.5,
small_kernel=5,
dw_ratio=1,
... |
13059735f89b10a289e94107fb286129fa9eeb5f319225d9503201caaf7cc238 | Python | 1,355 | 43 | #!/usr/bin/env python
"""
Mad City Labs Z stage functionality.
Hazen 05/17
"""
from PyQt5 import QtCore
import storm_control.hal4000.halLib.halMessage as halMessage
import storm_control.sc_hardware.baseClasses.stageZModule as stageZModule
import storm_control.sc_hardware.madCityLabs.mclController as mclController
... |
47d6805b083dcdc80547b48facfcc54cf1abfbf3a9a9f05282fb0909b59dced2 | Python | 1,356 | 45 | # model settings
norm_cfg = dict(type='SyncBN', requires_grad=True)
backbone_norm_cfg = dict(type='LN', requires_grad=True)
conv_stem_norm_cfg = dict(type='BN', requires_grad=True)
model = dict(
type='DepthEncoderDecoder',
pretrained=None,
backbone=dict(
type='DepthSwin',
pretrain_img_size=2... |
e4fa235084894084f19b1660baf995e0542f4bae9e3560c3f0be11bed0cf1f86 | Python | 1,356 | 46 | from pathlib import Path
import click
import nibabel.nifti1 as nifti1
import skimage
def T1_hybridization(
ll_path: Path,
mixed_path: Path,
csf_mask_path: Path,
threshold: float,
erode: int = 0,
) -> nifti1.Nifti1Image:
mixed_mri = nifti1.load(mixed_path)
mixed = mixed_mri.get_fdata()
... |
1174706803f3ce4833beaa08bc503535ac12f066643d25df35935f44392b3310 | Python | 1,357 | 37 | import sys
from pathlib import Path
p_dir = str(Path(__file__).absolute().parents[2])
if p_dir not in sys.path: sys.path.insert(0, p_dir)
import torch
import torch.nn as nn
import torch.nn.functional as F
from libs.pytorch_utils import Mish, AdaptiveConcatPool2d, Flatten
# This is from iafoss code
class ResNext(nn.M... |
20ee3576c7c562c6b42c346540bd64b5a85a59e5262e8d37dc40d0dec5616a1f | Python | 1,358 | 62 | """
Start the ChemGraph XANES MCP server via HTTP.
This is a thin wrapper that launches the XANES MCP server
(chemgraph.mcp.xanes_mcp) with streamable HTTP transport.
Prerequisites:
- FDMNES_EXE set in environment
- MP_API_KEY set in environment (for fetch_mp_structures)
Usage:
python start_mcp_server.py
# ... |
90f61092f136f5ffdd6894d17aab080a1e3074ac883658275f256c9ee79e1b90 | Python | 1,358 | 46 | """Codex endpoint (own-client protocol).
Codex keeps its existing client (``load_codex_model``), which owns ``codex:``
prefix stripping and ChatGPT subscription authentication. The model is immutable
once created, so no temperature or sampling parameters are forwarded.
"""
from __future__ import annotations
from che... |
d6aa26a2e5bf79c32dd611cac3849daca0bd87d6fd007f66f9698875b2009430 | Python | 1,358 | 44 | #############################################################################
# Copyright (C) 2020-2026 MEmilio
#
# Authors:
#
# Contact: Martin J. Kuehn <Martin.Kuehn@DLR.de>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may... |
e047c455a0d9392452178d4d590899fdaa2e1c9e9b839001cad28ddf2e1e53ae | Python | 1,358 | 39 | # wfield - tools to analyse widefield data - allen utils (numba)
# Copyright (C) 2020 Joao Couto - jpcouto@gmail.com
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the ... |
2d6c96b440d510f1c8dd3cf60f13c68cabbbd862dffaae7b22467abeffb5b56a | Python | 1,359 | 41 | """Example code for saving maps as nii files and plotting with workbench.
"""
import os
import numpy as np
from osl_dynamics.analysis import power
from osl_dynamics.utils import workbench
def get_data(name, output_dir):
if os.path.exists(output_dir):
print(f"{output_dir} already downloaded. Skipping..")... |
3fc59401f2442191276d4466121d369f6abf3cfaca7abfbe8d3a6b33618444f4 | Python | 1,359 | 42 | """
MC‐Dropout predictive mean & std for a single fold model.
$ python -m src.eval.mc_dropout_uncertainty --fold 0 --T 50
"""
import argparse, json
import numpy as np, torch
from tqdm import trange
from src.config import C
from src.utils.data_utils import load_data
from src.models.regression_model import RegressionMo... |
7b4b7856232046eec6ce20c8619b35ab791597c6100a14b99e3252c135b766c1 | Python | 1,359 | 54 | # -*- coding: utf-8 -*-
# python standard library inputs
import os
# external inputs
import numpy as np
import nibabel as nb
def get_mean4d(file_in, path_output="", name_output="", write_output=False):
"""Get mean 4D.
This function computes the mean time series of one or more time series.
Paramete... |
a4e6eaa9285131710faa146e74a26ab23ab7021b33a3fbd29666185c9f4a15e9 | Python | 1,359 | 49 | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtPrintSupport clas... |
c8e1d95614617fcf9bb9ce16ad974a074434edf6997e592255ede7ac36302a63 | Python | 1,359 | 49 | import numpy as np
import zarr
from pathlib import Path
from Waven.zarr_compat import load_array
def test_load_prefers_zarr(tmp_path: Path):
arr = np.arange(12).reshape(3, 4)
npy_path = tmp_path / "a.npy"
zarr_path = tmp_path / "a.zarr"
np.save(npy_path, arr)
zarr.save(str(zarr_path), arr)
... |
21549f1253916215f769bc296e782eeb8bfcb2201977d5db34dfd5530af25532 | Python | 1,360 | 37 | # 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.
import torch.nn as nn
from .learned_positional_embedding import LearnedPositionalEmbedding
from .sinusoidal_positional_embedding import Sinus... |
30c2fbc855597b1310c8acc4cd3b3ee0615770de6a8f31e89b39e437a7d2af8a | Python | 1,360 | 41 | #scenario1.py
#performs imputations and unifies to make sure they remain functional after changes.
import mmsdk
from mmsdk import mmdatasdk
import numpy
import sys
#uncomment all the ==> lines together
#A simple averaging technique. More advanced methods can be built based on intervals.
def myavg(intervals,features)... |
6b208e6296501af68b045158baf03e2901e0484ebf2bc9244903df9f6a2547e2 | Python | 1,360 | 43 | import os
import scanpy as sc
import pandas as pd
import anndata as ad
os.chdir("/data/wuqinhua/phase/covid19/datasets")
adata = ad.read_h5ad('./pre_data/3_COMBAT_2022/COMBAT-CITESeq-EXPRESSION-ATLAS.h5ad')
# adata
csv_data = pd.read_csv('./pre_data/3_COMBAT_2022/dict_combat.csv')
sample_ids_to_keep = csv_data['Samp... |
c682b4c41e5d030ff83e55fc73cce1ebd841c035b63681830ab8ee0bd6210d4a | Python | 1,360 | 53 | """# Dropdown selection widget
Choices for dropdowns can be provided in a few different ways.
"""
from enum import Enum
from magicgui import magicgui, widgets
class Medium(Enum):
"""Enum for various media and their refractive indices."""
Oil = 1.515
Water = 1.333
Air = 1.0003
@magicgui(ri={"choi... |
3b457d1761ce2e31d525ef291e58a152830e1b776b36dae23c034e52c16b51ba | Python | 1,362 | 41 | from __future__ import annotations
import copy
import torch
import torch.nn as nn
import torch.ao.quantization as tq
def make_qat_conv2d(base: nn.Conv2d) -> nn.Module:
# QAT uses fake-quant modules attached via qconfig
m = copy.deepcopy(base)
m.qconfig = tq.get_default_qat_qconfig("fbgemm")
return tq.... |
498d625c606dac6d03ddbc356d2ec386048e721c9608c284102e341609f14660 | Python | 1,362 | 49 | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides Qt3DCore classes an... |
6e045c2ab7116f99fbaa40771a2576f041174d710ec7d71b5f11ef4b06f99b24 | Python | 1,362 | 57 | # imagecodecs/__main__.py
"""Imagecodecs package command line script."""
from __future__ import annotations
import sys
from matplotlib.pyplot import show
from tifffile import Timer, askopenfilename, imshow
from .imagecodecs import imread
def main(argv: list[str] | None = None, *, verbose: bool = True) -> int:
... |
3e84d495bc803b1886bf5921389af9a733426b03efd578ecb1227884dd52dcbb | Python | 1,363 | 45 | # 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... |
abcff3275163f13d2a1f98497845f1c7c34aef26e71fdabb9f67c10d0e043401 | Python | 1,363 | 37 | #!/usr/bin/env python
from setuptools import setup, find_packages
from os import path
here = path.abspath(path.dirname(__file__))
long_description = "Datajoint schemata and analysis code for the mouse pipeline."
setup(
name='pipeline',
version='0.2.0',
description="data processing chain for MICrONS proj... |
decfa2b439560aabe95d41ebf430c028537ecdbb63f6b8e6c8a54b80a1245062 | Python | 1,363 | 52 | from impedancefitter.cole_cole import cole_cole_model, cole_cole_R_model, raicu
from impedancefitter.utils import return_diel_properties
import numpy as np
omega = 2. * np.pi * np.logspace(1, 8, num=20)
# for cole_cole_model
c0 = 1.
el = 81.
eh = 1.8
tau = 9.4e-3
a = 1. - 0.009
kdc = 1e-5
# for cole_cole_R_model
Rinf... |
069e1fd0e8a990e2a3327520283d78de0e1bbd68deeb4b0b2422d135c7f0e2b5 | Python | 1,364 | 41 | from pathlib import Path
from typing import Optional, Tuple
import aicspylibczi
from brainways.utils.image import ImageSizeHW, resize_image
from brainways.utils.io_utils.readers.base import ImageReader
class CziReader(ImageReader):
def __init__(self, path: Path, scene: int):
super().__init__(path, scene... |
1a63df708362e02bf10e194d906475b8afd8426d2ebf9f63b14ccd71c0db95ba | Python | 1,364 | 53 | import argparse
from datetime import datetime
from deepreg.train import train
name = "paired_ct_lung"
# 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(
"--test"... |
294842b4304eb293f0b952c725fa657a08843c7d2a5b9eece7aae706ff3b6326 | Python | 1,364 | 44 | import h5py
import time
import requests
from tqdm import tqdm
import os
import math
import sys
from mmsdk.mmdatasdk import log
def read_URL(url,destination):
if destination is None:
log.error("Destination is not specified when downloading data",error=True)
if os.path.isdir(destination.rsplit(os.sep,1)[-2]) is F... |
5d8455121d04c9bedf3133bcc05c86e162a5c3013a3fa2bf2d14dedb7d9c7446 | Python | 1,366 | 42 | # 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... |
add29b7524610c2886228bf13aec4b5bd238864e2d46266b362ef56dee39e3e2 | Python | 1,366 | 38 | import torch
from utils import loss_and_miner_utils as lmu
from losses.base_metric_loss_function import BaseMetricLossFunction
class GenericPairLoss(BaseMetricLossFunction):
def __init__(self, mat_based_loss, **kwargs):
super().__init__(**kwargs)
self.loss_method = (
self.mat_based_lo... |
b39b9b2a40152e9916e70a9733c4133029e6dc4b4ec564f5c4d2f25e6d482bbd | Python | 1,366 | 51 | import math
import torch
import torch.nn as nn
from torch import Tensor
# Modified from PyTorch Website and ChatGPT proposal
class PositionalEncoding(nn.Module):
def __init__(self, d_model: int, dropout: float = 0.1, max_len: int = 5000):
super().__init__()
self.dropout = dropout
if dropo... |
237e9a7083b28017a7bf8a8ea1edbe3df9e972aeb23b14d492c401734177f5d6 | Python | 1,368 | 27 | from step1_dataimport.xnatconnectionprovider import XNATConnectionProvider
from step1_dataimport.step1_1_dataoverview import DataOverview
from step1_dataimport.get_env_vars import get_environment_variables
def main(
overview_csv_filepath: str,
dcm_tags_csv_filepath: str = "src/step1_dataimport/dicom_tags_xnat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.