sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
8e09d0d9bd81ab63cacf6985745a24cef8c403c7be290e2f42f68658cc54f47c
Python
1,006
40
import pandas as pd import cooler import numpy as np ctrl = snakemake.input.ctrl bedpe = snakemake.input.bedpe of = snakemake.output.bedpe clr = cooler.Cooler(f"{ctrl}::resolutions/15000") pixels = clr.pixels()[:] bins = clr.bins()[:] a = pd.read_table(bedpe, header=None) a.columns = ['chrom1', 'start1', 'end1', 'ch...
dee79a8778a5e398a2b1931d78866cf5572b595143fe2f56d7fa5737ac4a25e2
Python
1,006
30
#!/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=['processing.zip']) tmp_dir = tempfile.T...
621e3d991e44df0042dd3b69f7a590c4d93aec7bcbf31ad931995fdcae391f89
Python
1,007
25
# Copyright (c) 2015 Tobias Neumann, Philipp Rescheneder. # # This file is part of Slamdunk. # # Slamdunk is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your o...
85dcc71e8041f8998193f0afb02f29ef153d0eacd593b44c9c16b7b2539ef8de
Python
1,007
23
from brainscore_vision import metric_registry from .metric import OSTCorrelation metric_registry['ost'] = OSTCorrelation BIBTEX = """@article{kubiliusschrimpf2019brain, title={Brain-like object recognition with high-performing shallow recurrent ANNs}, author={Kubilius, Jonas and Schrimpf, Martin and Kar, Kohitij ...
8da7ff67d927fc638348d7ad811c386177beef5977547eb8343fffc965367c7d
Python
1,007
43
#!/usr/bin/env python3 import sys from optparse import OptionParser USAGE = """ python trf-to-bed.py --trf <trf file name> --bed <bed file name> combine the split trf files into a single file """ ############################################################################### parser = OptionParser(USAGE) parser...
b5cad24cfb74622a5fe7092c3298bdeaebd99f43c1cfb04c107f375237d04a90
Python
1,007
26
import torch from peft import LoraConfig, get_peft_model, PeftModel def init_lora(target_modules, lora_r=16, lora_alpha=64, lora_dropout=0.2): lora_config = LoraConfig( r=lora_r, lora_alpha=lora_alpha, target_modules=target_modules if not target_modules is None else 'all-linear', # Specific...
d20affe431131f6b1c59086b5c6142b8f942f0d7174fa40bec1b725315e3ee2a
Python
1,007
41
# Copyright (C) CVAT.ai Corporation # # SPDX-License-Identifier: MIT """ ASGI config for CVAT project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/ """ import os from django.core.as...
d2f32af0086c029bc8406d4c5e3c84048efcb299dda2a89e07895247ff259be3
Python
1,007
44
""" nelpy.analysis ===== This is the nelpy analysis sub-package. nelpy.analysis provides several commonly used analyses. """ # from .hmm_sparsity import HMMSurrogate from .ergodic import fmpt, steady_state from .replay import ( column_cycle_array, get_significant_events, linregress_array, linregress_...
311b59ad75051dfdb5cea9b3d09d7711471aee5873b3c5d7334802d6eb6822ad
Python
1,008
38
import numpy as np import pandas as pd import os import time import seaborn as sns import matplotlib.pyplot as plt from scipy.spatial.distance import pdist from scipy.cluster.hierarchy import fcluster, to_tree, dendrogram, linkage from matplotlib.pyplot import cm import copy def get_entropy(vector): ''' Ge...
4dba5919a010a7e25f45a731577ec4f1c2f5012f9e9a5cc2e1c9bcefae71e9de
Python
1,008
45
import numpy as np import torch import pickle import os, sys import glob input_folder = sys.argv[1] subsets = ["test_id", "test_ood_ads", "test_ood_both", "test_ood_cat"] def flatten(d, index): res = [] for x in d: res.extend(x[index]) return np.array(res) def one_ckp(folder, subset): s = ...
ad037d95e269ec31f220964670864ef00f3c5872301d4b2f30fa0889d3abdca1
Python
1,008
41
#!/usr/bin/env python3 import arbor as A from arbor import units as U from util import plot_spikes, plot_network from unconnected import unconnected # global parameters # cell count N = 5 # total runtime [ms] T = 1000 # numerical time step [ms] dt = 0.1 class ring(unconnected): def __init__(self, N) -> None: ...
54a583cfb2452e0459c8acb7bb3d135f21f5164b78a7b913f4af9c6b00ad2cce
Python
1,009
43
#!/usr/bin/env python """ Find continuous regions that are covered by the first bed file (`bed_file_1`) but not by the second bed file (`bed_file_2`) usage: %prog bed_file_1 bed_file_2 """ from bx.bitset_builders import binned_bitsets_from_file from bx.cookbook import doc_optparse def print_bits_as_bed(bits): ...
5d4d8a9b14ba6ee059a28ca9f3eb962824c2a1ad2001c7eaee91cea2d9204c68
Python
1,009
40
#!/usr/bin/env python3 # Author: Jeffrey M Kidd # bed-length.py # Returns total length of intervals in in a UCSC (0-based style) bed file import sys from optparse import OptionParser USAGE = """USAGE:python bed-length.py -f <bed file> Reads a UCSC style bed file and reports total interval size. Assumes that inter...
002de3f615f887e496e5137c4411881cf6c33fa8006cdef4b0372e5e63aa4065
Python
1,010
43
import pytest from pyment.models.sfcn import ( BinarySFCN, CategoricalSFCN, MultiTaskSFCN, RegressionSFCN, sfcn_factory, ) @pytest.mark.parametrize( 'name, expected', [ ('sfcn-reg', RegressionSFCN), ('regression', RegressionSFCN), ('sfcn-bin', BinarySFCN), ...
0339bfadf563269264ab16c27e09c0113fa5de3516036e91958243489ada3b93
Python
1,010
45
# -*- coding: utf-8 -*- # python standard library inputs import os import sys import subprocess # local inputs from ..io.get_filename import get_filename def smooth_surface(file_in, file_out, n_iter): """Smooth surface. This function smoothes a surface mesh using freesurfer. Parameters ...
6a09e66af3e081a601866d8f359634c80c64f041fcd2dca3170ffa634d1e156b
Python
1,010
33
# anonymize_bam.py - de-identify sequencing data import setuptools # Set __version__ for the project. exec(open("./BAMboozle/version.py").read()) with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() setuptools.setup( name="BAMboozle", version=__version__, author="Christo...
a7e98ba0b211c6a340f0a75f1b7205fde0f455da2116c9184e1f781a41abd9fa
Python
1,010
38
from pathlib import Path data_dir = Path("data") file = "database.csv" # plots and visuals ColorMap = ["#ADE1DC", # soft aqua "#C5C2E4", # lavender "#F28C8C", # warm coral "#9FCBE1", # sky blue "#F8BC63", # amber "#CBEA7B", # light lime "#F5C6DA", # blush pink "#BFD8B8", # mint ...
f26eab69fefb1e95f0ea2c984b43298524265e8d2328c909f3d3cb4033ade6a9
Python
1,010
42
# -*- coding: utf-8 -*- # python standard library inputs import os # external inputs import numpy as np import nibabel as nb def get_series(file_in, path_out, name_output): """Get series. This function creates a 4D nifti time series from a set of 3D nifti files. Parameters ---------- file_...
7a390dfc2d759d4674e9a2f26bf8d200c214b14e5d824245b83e89ef2ff3f268
Python
1,011
35
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import pytest pytestmark = pytest.mark.xdist_group("serial") def test_generate_option(script_runner): ret = script_runner.run(['scil_search_keywords', 'test', '--regenerate_help_files', '--processes', '4']) ...
0047f9df57fa71a6a07efe039f8de06d61f08d1b6bd1aefc2888dcc3da15954a
Python
1,012
28
# -*- coding: utf-8 -*- # @Author : LG from PyQt5 import QtWidgets from ISAT.ui.info_dock import Ui_Form class InfoDockWidget(QtWidgets.QWidget, Ui_Form): def __init__(self, mainwindow): super(InfoDockWidget, self).__init__() self.setupUi(self) self.mainwindow = mainwindow self...
d9dd4a6a0aaac5623b4de266934de643817faea6c497c5c82aa1884049d88486
Python
1,013
26
# fslcpgeom # Usage: fslcpgeom <source> <destination> [-d] # -d : don't copy image dimensions import os from nipype.interfaces.base import (CommandLineInputSpec, CommandLine, traits, TraitedSpec, BaseInterface, BaseInterfaceInputSpec, File) from traits.api import Directory, Str, List, Bool, Enum, Int, Float, TraitErr...
c120a795660fc11c6e8cd7546c5cd2f71e763770923fb483195708b2c3a8641b
Python
1,014
43
import sys import os import signal import traceback def error_handler(exctype, value, traceback): print() print("Error:", value, file=sys.stderr) sys.exit(1) def exit_handler(signal, frame): print() print("User abort (CTRL-C) received.") sys.exit(0) def show_error_dialog_win(title, message): """Display...
dd012be52adaf83e465065398ae71f5f1d1f6421c58e4a2d58a8956d3868ab22
Python
1,014
29
#!/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=['atlas.zip']) tmp_dir = tempfile.Tempor...
8872aa69e960cce12b30fe9dde1a646d42e714418e58be9727d8debfe43d7eec
Python
1,015
36
""" Tests for `bx.seq.qdna`. """ import unittest from bx.seq import qdna test_qdna = "test_data/seq_tests/test.qdna" # Same sequence data as stored in test.qdna valid_seq = ( "C7wMwHQrMKqEtSREuUv5nsLinpTS8l7jXpbI7IipvCbHnhOdgx" "5tzRgzYl4j85d:xSlvKPEKEIvZkfiX1YPkBi1Ibhfn9fTZd8gG" "Wy284hJnwf93W4eHOjeRk...
d64f40f71c3bdf3ab00edd66ea928365ff0feffabff01462c82a9e5d1f0a1a0f
Python
1,015
36
""" Tests for `bx.seq.fasta`. """ import unittest from bx.seq import fasta test_fa = "test_data/seq_tests/test.fa" # Same sequence data as stored in test.fa valid_seq = ( "TGGAGGCATTTGTGATTCAATAGATGCAGAAAGAAACCTTCCTAGAGCTG" "GCGTTCTCTAACTAAAAGTGGAAAGTTCTGAGGAATGAGGACTGTTATAA" "ATCCCACCCCACACCGCACCTTCTC...
6b579494c3bd54d5d307e47f765c6ae250dc9162a4bcde83b18c80788008b030
Python
1,016
25
from brainscore_core.supported_data_standards.brainio.assemblies import NeuronRecordingAssembly from brainscore_vision import data_registry, load_stimulus_set from brainscore_core.supported_data_standards.brainio.s3 import load_assembly_from_s3 BIBTEX = """@article{lee2019sensitivity, title={Sensitivity of inferote...
6fe007a6956ece79b3cdcc1ae07f4b68410eab3495656ff5aaefb195037f71cf
Python
1,016
35
from dataclasses import dataclass from typing import List import numpy as np @dataclass class Obj: acc: float # maximize analog_macs: float # maximize dig_w_mb: float # minimize def dominates(a: Obj, b: Obj) -> bool: return ( a.acc >= b.acc and a.analog_macs >= b.analog_macs and ...
b43df6abc867bbf9156b955d54a3bb92973ab232357c1350576af14cbbd2f5ff
Python
1,016
36
from setuptools import setup import os.path as op import glob from setuptools.command.build_py import build_py class build_py_with_references(build_py): def run(self): references_src = op.join("docs", "source", "references.bib") references_dst = op.join("AFQ", "_references.bib") with open...
14a218bb3493d8c1c9546ecf6757b2526f624b6cfebd1d8430a84b8cf771de58
Python
1,017
27
# Package marker for ui.widgets from .navigation_controls import NavigationControls from .double_zoom_widget import DoubleZoomWidget from .image_mouse_move_handler import ImageMouseMoveHandler, ImageMouseMoveState from .display_options_panel import DisplayOptionsPanel from .collapsible_right_panel import CollapsibleRig...
281e883ef41c65790def33cc6d78799f1e8077c680115ad9d2bf8f0e9cc4b08d
Python
1,017
24
from typing import Union, Tuple, List import torch from batchgeneratorsv2.transforms.base.basic_transform import SegOnlyTransform class RemoveLabelTansform(SegOnlyTransform): def __init__(self, label_value: int, set_to: int, segmentation_channels: Union[int, Tuple[int, ...], List[int]] = None): if not i...
39a71d4211c3e26a51729616008db51c80857da4382bd3067ae157779d3c0d67
Python
1,017
48
# %% # imports import os from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter import ffmpeg # %% # Argle parser parser = ArgumentParser( prog='resample_video_fps', description='Resample a directory of videos to 10 fps.', formatter_class=ArgumentDefaultsHelpFormatter ) parser.add_argument( ...
3cf599a18a62bca2de3df8f2cf3566d7b16657e00182f1b0cd955615075dca36
Python
1,017
25
from brainscore_vision.model_helpers.check_submission import check_models 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 from .helpers.cornet_helpers import v...
c5f83019ad74a558371aa37fe19fa87fa3aa14d1154659dbf0f1f50200d4efce
Python
1,017
31
#! /usr/bin/env python3 import anatomy import argparse if __name__ == "__main__": parser = argparse.ArgumentParser( description="mp2rage_recon-all (requires freesurfer v7.1, CAT12 and optionally gradient_unwarp.py)" ) parser.add_argument( "inv2", type=str, help="path to nifti file containin...
f3c866c9cf9d5a5b4feba31b8eb5be54705c5603ce234574064ad5df407e2f27
Python
1,017
31
""" Assign weights to distances in a way such that farther values are weighed less """ import numpy as np def shepards(distances, power=2): """ Basic inverse distance weighting function Parameters ---------- distances: list/numpy.ndarray 1D list of numbers (ex. distance results from call to KD...
63e7be9373a34e17e06fa4bebb602bdc661f7ecd9f45c3cabc1380407550c111
Python
1,018
31
#!/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=['tracking.zip']) tmp_dir = tempfile.Tem...
8a02c5959e543a2588c40a9c91f9cc057008b2e5c3d3b74b31658426ef8e3394
Python
1,018
26
import torch import torch.nn as nn import torchvision.models as torch_models class TorchVisionOverwrite(nn.Module): def __init__(self, arch='vgg16', pretrained=False, num_classes=1000, in_chans=3): super().__init__() model = torch_models.__dict__[arch](pretrained=pretrained) # Layers are...
d434d81706b0f6c699a1cab5b99346cca8c257177be4ab20c31cdd0e51f88479
Python
1,018
30
"""Get training data. This script will download source reconstructed resting-state (eyes open) MEG data. This data is part of the MEGUK dataset. It is CTF data from the Nottingham site. 65 subjects are part of this dataset. """ import os def get_data(name, output_dir): if os.path.exists(output_dir): pri...
da9ce6fabf12a79d78b484f65e8dc9f73577af39c4b3922e2477df3574786567
Python
1,018
36
from ..util import NodeSelector from ..qt import * class AlgebraWidget(QWidget): def __init__(self, config, stub): super().__init__() self.config = config node_selector = NodeSelector(config, 'Source', False) equation_edit = QLineEdit() grid = QGridLayout() grid.addWidget(QLabel('Equation:'...
20ed009d4145801ff4e7b48415adf49377df82b31d5dca092872cb46066c8f85
Python
1,019
23
from step1_dataimport.step1_2_filter import FilterDataset from step1_dataimport.step1_2_import import DataImport from step1_dataimport.xnatconnectionprovider import XNATConnectionProvider from step1_dataimport.step1_2_duplicates import IdentifyAndMoveDuplicates from step1_dataimport.get_env_vars import get_environment_...
438fd33b62c91ee0dba30b4b5bba5a0cbe29ab99f719f3cd546ac0b5cae4b29c
Python
1,020
28
"""Collection of performance metrics and related utilities. Score model outputs by prediction correlation and other metrics. Measure equivalence, sparsity, and other properties of model predictions and/or recorded neural responses. # TODO: These contents don't all exist yet, sketching this out based on # the st...
a347c47abffc073def7624c6bd585676b5241914f17158fdc4f7a4d12802294e
Python
1,020
31
import ants import antspynet import sys import tensorflow as tf t1_file = sys.argv[1] output_prefix = sys.argv[2] threads = int(sys.argv[3]) tf.keras.backend.clear_session() config = tf.compat.v1.ConfigProto(intra_op_parallelism_threads=threads, inter_op_parallelism_threads=threads)...
d3ff167902bc6053b7562a33d97fc52d23a8fd338eabcda09c2cc6701e6b278a
Python
1,020
49
#!/usr/bin/env python # -*- coding: utf-8 -*- # import distutils.cmd import platform import os import setuptools.command.build_py import subprocess import sys from setuptools import setup, find_packages version = "2.0" description = "STORM microscope control code." long_description = "" setup( name='storm_cont...
d50b501a3224ebfe679c3f9e60cead0914861eebcd59a79dea062b1248469727
Python
1,020
29
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/10_Schuurman_2021/pbmc.h5ad') adata.obs.rename(columns={'id_new': 'sample_id'}, inplace=True) adata.obs = adata.obs.rename(index=lambda x: x.replace('.', '-')) csv...
f11faa403f384a7e68c7abe24cdd2460727c9c89eceb00d2dfe107c312fe9005
Python
1,020
40
import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.parameter import Parameter def gem(x, p=torch.ones(1)*3, eps: float = 1e-6): return F.avg_pool2d(x.clamp(min=eps).pow(p), (x.size(-2), x.size(-1))).pow(1./p) class GeM(nn.Module): def __init__(self, p=3, eps=1e-6): sup...
3b67bd33a8b6fa0ab66407ecf80ddbcc8988d9c30e1267faa4a7cf3d61f85425
Python
1,021
34
#!/usr/bin/env python3 """Interactive installer for metaprivBIDS. This script prompts the user whether the optional ``pygraphviz`` dependency should be installed. ``pygraphviz`` is used for advanced graph visualisation but can be troublesome to install on Windows systems. If the user declines, installation proceeds ...
87a576e4a7c89dafe0217f8766fb4edfe439a08dfbae3f25633c777f6933cd0c
Python
1,021
22
from tests.utils import pytest_importorskip def test_qt3danimation(): """Test the qtpy.Qt3DAnimation namespace""" Qt3DAnimation = pytest_importorskip("qtpy.Qt3DAnimation") assert Qt3DAnimation.QAnimationController is not None assert Qt3DAnimation.QAdditiveClipBlend is not None assert Qt3DAnimatio...
e38d1d5d4468c285ece2b1f3fa705fe373ffd6b28a17130033cc5c55ab2242b2
Python
1,021
32
#! /usr/bin/env python3 import sys import os from nipype.interfaces import spm,matlab spm_path = '/data/pt_02389/Software/spm12' def spm_bias_correction(): # bias correct INV2 seg = spm.NewSegment() seg.inputs.channel_info = (0.001, 20, (False, True)) seg.inputs.affine_regularization = 'mni' seg.i...
008f4d397a79f5056992a1d9f1ef93fff57dcdee8978c912f186b0c251f88d42
Python
1,022
35
from magicgui.widgets import protocols class _OrientationMixin: """Properties for classes wrapping widgets that support orientation.""" _widget: protocols.SupportsOrientation @property def orientation(self) -> str: """Orientation of the widget.""" return self._widget._mgui_get_orient...
0e762d040a40278eb3030a17ad99ca81fd44eb7fa21dbdb0d6b1f2e6f87f87af
Python
1,022
35
from typing import Protocol from eir.models.input.sequence.transformer_models import ( MaskedTransformerFeatureExtractor, TransformerFeatureExtractor, TransformerWrapperModel, ) class SequenceModelClassGetterFunction(Protocol): def __call__( self, model_type: str, force_masked...
9c9e502bac839aee8a5fa2a8b404c8c98b107ecfbf0ab910adbbaaa47fac216f
Python
1,022
36
import base64 from io import BytesIO import requests from PIL import Image def encode_image_to_base64(file_path: str) -> str: with Image.open(file_path) as image: buffered = BytesIO() image.save(buffered, format="JPEG") return base64.b64encode(buffered.getvalue()).decode("utf-8") def se...
bfd28d9dd5108c843c3bcc459629f743787c8d46b89e9d6644e24da89a8227be
Python
1,022
26
import dask_image.imread import numpy as np from skimage import draw import os def loading_by_dask(image_path, crop_coords=None): ''' Load images by dask_image.imread.imread Args: image_folder: path to image folder crop_z_range: crop z range (only for fixed image) moving_crop_coords...
f01e1998a9fd292e908682f401a52fdb4520c2fc38d3afaf6db3c9c70c3ec512
Python
1,022
44
import os from collections.abc import Callable from functools import wraps from typing import TYPE_CHECKING, Any from torch.nn.parallel import DistributedDataParallel from eir.utils.logging import get_logger if TYPE_CHECKING: pass logger = get_logger(name=__name__) def in_distributed_env() -> bool: return...
3d9278637cccfa528b3fdbf6a301a84c97f01d2f04024ad5d03f026bce796d82
Python
1,023
27
from brainvoice.data.fmri import load_fMRI_data from brainvoice.visualization import plot_fMRI_maps import numpy as np if __name__ == "__main__": root_path = '../Data/charly/BrainVoice_11-02-23' sub_name = 'sub-01' contrast_name = 'averaged_single_trial_vs_sil' #rois = ['LA1', 'RA1', 'LmTVA', 'RmTVA'...
8c63570fac8f602d83ed99fb0ab24bd24ce838c272cf6e1bed0aaf3c614c7e03
Python
1,023
33
from typing import Any, Dict, Type from pymongo import MongoClient import pprint from dotenv import load_dotenv import os import logging load_dotenv() class Container: FACTORIES: Dict[str, Type[Any]] = dict() ENTITIES: Dict[str, Any] = dict() PLUGINS: Dict[str, Type[Any]] = dict() DAOS: Dict[str, Any...
c8e48ce7b1f085c00d2a87637e13bb58a1ee01bad2069860aa1554a3f4b07d9b
Python
1,023
35
#!/usr/bin/env python """ Test parameter file IO. """ from storm_control.test.hal.standardHalTest import halTest def test_hal_params_1(): halTest(config_xml = "none_classic_config.xml", class_name = "ParamTest1", test_module = "storm_control.test.hal.param_tests") def test_hal_params_2()...
1b318ed46effa701b7bc4caab13158eb8463bb6756a072b598607da4c54fe560
Python
1,024
40
from __future__ import annotations from pathlib import Path import pytest from pytestqt.qtbot import QtBot from ..conftest import close_or_pause from .conftest import MainWinFactory @pytest.mark.gui def test_MainWindow_open( *, main_win: MainWinFactory, qtbot: QtBot, pause: bool ) -> None: win = main_win()...
41ee3644c4dd48d1b3c7f3f6feab0e2ca41d2bb24148c565b3debab13848b532
Python
1,024
35
#!/usr/bin/python import sys import re import os from src.hierarchy import Hierarchy try: os.mkdir('res') except OSError: pass PYTHON_PATH = './' GENERAL_HIERARCHY_FNAME = 'data/KO_gene_hierarchy/KO_gene_hierarchy_general.tms' CHANGES_FNAME = 'data/KO_gene_hierarchy/KO_gene_hierarchy_changes.csv' MAPPINGS_PA...
4519b09d7e775a1404b96528bd64cc9fbaf018e1234d8a42a8db081d5588b0f4
Python
1,024
23
from brainscore_vision.model_helpers.check_submission import check_models import functools import timm from brainscore_vision.model_helpers.activations.pytorch import PytorchWrapper from brainscore_vision.model_helpers.activations.pytorch import load_preprocess_images def get_model(name): assert name == 'deit3_bas...
8054121c4989573b990f412f6bcacda386ab41a883c7c50c59771a8fc7f92a03
Python
1,024
45
""" Binary classificatios sytem DB van de Pavert and MB Vessies """ import torch import torch.nn as nn from ecgxai.systems.base_system import BaseSystem class ClassificationSystem(BaseSystem): def __init__( self, model: nn.Module, mode: str, **kwargs ): super().__ini...
5202316fd2ff962c76b789349dd50a4980249fbad4c34d681d873ab3e228c126
Python
1,025
34
"""Example script for plotting the activity maps from the state/mode means. In this example we plot the state means from an HMM fit, but this can be easily substituted with mode means from DyNeMo. """ import os import numpy as np from osl_dynamics.analysis import power def get_data(name, output_dir): if os.path...
9599fcb969eae7809cedaee0079d3749461588158361f80acc0a134f4c2e7074
Python
1,026
28
#!/usr/bin/env python3 """Run CNN vs rule-based comparison for all artifact types.""" import logging from artifact_identification.evaluation.cnn_vs_rules import evaluate_model def main(): logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') logger = logging....
e1180af356a7c874e501e4c9dcd54fba24eceb61cf642de6b50c35f45ad69429
Python
1,026
23
from brainscore_core.supported_data_standards.brainio.assemblies import NeuronRecordingAssembly from brainscore_vision import load_stimulus_set from brainscore_vision import stimulus_set_registry, data_registry from brainscore_core.supported_data_standards.brainio.s3 import load_assembly_from_s3, load_stimulus_set_from...
10d6e59d8b5657de852a5ecee56438e2c026c6ecf8dc2f490cfe0b8dcebb3af0
Python
1,027
38
# 2023-03-01 import pandas as pd import numpy as np from scipy.stats import entropy import sys from util import get_max_of_dict, get_min_of_dict, read_list, read_expr import matplotlib.pyplot as plt from scipy.ndimage import gaussian_filter1d from filter_gene import * wt_expr = pd.read_csv(sys.argv[1]) pcgs = read_...
e8d823ff6d644e37e9145a3c074da26c46aa73e66fba784daa2a611ecf2c7914
Python
1,027
34
# -*- coding: utf-8 -*- """ Created on Mon Jun 13 15:58:31 2022 @author: Yoshi """ def modulation_color_key_generator(): # Dictionary to store colors color_key = {} # Calculates HSV values for negative values negative_list = [-1.0,-0.8,-0.6,-0.4,-0.2] for index in negative_list: ...
063ca7280d2d8959098ac214a1385aca40d8452ce1dabd41503042c7e062a366
Python
1,028
44
from cProfile import label import numpy as np import pandas as pd import json import torch from pathlib import Path def str_to_int(s): if s == 'human': return 1 else: return 0 path1 = Path('datasets/Twibot-22') data = pd.read_csv(path1 / 'label.csv') label = data['label'] label = torch.tensor(...
392f9e00eb5286025e2d29f39fe6fa3defe6936ce042489c61186e4a6c646afe
Python
1,028
21
"""" save key code and log """ import shutil import os def save_log(save_path): shutil.copytree("./dataloader/", save_path+"/dataloader/") shutil.copytree("./models_for_cifar/", save_path+"/models_for_cifar/") shutil.copytree("./models/", save_path+"/models/") shutil.copytree("./utils/", save_path+'/uti...
c5006e3dcaf59f18c9067f1496da27734772485bf532c204e05f7c10050bef10
Python
1,028
44
import gzip import os, sys import pickle from tqdm import tqdm from multiprocessing import Pool import lmdb from rdkit import Chem import torch split = torch.load("split_dict.pt") train_index = split["train"] os.system("rm -f label_3D.lmdb") env_new = lmdb.open( "label_3D.lmdb", subdir=False, readonly=F...
d530a8aeec9534b6eb0f7c6e66fe15f7caf018fbe9fc2d71293a82167412e91d
Python
1,028
30
from typing import List, Union from torch_geometric.data import Data, HeteroData from torch_geometric.data.datapipes import functional_transform from torch_geometric.transforms import BaseTransform @functional_transform('normalize_features') class NormalizeFeatures(BaseTransform): r"""Row-normalizes the attribut...
8d99b5943c5c29cfff4ece3c44493040a2bcecb141ef1e20cd56a2117390532b
Python
1,030
33
# This updates usage/methods.rst to the latest API methods # Developers can run this after modifying any arguments the user can see from textwrap import dedent from AFQ.api.utils import methods_descriptors prologue = """ .. _methods_docs: The pyAFQ API methods --------------------- After defining your pyAFQ API obj...
911c983beea2b48c8a4e61844e7b035383f50eb79e1dd22d1c589d6044173078
Python
1,030
21
import pandas as pd import matplotlib.pyplot as plt ## probably figure one here. I don'y know yet if I want to seperate each state or overlay them. I think seperate. vermont_raw = pd.read_csv('C:/Users/Alfred/OneDrive - Noorda College of Osteopathic Medicine/Flu-modeling/Vermont/Vermont_Data_Combined.csv') ...
a0973d3af2dc0dd788dd0fee3762287c5558250e5fc3fb499e176f711b46ca42
Python
1,030
34
#!/usr/bin/env python3 import os from glob import glob import numpy as np import pandas as pd from photonai.base import Hyperpipe from photonai_neuro import BrainMask from photonai_neuro.nifti_transformations import ResampleImages def main(): df = pd.read_csv('/input/input.csv', index_col='subject') files =...
2be91dbb2aa4d2bf850971ecfa85dc8509bd7ebd74494594388943b2c37c73f5
Python
1,031
41
# -*- coding: utf-8 -*- import torch class Embedding(object): def __init__(self, tokens, vectors, unk=None): super(Embedding, self).__init__() self.tokens = tokens self.vectors = torch.tensor(vectors) self.pretrained = {w: v for w, v in zip(tokens, vectors)} self.unk = u...
621d04e6e5fa2aab153449df0b4f14b6fbc05f9ba13d16c66ca60bb6f171cb07
Python
1,031
31
import torch import torch.nn.functional as F def la_loss(anchors, positives, negatives, tau: float = 1.5): """ La loss as described in Section 3.1.3. anchors: visual features f_a, [B, D] positives: positive text features f_p, [B, D] negatives: negative text features f_n, [B, D] All assu...
7d644b41ee20554dc002143e22bb7bef195ed8eaba0def43f7fa842ee575b825
Python
1,031
37
import subprocess import sys import yaml script_compare = 'enrichments/compare_nw_ww.py' pathpath = 'PATHS/filepaths_carlen.yml' with open(pathpath, 'r') as myfile: pathdict = yaml.safe_load(myfile) sys.path.append(pathdict['code']['workspace']) from pfcmap.python import settings as S setkeys = [key for key in S.run...
afc0192e66ea938808028af462f46072a08e44a834fa13aaa7b1c23caf8556a1
Python
1,031
47
""" FLYNC Assets Module This module provides access to packaged model files and configurations. """ from pathlib import Path import importlib.resources as pkg_resources __all__ = ["get_asset_path", "list_assets"] def get_asset_path(asset_name: str) -> Path: """ Get the path to a packaged asset file. P...
6c211ce2a87363f7a0df7608fb92d93fd00116d331fa8e2651ec296b51f2bc03
Python
1,032
45
# -*- coding: utf-8 -*- # python standard library inputs import os import sys import subprocess # local inputs from ..io.get_filename import get_filename def inflate_surf_mesh(file_in, file_out, n_iter): """Inflate surf mesh. The scripts takes a generated FreeSurfer surfaces and inflates it. Param...
7daca94cd0e2e112216a8b9f6186f3bdfb286489c623ba7d6a134da7adc0e6d8
Python
1,032
37
import base64 import io import json import numpy as np from model_handler import ModelHandler from PIL import Image def init_context(context): context.logger.info("Init context... 0%") model = ModelHandler() context.user_data.model = model context.logger.info("Init context...100%") def handler(con...
03492e9efa958cc3adfbedf55d3b8e1a42d1eb3d1e00158ee5f4a406d2c27815
Python
1,033
17
raw={} raw["words"]='http://immortal.multicomp.cs.cmu.edu/CMU-MOSEI/language/CMU_MOSEI_TimestampedWords.csd' raw["phones"]='http://immortal.multicomp.cs.cmu.edu/CMU-MOSEI/language/CMU_MOSEI_TimestampedPhones.csd' highlevel={} highlevel["glove_vectors"]='http://immortal.multicomp.cs.cmu.edu/CMU-MOSEI/language/CMU_MOSEI...
7e33528c93bf48bf2d9a5e66154202458e09f4ccb9c06a2831f307a2e04c1755
Python
1,033
42
"""Example script for plotting Amplitude Envelope Correlation (AEC) functional connectivity maps. """ print("Setting up") import os import numpy as np from osl_dynamics.analysis import static, connectivity from osl_dynamics.data import Data # Make a directory to save plots to os.makedirs("figures", exist_ok=True) #...
eb4cc1c83d11b823a61c5df06ec63d5a912454d057934f929341c60a96feff28
Python
1,033
44
""" Find which runs used which patterns """ import pandas as pd import glob import os ROOT = '/Volumes/sDresBackUp/s1Anfunco/Nifti' subs = sorted(glob.glob(os.path.join(ROOT, 'sub*'))) for sub in subs: sub = sub.split('/')[-1] print(sub) funcDir = f'{sub}/derivatives/{sub}/func' runs = sorted(glob...
ee05dda5283399038d5960f895c7bd6c1f9dabc682d26630d7d9ffe0d400195b
Python
1,033
40
import torch class Config: # 数据参数 M = 10 # 阵元数量 f = 1500 # 信号频率 (Hz) v = 1500 # 声速 (m/s) d = v / (2 * f) # 阵元间距 T_values = [50, 80, 100, 200, 500] # 快拍数 snr_range = [-20, 20] # SNR范围 (dB) # 噪声类型 noise_types = ['white', 'pink', 'red', 'blue', 'violet', 'impulse...
18e10779ef68b2321c1b1a5edc670c761ed4685f790446ebb9d3122f2d45e04f
Python
1,034
31
# data_loaders/inference_dataset_loader.py import torch from torch.utils.data import Dataset import pandas as pd import numpy as np class class_ls(Dataset): def __init__(self, x, transform=None): df = pd.read_pickle(x) self.X = df['coo_format_data'].tolist() self.N = df['Precursor'].tolist...
3155f8f7107e8f31993a9627debcb9c4a69e5a7b50e631f29c83e3321d6f4cd6
Python
1,034
34
import pandas as pd import sys import numpy as np def my_groupby(gdf): real = gdf[gdf.case == "Real"] null = gdf[gdf.case == "Null"] return (real.length * real["cov"]).sum() - (null.length * null["cov"]).sum() bed = sys.argv[1] df = pd.read_csv(bed, sep="\t", header=None) df.columns = ["ct", "st", "en",...
3859e7adb282a1ccf3ef554f0b0c022e3a6aa31849a9f378ab2cc4a0ee0091f2
Python
1,034
33
#!/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=['processing.zip']) tmp_dir = tempfile.T...
7ebce6f21eea2b52de5a276803ab20b09542bdeaced319481343bbe1f577bd2c
Python
1,034
36
import pandas import numpy as np from tqdm import tqdm def read_single_csv(input_path): import pandas as pd df_chunk=pd.read_csv(input_path,chunksize=1000) res_chunk=[] for chunk in df_chunk: res_chunk.append(chunk) res_df=pd.concat(res_chunk) return res_df if __name__ == '__main__': ...
4d963da8b64ae7c342b42b081ac5c649d2e890ac9497b187fd1d1dc765ee5bf7
Python
1,035
35
#!/usr/bin/python3 import os import numpy as np from nibabel.testing import data_path import nibabel as nib import sys lobar_map_filename = os.path.join(data_path, sys.argv[1]) concentric_map_filename = os.path.join(data_path, sys.argv[2]) lobar_map = nib.load(lobar_map_filename) concentric_map = nib.load(concentri...
6ac9d0d93754ca3c92d5b8dc63b71b7eb6ff18f7d4b6144f8def39ea74008174
Python
1,035
28
import numpy as np from nose.tools import eq_ from fancyimpute.knn import KNN from low_rank_data import XY, XY_incomplete, missing_mask def test_knn(): # get a baseline error from just zero-filling the missing entries sad_zero_fill = np.sum(np.abs(XY[missing_mask])) mad_zero_fill = sad_zero_fill / missi...
89583aa17fa100d3e14003ea0d57c3c156f011282d5c7601215a992317a6619a
Python
1,035
52
_dti_ = { "md": "dti_md", "rd": "dti_rd", "ad": "dti_ad", "fa": "dti_fa", "fe": "dti_fe", "trace": "dti_trace", "odf": "dti_odf", } _dki_ = { "mk": "dki_mk", "rk": "dki_rk", "ak": "dki_ak", "kfa": "dki_kfa", "mkt": "dki_mkt", "trace": "dki_trace", "odf": "dki_odf...
a9afb8327a4ada4fa6b33e29d82bd3b330eeed2944a4c516a349027410cc660b
Python
1,035
29
#!/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=['processing.zip']) tmp_dir = tempfile.T...
daeb56fd486fc84e3eea6ab9ed2e8b4676f764c13aa48a50972b0ad22de72f7d
Python
1,035
22
# Copyright (c) OpenMMLab. All rights reserved. from .ckpt_convert import swin_convert, vit_convert from .embed import PatchEmbed, PatchEmbedSwin from .inverted_residual import InvertedResidual, InvertedResidualV3 from .make_divisible import make_divisible from .res_layer import ResLayer from .se_layer import SELayer f...
f8ca5b29be0ae95a760db4202cb851ae8c893bbd534f89ef3c91f0333ef19c76
Python
1,036
30
#!/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']) fetch_data(get_testing_file...
154631a9e72f5aba960b79eef930c88f3213459e3b18caf0421811975e860977
Python
1,037
44
#!/usr/bin/env python """ Given two bed files print the number of bases covered 1) by both, 2) only by the first, and 3) only by the second. usage: %prog bed_file_1 bed_file_2 """ from bx.bitset_builders import binned_bitsets_from_file from bx.cookbook import doc_optparse def coverage(bitsets): total = 0 f...
6a245800f74fd2f13a4d40584f214c7654aef806eada1b529d42e0e9d0b0fa1c
Python
1,037
33
import mne import pandas as pd import numpy as np from scipy.stats import t import matplotlib.pyplot as plt import pickle from joblib import Parallel, delayed subs = [f"sub-{(i+1):02}" for i in range(20)] idx_ref_vs_out = 3 main_delta = [] for sub in [x for x in subs]: res = mne.read_evokeds(f"../bids_data/d...
d8d3a21452944ea870d1e88c15db04411552324a92828cc55e319be880da33f2
Python
1,037
22
import torch from torch import nn class LocalSpatialAttention(nn.Module): def __init__(self, in_channels, num_reduced_channels): super().__init__() self.conv1x1_1 = nn.Conv2d(in_channels, num_reduced_channels, 1, 1) self.conv1x1_2 = nn.Conv2d(int(num_reduced_channels*4), 1, 1, 1) ...
f566b37c9782f8ecb33bcb931df2ad052f78b66d1aadb481f6369dfbc5c7b248
Python
1,037
31
#!/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....
731636cc3e3a7ef0b9dc43adce60f97c719f1b14427b4acf49a3e91f18da8297
Python
1,038
27
# This file is part of connectome-manipulator. # # SPDX-License-Identifier: Apache-2.0 # Copyright (c) 2024 Blue Brain Project/EPFL """Null manipulation module - does not do anything.""" from connectome_manipulator import log from connectome_manipulator.connectome_manipulation.manipulation import Manipulation class...
53f7e565f1df86ec7ad60883464177b97fb46895694442c6d93bbeca95ce2e2f
Python
1,039
39
from __future__ import annotations import pytest from pytestqt.qtbot import QtBot from labelme._widgets._zoom_widget import ZoomWidget @pytest.fixture def widget(*, qtbot: QtBot) -> ZoomWidget: zoom_widget = ZoomWidget() qtbot.addWidget(zoom_widget) return zoom_widget def test_zoom_widget_defaults_to_...
866201ae6303ae1b9a2340ee1211dc2e76eb9630647d568936730614dee7b2c9
Python
1,039
30
#!/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=['filtering.zip']) tmp_dir = tempfile.Te...
b12fa2f345a02c24786c268857b7a027497fef667032098a11dd9fbbb726bff7
Python
1,039
25
"""genetate scheduler """ from torch.optim import lr_scheduler def get_scheduler(optimizer, cfg): if cfg['learning_schedule'][ 'main_scheduler'] == 'lr_scheduler.CosineAnnealingLR': main_scheduler = eval(cfg['learning_schedule']['main_scheduler'])( optimizer, T_max=cfg[...
04e5a7c9b4e85b160616378bd4a6d1975e3efa758c0a55405468426bb43de9d6
Python
1,040
29
from typing import List, Optional import torch from torch import Tensor import numpy as np from sklearn.utils.extmath import randomized_svd def dual_pca(x, y, dim=50, singular=False, backend='sklearn', use_gpu=True): assert x.shape[1] == y.shape[1] device = 'cuda' if torch.cuda.is_available() and use_gpu els...