sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
be5c0c60935bbda30c43a1d6934f7c8ea9068d42961e18722fbc8f33847af31c
Python
1,891
76
import matplotlib.pyplot as plt import numpy as np from matplotlib.gridspec import GridSpec import seaborn as sns def plot_scatter_labels(ax, data_proj, gen_data_proj, proj1, proj2, labels): ax.scatter( data_proj[:, proj1], data_proj[:, proj2], color="black", s=50, label=la...
1c15ef5af2273a8e5304831fdaa7113457be0887dfbf884237a48d420342d247
Python
1,892
56
#!/usr/bin/env python import pandas as pd import argparse import time import os import sys def tidy_promoter_file(baits,out_file,p_id): cols = ['chr', 'start', 'end', 'frag_id', 'genes'] bait_df = pd.read_csv(baits, sep="\t", names = cols).drop_duplicates() bait_df['genes'] = bait_df['genes'].str.replac...
b229eef2d40d737af4381ca1418e485d908cd8f76d09710e048632240199af7f
Python
1,892
64
import os import sys import traceback from pathlib import Path from typing import Dict import numpy as np import snapatac2 as sa2 import pyprojroot code_root_dir = str(pyprojroot.here()) pack_dir = f"{code_root_dir}/package/python" sys.path.insert(0, pack_dir) import utils #pyright: ignore # noqa: F401, E402 # * log...
ce7f5092de49168802fb18407df7d491207b26e9c929b525df3fe8542ea9158c
Python
1,893
66
"""A modified image folder class We modify the official PyTorch image folder (https://github.com/pytorch/vision/blob/master/torchvision/datasets/folder.py) so that this class can load images from both current directory and its subdirectories. """ import torch.utils.data as data from PIL import Image import os import...
e9fe59fd108167e80b1ee6b6a95560422bc05d9933371436316add4568fa5272
Python
1,893
59
import logging import os import tempfile import unittest from codecarbon.external.logger import logger, set_logger_format class TestSetLoggerFormat(unittest.TestCase): """Tests for issue #375 — set_logger_format() must not clear user-defined handlers.""" def setUp(self): self._original_handlers = lo...
232ef452a2ccd58efad30eadf0a394bf15a113c19186b5e950273a3376a958e3
Python
1,894
51
from torch import nn def get_norm(norm_type: str, num_features=None, spatial_dim: int = None, **kwargs): if spatial_dim is not None: assert 1 <= spatial_dim <= 3 if norm_type == 'none': return nn.Identity(**kwargs) if norm_type == 'bn': if spatial_dim is None or spatial_dim == 2: ...
2cf9630e7df6e258f1cb77e723d419aba764fdc51b4acf44dd1746ba415d25ef
Python
1,894
77
""" Tests to make sure evaluate module functionality works as expected. """ import pytest import eugene as eu import numpy as np import pandas as pd from pathlib import Path HERE = Path(__file__).parent eu.settings.logging_dir = f"{HERE}/_output" @pytest.fixture def sdata(): sdata = eu.datasets.random1000() ...
531298ae0a70c4c6e42b67249cbb69113440d31018ad7af6f42c7da07ed41b71
Python
1,894
58
import socketserver import sys import rpy2.robjects as robjects class MyTCPHandler(socketserver.StreamRequestHandler): def handle(self): # verbose server print("%s wrote:" % self.client_address[0]) # self.rfile is a file-like object created by the handler; # we can now use e.g. re...
aab2f9376ef35ee113514be9100f5bed9232d3369e2c7d541c6130e172c8489d
Python
1,894
90
from flask_login import LoginManager, AnonymousUserMixin from werkzeug.security import check_password_hash from database import ( UserModel, DatasetModel, CategoryModel, AnnotationModel, ImageModel ) login_manager = LoginManager() class AnonymousUser(AnonymousUserMixin): @property def dat...
c2f700ccdc4c4d190b88f9699d1979a96c8e5d1710722e83fa92a537e8ad6117
Python
1,894
27
#==============================================================================# # Author: Dominik Müller # # Copyright: 2024 IT-Infrastructure for Translational Medical Research, # # University of Augsburg ...
c341708282872e67823355ea462c52c7974333bfa8eeeb79f6bb3f2a5ad90c87
Python
1,894
72
class FeatureSetting(object): """ Class to hold parameters for encoded features Attributes ---------- skip_existing : bool True if not want to encode already existing features augment_tiles : bool True if apply augmentation sequence to tiles batch_size : int Size of batc...
ca072e91d0abed8f980132754eceb13adf5f9fa0cb0483b19946d169f2bbd583
Python
1,894
61
"""Invariant tests for public grouped option classes.""" from __future__ import annotations from dataclasses import FrozenInstanceError, fields, is_dataclass from typing import Any import pytest from torchlens.options import ( CaptureOptions, InterventionOptions, ReplayOptions, SaveOptions, Stre...
badbc60a807ee31c72ad4a5dbd9ce69dfe6894d3e4f05c1262b8de755b84ff01
Python
1,895
59
import sys from Bio.SeqRecord import SeqRecord from Bio.Seq import Seq from Bio import SeqIO from utils import get_CDS_loc, getLongestORF import pandas as pd import numpy as np import random def has_uORF(fasta_file,test_csv): test_df = pd.read_csv(test_csv,sep='\t').set_index('ID') is_coding = lambda x : x.st...
e00998935bfdae6a7de907e94a9a8320f73a183844fad355662a647770c83ead
Python
1,895
61
import numpy as np #import pumpprobe as pp import matplotlib.pyplot as plt import pyneuronsegmentation as pyns import struct import time folder = "/home/francesco/tmp/" folder = "/tigress/LEIFER/francesco/bleaching/20190311/pumpprobe_20190311_145010/" framesN = (np.uint32)(100) sizex = (np.uint32)(512) sizey = (np.ui...
285d7fba947bf1d7296d5b9f937bb6d63aa7520d1a2e1c69470623f93357b2f2
Python
1,897
50
"""Multiprocessing distributed data parallel support""" import torch import torch.distributed as dist import torch.backends.cudnn as cudnn import torch.multiprocessing as mp def get_local_ip_and_match(ip_list): import socket s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) ...
62098ec50857e2d51939b11d189508430dd86d9419b060ff764681160c5e8ef9
Python
1,897
56
import os import argparse import logging import autogluon.core as ag from gluoncv.auto.tasks import ObjectDetection from gluoncv.auto.estimators import SSDEstimator from d8.object_detection import Dataset os.environ['MXNET_ENABLE_GPU_P2P'] = '0' if __name__ == '__main__': # user defined arguments parser = a...
a01d796e4632741351887e96daf553aaa4e65269598ff479ccee3aa8a0caac12
Python
1,897
61
import numpy as np from gym import utils from gym.envs.mujoco import MuJocoPyEnv from gym.spaces import Box class Walker2dEnv(MuJocoPyEnv, utils.EzPickle): metadata = { "render_modes": [ "human", "rgb_array", "depth_array", ], "render_fps": 125, } ...
ba06e7006b8cbfaa44063aa7a5d3ce57c8db0cf2c34152d9bc2bd2ec900120eb
Python
1,897
61
import os import sys import sphinx_rtd_theme sys.path.insert(0, os.path.abspath("..")) # -- General configuration --------------------------------------------------- needs_sphinx = "2.0" # Nicer param docs suppress_warnings = [ "ref.citation", "myst.header", # https://github.com/executablebooks/MyST-Parser...
d59886231bb5a6f40dd90a4bf9fe9155214188951807130790189533c0d6e5af
Python
1,897
58
import numpy as np import pandas as pd from copy import deepcopy from collections import defaultdict import auggam.data as data import pickle as pkl from spacy.lang.en import English from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer if __name__ == '__main__': tok_simp = English().tokeniz...
5260b5d2226fdd28bec35fe0d484a8e074f51ab792212eaf245ec3737c794320
Python
1,898
77
import os import sys sys.path.append('..') import numpy as np import warnings import argparse import pandas as pd from data_load.dataloading import data_preparation_and_train """ Examples: python3 train.py -d data/wav -j data/folds.json python3 train.py -d data/wav -j data/guitars.json python3 train.py -d data/wav -...
2ef22f69745263da364e8d5f3f4076ee9536813b6fc909b5ae2405aac2307de8
Python
1,899
35
from irnlm.utils import check_folder from fmri_encoder.data import fetch_masker from irnlm.contrasts import plot_brain_fit if __name__=='__main__': ### # Replicating Fig6: Supra-lexical vs Lexical ### saving_folder = 'derivatives/Fig6' check_folder(saving_folder) masker = fetch_masker('deriva...
3d1bbc768d0345b4f934d56af3c2966737a03ac0ed4f4c685eaa1929d80d3b7b
Python
1,899
62
import logging import os import traceback from logging.handlers import RotatingFileHandler from click import get_app_dir from qtpy.QtCore import QObject, Signal class NoExceptionTracebackFormatter(logging.Formatter): """Custom formatter for formatting exceptions without traceback.""" def format(self, record...
60dd5ca569dba6d73f1f3a147b29439e8e6fba809bb45af145e378f1ab422d9f
Python
1,900
55
# -*- coding: utf-8 -*- """ Created on Wed Dec 15 19:11:53 2021 @author: Adrien Peyrache This script shows how to use pynapple to compute sleep reactivation, step by step. See pynacollada_replayExample for a real case example """ import pynapple as nap import pandas as pd import numpy as np import seaborn as sns; s...
aa66ca94baec5bcac47ecaf6ee0f1ffea4cbf2bb4febec0d1d6ba23bbaebbbd8
Python
1,900
58
import numpy as np import deepdish as dd from readout import load_results from digest import conds out_fname = 'nspikes.h5' def get_nspikes(cfg, ISIs, templ): ''' Retrieves the average number of spikes per trial, summed across the entire network. Structure: {STD: {TA: {cond: ndarray(nets*pairs*2)}}} ...
e09d3ef9f5c143a11d4b115c0d5d5093a81b22d5a46a8cbadd1604149912c06a
Python
1,900
58
from __future__ import annotations import random import numpy as np import panel as pn import pytest from larvaworld.portal.models_architecture.module_inspector_app import ( _ModuleInspectorController, module_inspector_app, ) @pytest.fixture(autouse=True) def _seed() -> None: random.see...
4354cb83ab01163ce26647026992326187bfb3347414a1a99b91aacb0cfbc9bf
Python
1,902
44
""" Predictors based on gammatone spectrograms Assumes that ``make_gammatone.py`` has been run to create the high resolution spectrograms. """ from pathlib import Path import eelbrain # Define paths to data, and destination for predictors DATA_ROOT = Path("~").expanduser() / 'Data' / 'Alice' STIMULUS_DIR = DATA_ROO...
4e9b4bb6fa9ec22285bf8c5004bec5a32d25b60ab1717acd38f98ed8f6ec63c4
Python
1,902
70
from __future__ import annotations from flask import Flask from flask import Request from flask import request from flask.testing import FlaskClient def test_max_content_length(app: Flask, client: FlaskClient) -> None: app.config["MAX_CONTENT_LENGTH"] = 50 @app.post("/") def index(): request.for...
c76e0865c4b37fa5fc834e66be0f327390edab1ec5ff8ae8037914290e323991
Python
1,902
44
import torch import numpy as np import torch.nn.functional as F def transI_fusebn(kernel, bn): gamma = bn.weight std = (bn.running_var + bn.eps).sqrt() return kernel * ((gamma / std).reshape(-1, 1, 1, 1)), bn.bias - bn.running_mean * gamma / std def transII_addbranch(kernels, biases): return sum(kerne...
cf4bbcb3dbae1617c04562979b10e330ca589b03e492bee9950001c347de439e
Python
1,902
64
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Copy warped MRI to the proper BIDS directory. @author: mikkel For information about NatMEG-PD please refer to the data descriptor: Vinding, M. C., Eriksson, A., Comarovschii, I., Waldthaler, J., Manting, C. L., Oostenveld, R., Ingvar, M., Svenningsson, P., & Lundqv...
102a3310d35a7d221a08bd50afe18fcd5963452c6315dc510ea6576c4cef22cc
Python
1,903
53
from collections.abc import Iterable from typing import ( TYPE_CHECKING, ) from galaxy.exceptions import RequestParameterInvalidException from galaxy.model import DatasetCollectionElement from . import BaseDatasetCollectionType from .paired import ( FORWARD_IDENTIFIER, REVERSE_IDENTIFIER, ) if TYPE_CHECKI...
368f25d398ab828d4e9c95dd60064b9bc7923572f1bdcfc4aa1429b12db34894
Python
1,903
43
# %% import os import numpy as np import nibabel as nib # %% def get_nii_orientation(target): affine = nib.load(target).header.get_best_affine() orient = nib.orientations.aff2axcodes(affine) orient = ''.join(orient) return orient # %% def reorient_vol(vol:np.ndarray, old_orient:(str,tuple), new_orient:(str,...
b126937afa2b8d61db8859f30450de2085fa1e4a1ee7db59b7417a9eae760557
Python
1,903
60
""" This script demonstrates how to plot membrane properties over time. Passive membrane properties are calculated for every sweep. Sweeps contain a brief hyperpolarizing square pulse from -70 mV to -80 mV. See comments in the memtest module for theory and implimentation details. """ import os import sys PATH_HERE = o...
1c22c0e4a8088f9f3de2cce980a429bde062bb66dcd679ac2da07a04b725f708
Python
1,904
66
import torch import torchio as tio from torch.nn.functional import softmax from fit.fit import Fit class BaseFit3D(Fit): def __init__(self, device, amp=False): super().__init__(amp, device) def iterate(self, data, model, criterion, is_train=False): x, y = data['ct'][tio.DATA].to(self.device)...
25237de12a6abefe5cd4a0f3068d65bb2c3cde627f689ddd7cded07279ac4fa4
Python
1,904
39
import unittest from unittest.mock import Mock from random import choices from svim.SVIM_COMBINE import generate_insertion_consensus from svim.SVSignature import SignatureInsertion, SignatureClusterUniLocal class TestSVIMConsensus(unittest.TestCase): def setUp(self): self.nucleotides = ["A", "C", "G", "T"...
b4291a7c7da01f9f061f840ebf94460c60606d0cc14b278c7067448df3ae1e90
Python
1,904
42
from pl_bolts.datamodules.async_dataloader import AsynchronousLoader from pl_bolts.datamodules.binary_emnist_datamodule import BinaryEMNISTDataModule from pl_bolts.datamodules.binary_mnist_datamodule import BinaryMNISTDataModule from pl_bolts.datamodules.cifar10_datamodule import CIFAR10DataModule, TinyCIFAR10DataModul...
6d01857eb321243d528ad52dcb70576621266c25db8d72d957ae71577fa7bf15
Python
1,905
64
# EUGENe on sdata def count_kmers_sdata(sdata: SeqData, k: int, frequency: bool = False) -> dict: """ Counts k-mers in a given sequence from a SeqData object. Parameters ---------- sdata : SeqData SeqData object containing sequences. k : int k value for k-mers (e.g. k=3 generate...
e4661418cea24684385bcf77da7c438b702820143472b5192fdc69638defcc32
Python
1,905
55
"""Loss functions for Object Detection task.""" from torch import Tensor from pl_bolts.metrics.object_detection import giou, iou def iou_loss(preds: Tensor, target: Tensor) -> Tensor: """Calculates the intersection over union loss. Args: preds: batch of prediction bounding boxes with representation...
f1424f65620e26e7ab0533bec690ee68a97feab36523287fd044aff0a586cfa1
Python
1,905
63
# This example requires the following dependencies to be installed: # pip install lightly # Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import pytorch_lightning as p...
6f0ffeb94fcf14520f84782ace18ebccfb2bea736d3d62b20d6e4a6d78c05383
Python
1,906
59
"""Subprocess entry point for isolated viz-identity DOT generation. Renders every forward-DOT golden in ONE fresh interpreter, constructing both models BEFORE the first capture so no model ctor ever runs on wrapped torch: in-process generation inside the pytest session constructed models on whatever wrap state earlier...
afa061aed825d73ccdc4528ccbe579d6e530381fa5c578003396bf287b9626f4
Python
1,907
60
from pyrosm.data_manager import get_osm_data from pyrosm.frames import prepare_geodataframe def get_network_data( node_coordinates, way_records, tags_as_columns, network_filter, bounding_box, slice_to_segments, filter_type="exclude", keep_metadata=True, osm_keys="highway", step...
df5d956b2aca57f76d27c50d7836a18a0e0f972c1e9971bc52eccd00da146605
Python
1,907
87
import array import pytest import rpy2.rinterface as ri ri.initr() def test_init_from_bytes_in_seq(): seq = (b'a', b'b', b'c') v = ri.ByteSexpVector(seq) assert len(v) == 3 for x, y in zip(seq, v): assert ord(x) == y def test_init_from_seq_of_bytes(): seq = (b'a', b'b', b'c') v = ri...
17f1436546d9ace3635ef5c70278e459ee16df463219236adc55d42d24a17423
Python
1,909
43
# 05/23/2023 Fengyao Yan # Make semi silico data from the cmp dataset. import os import pandas as pd from multiprocessing import Pool, cpu_count from decide_organ import _gen_comp from decide_organ import master data_raw = '../../data/raw' cpu_count = 12 if not os.path.exists(f'{data_raw}/tissue_cmp_expression.csv'...
3d25c4e872624e764d1809a84cfe0ee62d4b911c5a1286c3b5c6e11dfdd10bfd
Python
1,909
58
import os import warnings import h5py import numpy as np import scanpy as sc from scbig import run_scbig, preprocess, setup_seed warnings.filterwarnings('ignore') import time from memory_profiler import profile @profile def run(adata): adata = run_scbig(adata) from memory_profiler import memory_usage m...
ccaaf2d2c765a646161bb344cf1e290123da1217f4b8e13342a05cf88f26d652
Python
1,909
52
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jan 12 12:22:02 2022 @author: mikesha """ import torch def find_rigid_alignment(A, B): """ See: https://en.wikipedia.org/wiki/Kabsch_algorithm 2-D or 3-D registration with known correspondences. Registration occurs in the zero centered ...
e337c850886e53b5b57fd6e295fb5aec191ef6ed5fc1eb5e502041df58901d63
Python
1,909
60
from pathlib import Path import numpy as np from tensorflow.keras.models import load_model, Model from barriernn_p.input_generation import create_meta_dataset_predictions from tqdm.autonotebook import tqdm #%% ----- Parameters ----- ######### datasets = ['dataset_2208_synth', 'dataset_2208_traj'] base_name_dir = "2208...
928658d51a0cb867f003ffc61513c6b9c767957be4195c27c9569ae381b6bd87
Python
1,910
51
import os, math, operator, sys import numpy as np def norm(v): '''Calculate the norm of vectors stored in an array''' # Example: nx3 array containing the coordinates of n 3D vectors # v = np.array([[1, 2, 3] # [...] # [4, 5, 6]]) # norm(v) will return array([3.741657...
c746dc16c847fe5ad1899891efe53de051bb4341452372cfc68b942c2cc17db7
Python
1,910
54
import torch import numpy as np from os.path import join from pathlib import Path from torch.utils.data import Dataset from torch.nn.utils.rnn import pad_sequence class DSet(Dataset): ''' LibriSpeech parser which takes raw LibriSpeech structure''' def __init__(self, path, split): # Setup self....
e55dec50a8ce5f16ac5461d52998dfe152559e8c285c618f347123ae6881a5de
Python
1,910
61
from typing import Iterable import numpy as np import tensorflow as tf from angorapy.analysis.util.sindy import compute_z_derivatives, sindy_library_tf, library_size def build_encoder(layer_sizes: Iterable[int]): encoder = tf.keras.Sequential([ tf.keras.layers.Dense(size, activation="relu") for size in ...
1f6214205661f79b21fbbfba1b0b39e5cb7e02b82ca4dc036c6926c69a11d871
Python
1,911
53
# ------------------------------------------------------------------------------ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. # ------------------------------------------------------------------------------ import torch import torch.nn as nn import torch.nn.functional a...
f94c2b926f25816ee98e77441b19008c5e51e0cdcb1c55ce87d39eb734b05c2d
Python
1,911
58
# -*- coding: utf-8 -*- # Copyright (c) 2016-2018 Braintech Sp. z o.o. [Ltd.] <http://www.braintech.pl> # All rights reserved. """Module providing methods for packing and unpakig tags from dictionary: 'unpack_tag_from_dict', 'pack_tag_to_dict'.""" def unpack_tag_from_dict(p_dict): """ For given dictionary de...
fbc01a7d200c45f9969dfdaec33f3b73b3aa042d501ec7e8e3df409113f77016
Python
1,911
70
import tensorflow as tf import tensorflow_datasets as tfds from tensorflow.keras.models import load_model from gradient_accumulator import GradientAccumulateModel def normalize_img(image, label): """Normalizes images: `uint8` -> `float32`.""" return tf.cast(image, tf.float32) / 255., label def test_train_mn...
0972e15dd6a281dac843c61b7a36c6e65c8da3aaf48b228941c308c016602798
Python
1,912
75
from ..preprocess._helpers import _get_vocab import numpy as np import pandas as pd TINY = np.finfo(float).tiny def pfm_to_df( pfm, vocab: str = "DNA", ): vocab = _get_vocab(vocab) pfm_df = pd.DataFrame(pfm, columns=vocab, index=range(pfm.shape[0])) return pfm_df def pfms_to_df_dict( pfms, ...
4588f46aecf2d6c817254920d477bb251ab5a17fc0ee80a2e5255156ef52bb9d
Python
1,912
55
import sys # setting path sys.path.append('../TM2_segmentation') import os import numpy as np import nibabel as nib import itk import pandas as pd import tarfile from dateutil import parser from datetime import datetime from scripts.preprocess_utils import find_file_in_path, register_to_template # load metadata file...
b6e4c72612a227b3b84454522aa48a65cc9fdecdce6500577ae953e1a1d19ae5
Python
1,912
71
"""Tests for specparam.utils.select""" from pytest import raises from specparam.utils.select import * ################################################################################################### ################################################################################################### def test_group...
1900b1bb94cf8f487a25aefcdc6c4561f19bcd5fbcad8e07088ee7bd1bab12de
Python
1,915
64
from permacache import permacache, stable_hash import tqdm.auto as tqdm import torch import numpy as np from modular_splicing.data_for_experiments.standardized_sample import ( calibrate_thresholds_on_standardized_sample, ) from .data import dataset_for_species def compute_thresholds(model, species): _, path...
a0ff97fe4d2f6d20780b0955e06415541010f6e23ff1fac589c75ee728556007
Python
1,915
52
# -*- coding: utf-8 -*- # tests for toy_graphs.py """authors: Thomas Bonald <bonald@enst.fr> Quentin Lutz <qlutz@enst.fr>""" import unittest from sknetwork.data.models import * class TestModels(unittest.TestCase): def test_shape(self): n = 10 for model in [linear_graph, linear_digraph, cyclic_gr...
4461dbd80d27abdc9abcad4ac9b61207f72731b93092d1dade8235404ab0829b
Python
1,916
69
import codecs import os import sys from setuptools import find_packages, setup if sys.version_info < (3, 6): sys.exit("Sorry, Python < 3.6 is not supported") def read(rel_path): here = os.path.abspath(os.path.dirname(__file__)) with codecs.open(os.path.join(here, rel_path), "r") as fp: return fp...
6a228d223bd62912625fc8b67c17f1d621501557c5b4d7480a4eddeeb952a44c
Python
1,916
45
""" Théo Gauvrit Mars 2022 compute Mean Absolute Error on the evoked response(EPSP) of two groups of recordings. """ import numpy as np import pandas as pd import pyabf from sklearn.metrics import mean_absolute_error from Utils import browse_directory def mae(group_name, group_path, sampling_freq, stim_timing=1.04, ...
00f24a6401a30e9dd6a0c7f9bf0ae9d47385dfb27d5f0a0b1300f66575e3b71b
Python
1,917
69
import subprocess import os if __name__ == "__main__": # Import config try: from config import python_path, lib_path except: from config_template import python_path, lib_path if python_path is None: raise ValueError('"python_path" is not specified') if lib_path is None: ...
560e740c7a27a1455c7424fd5b80733205e143ccf61cf9452c965e9ed4374e98
Python
1,917
62
#!/usr/bin/env python import sys from Bio import SeqIO def index_genbank_features(gb_record, feature_type, qualifier): answer = [] for (index, feature) in enumerate(gb_record.features): if feature.type == feature_type: start = feature.location.start.position end = feature.loc...
29704779beab93fb68257d5161892c27890c447e80d762a72f1f675eb3784db4
Python
1,918
61
""" Portal apps and helpers for working with datasets. """ from __future__ import annotations from importlib import import_module from typing import Any __all__: list[str] = [ "ImportRequest", "RawDatasetCandidate", "WorkspaceDatasetRecord", "build_workspace_proc_folder", "discover_raw_datasets",...
495b3161cb1dcdac08d5f142ac1732b112e155b1d82b62389b0704ef2080166b
Python
1,918
54
from scipy.stats import ttest_1samp, ttest_ind from mne.utils import check_random_state import numpy as np def _permutation_1samp(X, n_permutations = 10000, alternative = 'two-sided', seed = None, statfun = None): ''' computes the permutation distribution of p-values from ttest_1samp ''' _, p_obs = ...
a0550363d99bc41db488cd68467e69e0b09e59be14c05492b31002f7ef20a24e
Python
1,918
53
import pandas as pd import pysam import csv import argparse def parse_arguments(): parser = argparse.ArgumentParser() parser.add_argument('-i', '--input', required=True, type=str, help='File of indel mutations') parser.add_argument('-b', '--blacklist', ...
a44a1d42ddc4db2a23805e8d07f47678442d7582f7a0f04eb737b5a0413a2101
Python
1,918
51
"""Unit tests for LarvaDatasetCollection.get_colors().""" from __future__ import annotations from types import SimpleNamespace import pytest from larvaworld.lib.process.dataset import LarvaDatasetCollection from larvaworld.lib import util def _fake_collection(colors): datasets = [SimpleNamespace(config=Simple...
a9a67921eb4698f6e237b8825b93636c0aed61d80841f423a8f099efa4e5585e
Python
1,918
58
#!/usr/bin/env python #========================================================================= # # Copyright NumFOCUS # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://...
bf17c31dd54ef8ab84fc73a2e8cf583c2696a1cd18f47732f3582197cdb7df8c
Python
1,918
60
from tensorflow.keras.layers import Dropout, MaxPool1D, MaxPool2D, Conv1D, Conv2D, Dense from tensorflow.keras.models import load_model from pathlib import Path def writeShape(shape): return ", ".join(str(s) for s in shape[1:]) def getName(layer): if isinstance(layer, Conv2D): return "Convolution 2D"...
2fe0c9ff1ce990aef032c6eed68d545903315ecd78f91cfdd05aecde75612d1b
Python
1,919
59
#!/usr/bin/env python """Tests for ClusterPlot.""" import unittest from stlearn.adds import row_annotations from tests.utils import path_for_test_data, read_test_data class TestRowAnnotations(unittest.TestCase): """Tests for row annotations.""" @classmethod def setUpClass(cls): cls._base_adata...
5548b7324004ef83fd9724843d785be58da628915a80a76964b91a6d2c390b4d
Python
1,919
67
import os from typing import Optional from omegaconf import DictConfig from pytorch_lightning.callbacks import ModelCheckpoint, ModelSummary def create_checkpoint_callback( save_last: bool = False, save_top_k: int = 0, monitor: str = "loss", dirpath: Optional[str] = None, ) -> ModelCheckpoint: ""...
c3eed4c35e3fd51cc14eb259a8d7c39905d105e38cc22fccdae9625295942d9a
Python
1,920
58
''' Processes datasets for different acceleration factors author: obanmarcos ''' from config import * from concurrent.futures import process import os, sys # Where am I asks where you are sys.path.append(where_am_i()) import argparse import numpy as np import matplotlib.pyplot as plt import pandas as pd from utiliti...
255087b2a12682f8a89710ba4dc51b88f49dd027ca4315b861a8b1a2a7bf45ce
Python
1,921
70
import argparse from io import BytesIO import multiprocessing from functools import partial from PIL import Image import lmdb from tqdm import tqdm from mxnet.gluon.data.vision.datasets import ImageFolderDataset # pylint: disable-all def resize_and_convert(img, size, quality=100): img = img.resize(size) buff...
38d4f75ab83e2959865830063faa33bbe5ffbb32ee73a0874ce1c02d4037fc30
Python
1,921
67
from keras.src import ops from keras.src.backend.common import standardize_dtype DTYPE_TO_SIZE = { **{f"float{i}": i for i in (16, 32, 64)}, **{f"int{i}": i for i in (8, 16, 32, 64)}, **{f"uint{i}": i for i in (8, 16, 32, 64)}, "bfloat16": 16, "bool": 1, } def dtype_size(dtype): size = DTYPE_...
db7c9aafe312e85a306b0de1177dedfa194c2bfef58bc8558f0fc1b37fb85c40
Python
1,921
60
"""Benchmarking module for AlignmentFile functionality""" import os import subprocess import pysam from TestUtils import BAM_DATADIR def count_number_lines_with_samtools(fn): os.system("samtools view {} | wc -l > /dev/null".format(fn)) return 3270 def count_number_lines_with_samtoolspipe(fn): with sub...
df0e2efbb50b8bc6e04b245fe175fd0a5f9037278d70c89faedd6f5a0b23778f
Python
1,921
47
from tensorflow.keras.layers import UpSampling3D import nibabel as nib import pandas as pd import os def remove_extra_skull(patient): # get scan file names print(f"PATIENT {patient}") nccts = ["/"+file for file in os.listdir("NCCT")] cta = ["/"+file for file in os.listdir("CTA")] ncct...
19d8f05bf3ea9fb579b4de2f3ddff60b9d53a68b660d40d705b80c7ec07d2065
Python
1,922
50
from neurogym import _SB3_INSTALLED from neurogym.envs.native.annubes import AnnubesEnv from neurogym.wrappers import Monitor def test_activation_traces(n_trials: int = 10): """Tests for neuron activation traces.""" session: dict[str | tuple[str], float] = {"auditory": 0.5, "visual": 0.5} catch_prob = 0.2...
76de35be4d43692d47f8bac10426577c84a3d60e4f2c071ac4d4cd33bd2f8f5b
Python
1,922
72
import numpy as np import torch def _2d_morph_conv(seg_oh, selem=None): assert torch.is_tensor(seg_oh), 'input seg must be a torch tensor' assert len(seg_oh.shape) == 4, 'seg must be 4d' nz = seg_oh.shape[1] if selem is None: selem = torch.tensor([[0, 1/5, 0], [1/5, 1/5, 1/5], [...
9edb01fefb2375bbcf2773ba64c21fa411ed7c388997de5c1e200ea9e7e6116a
Python
1,922
63
import numpy as np import math import statistics import pdb # ------------------------------------------------------ # 3d distance def distance3d(a, b): d = math.sqrt(math.pow(a[0] - b[0], 2) + math.pow(a[1] - b[1], 2) + math.pow(a[2] - b[2], 2) * 1.0) # print("Distance is...
c2aed18c41704242e1482e41b6740bd0dc6d4d6e447581fad58164ef97e15161
Python
1,922
53
import mxnet as mx from mxnet import nd, autograd, gluon from mxnet.gluon import nn, Block from gluoncv.utils.parallel import DataParallelModel, DataParallelCriterion def test_data_parallel(): # test gluon.contrib.parallel.DataParallelModel net = nn.HybridSequential() with net.name_scope(): net.add...
cf212bc2794285e5d65771941af6061c20eb360cf20dceaae49f9c1ba6211dc2
Python
1,922
55
# -*- coding: utf-8 -*- """ General framework regrouping the different splitting strategies possible to integrate in the regression analysis pipeline. =================================================== A Splitter instanciation requires: - out_per_fold: the number of run to left out for the test set. It makes use ...
f9ab4fbd243c61690c3966090a457d3679cfff1860377e793f2cd9826fb6cc0c
Python
1,922
56
import os import numpy as np import pandas as pd import nibabel as nib from os.path import join as pjoin from magicbox.io.io import CiftiReader, save2cifti from cxy_visual_dev.lib.predefine import proj_dir, mmp_map_file,\ Hemi2stru, LR_count_32k anal_dir = pjoin(proj_dir, 'analysis') work_dir = pjoin(anal_dir, 'AH...
02b9835760bd30a15ac2be8a094bca19bbb32e82da6000b4628637794cad696e
Python
1,923
57
import glob from ase import io as ase_io from pymatgen.io.ase import AseAtomsAdaptor from pymatgen.io.qchem.outputs import QCOutput from instance_mongodb import instance_mongodb_sei if __name__ == "__main__": """Store all data in representative xyz files for easy visualisation.""" db = instance_mongodb_sei...
857f2d904b873a83196b74b35ad80b7a24661f1fa44a32e5283782e802f7b39d
Python
1,923
55
import warnings import pandas as pd import numpy as np from numpy.random import default_rng from scipy.stats import expon, weibull_min warnings.simplefilter("ignore") def synthetic_data_random(n_samples=100, as_dataframe=True): coefficients = [2, 4, 6] rng = default_rng(seed=0) x1 = rng.standard_normal((...
c17b60de5f5045b2d9db47e3cd2abfab2e02630751b8e81934c86041152e60bd
Python
1,923
51
"""W051-TRACK / AUD-CODE 2.15: an ``echo=`` sink-open failure must release the capture reservation on the error path. The echo sink opens its path eagerly; before the fix the open ran between the capture-slot claim and the forward's own guard, so holding the exception (REPL ``sys.last_traceback``, pytest ``excinfo``) ...
d2dbcc765a7c7bf5a8ff6cc062cc715005bb36d2bc81f694207b131b61a4a915
Python
1,923
71
import pandas as pd import os from sqlalchemy import create_engine import codes3d import snps import sys def get_snp_list(test_dir): ''' rs1794265 # biallelic rs1689510 # at start of MboI fragment; ensures fragments are 0-based ''' return pd.read_csv( os.path.join(test_dir, 'test_snps.txt'...
f5f9f45d66238b9f1515795957fb9eaaa83387cec5d5511104382fecbad3b8ca
Python
1,923
70
from modular_splicing.models_for_testing.width_models import ( AM_21, AM_17, AM_13, AM_13_more_layers, AM_13_secondary, AM_13_secondary_control, AM_13_flanks, AM_13_reprocessed_21, AM_13_reprocessed_45, ) normal_spec = dict( type="H5Dataset", sl=5000, datapoint_extractor...
669616a2bc3062cd46b9e06cd04c79d8a2b5004f978ef2ff20f928d8939106af
Python
1,924
85
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ ================================= BIDS: MICA structural processing ================================= Preprocessing workflow for structural T1w. This workflow makes use of ANTS, FSL and Freesurfer Atlas an templates are avaliable from: https://github.com/MICA-MNI/mi...
ecffdfd9286c1e0e6ddd006c6ec24279ee7b85248a0f26c101b0fece99e730bf
Python
1,925
55
import os import argparse import logging import autogluon.core as ag from gluoncv.auto.tasks import ImageClassification from gluoncv.auto.estimators import ImageClassificationEstimator from d8.image_classification import Dataset os.environ['MXNET_ENABLE_GPU_P2P'] = '0' if __name__ == '__main__': # user defined ...
54c1347fb224b01c3253b9bc5df4ec57e33f7d4500f8feafa67a4ec327ceaa13
Python
1,926
67
import argparse from chembl_structure_pipeline import checker, standardizer def load_mols(input_file): """ Returns a list of strings, each a molblock """ with open(input_file) as f: mols = [ "".join(("\n", mol.strip())) for mol in f.read().strip().split("$$$$\n") ] ret...
a2b1291f49f6c3057adfa158f63f1ea236e7208817e4d3ae63cbc02e314457da
Python
1,926
55
"""Detection Dataset from LST file.""" from __future__ import absolute_import import os import numpy as np import mxnet as mx from mxnet.gluon.data import Dataset from ..recordio.detection import _transform_label class LstDetection(Dataset): """Detection dataset loaded from LST file and raw images. LST file i...
beb349406ffa8a6f61449d9937cd19ccf0e571e907b117a0dfbc7eb6ef641c60
Python
1,926
52
# LICENSE # # _This file is Copyright 2018 by the Image Processing and Analysis Group (BioImage Suite Team). Dept. of Radiology & Biomedical Imaging, Yale School of Medicine._ # # BioImage Suite Web is licensed under the Apache License, Version 2.0 (the "License"); # # - you may not use this software except in compl...
05fb6456e9ee36cb236cbdbade391acc0438dc53d8e1b72a60d910b958f17a63
Python
1,927
60
import numpy as np import pytest from CEST.src.CEST import CEST from Metrics.src.CEST import mtr_asym from test_support_function.src.CEST import generate_Z_3D def test_OF_0(): # Test CEST with and water offset of 0 ppm wassr_img = generate_Z_3D(img_size=(2, 2), dyn=21, ppm=1, a=1, b=0, c=1) cest_img = ge...
150102c6869d99ce6d9b45ee031ad152e97c0f4f5071961e4b4833a3e88cd01e
Python
1,927
53
"""Smoke tests for default queue type fallback behavior. Tests that Celery respects task_default_exchange_type and task_default_queue_type when using implicit routing. """ from __future__ import annotations import pytest import requests from pytest_celery import RESULT_TIMEOUT, CeleryTestSetup from requests.auth impo...
35a182900387b94f159dc644c65c16d1e51d6f68467992a519e3ba407dbd79d0
Python
1,927
74
"""Discover within a submodule before choosing a finer selector. What this demonstrates ---------------------- Use ``tl.in_module("block")`` to restrict discovery, then compose it with ``tl.func("relu")`` for the intervention target. How to run ---------- ``python examples/intervention/09_submodule_discover_first.py`...
b462bed70434c8452ec29b9dca7acd366d21d97227e17b0b8bb93d14e758fc49
Python
1,927
52
import pandas as pd import numpy as np def aa_encoding_tensors(germline_cdr3_csv, aa_order, v_gene_list, j_gene_list, max_cdr3_len): """ Build tensors that one-hot-encode the germline sequences that extend into the CDR3. V genes are left-aligned, while J genes are right-aligned. """ aa_list = list...
b797ad2e4b2b53727c88437439af04f05d077f9954a83d64143a8e83b768fd26
Python
1,927
53
import sys # setting path sys.path.append('../TM2_segmentation') import os import numpy as np import nibabel as nib import itk import pandas as pd import tarfile from dateutil import parser from datetime import datetime from scripts.preprocess_utils import find_file_in_path, register_to_template # load metadata file ...
eb84e124f099d4a012092ac5fae915238f36ebf44d2d734b4772d84f6e6ae05a
Python
1,927
64
from sys import argv from msp import MSP msp = MSP() msp.file = __file__ msp.seed = int(argv[1]) msp.architecture["num_motifs"] = 82 msp.architecture["sparse_spec"] = dict(type="SpatiallySparseAcrossChannels") msp.architecture["motif_model_spec"] = dict( type="AdjustedMotifModel", model_to_adjust_spec=dict( ...
211061b4b5fed20981083e7ecf59a04fe26515975cf21c272da32b4a628c21ab
Python
1,928
69
import torch import torch.nn as nn from einops import rearrange from SRDTrans.SpatioTemporalTrans import SpatioTemporalTrans from SRDTrans.MainFrame import MainFrame, SingleConv class SRDTrans(MainFrame): def __init__( self, img_dim, img_time, in_channel, ...
6965f21912a009088963f75bc9d99c381229ab4604dc23e28086dba84ca4bb4b
Python
1,928
46
# -*- coding: utf-8 -*- """ Created on Tue Sep 20 14:35:19 2022 This is the Updated Version for easy access for multiple choses. 23/09/22 -> Starts Parallel Processing of Multiple Scripts -> "_ImpPlot=True" Plots the Impedance Plot -> "_SRT_Plot=True" Plots the Semi Real Time Data ...
99cd8eba4f7e735b2277d36b7b7d15b7ec66862197a4323c3f1b4bdc35c57b29
Python
1,928
58
import numpy as np import time from getUi import getUi from noiseless_PutM import noiseless_PutM def manfit_km17(data, d, r, X, opts): # This code is to implement the LPCA method in # Mohammed, K. and Narayanan, H. (2017). Manifold Learning Using Kernel Density Estimation and Local Principal Components...
fed91a82d28750fe1bc46f629ef4018e41453c676995b8672658b9ff88d73b8b
Python
1,929
48
"""Bounding-box helpers: validate/normalise a box, reduce it to its bounds, flag in-box coordinates, and read back the in-box node ids spilled per shard.""" import numpy as np from pyrosm.utils import validate_bounding_box def _normalize_bounding_box(bounding_box): """``bounding_box`` checked and normalised as `...
0b8f42caa6fcae31118f45da36542cfa62f93887caf3cf319e21f25d124c1895
Python
1,930
59
#!/usr/bin/env python '''Given desired set of parameters, generates all configurations obtained by enumerate each parameter individually (continuous are discretized). ''' import sys, re, MySQLdb, argparse, os, json, subprocess import pandas as pd import makemodel import numpy as np from MySQLdb.cursors import DictC...