sha256
stringlengths
64
64
language
stringclasses
27 values
size
int32
1
491k
lines
int32
1
21.8k
content
stringlengths
1
200k
769ce7dc5b836dbd9695c33bf3028310a87dcda40b4aeb2ebf89f43687c82598
Python
1,794
53
import json import os import numpy as np import pytest from oneqmc import convert_geo INPUT_FILES = { "yaml": "../data/cyclobutadiene/square.yaml", "xyz": "test_square.xyz", "json": "test_square.json", } @pytest.mark.parametrize("from_fmt,to_fmt", [["yaml", "xyz"], ["yaml", "json"], ["json", "xyz"]]) d...
dbf47281ee7f70dbc1578964ee252b3b2dda4e97547055b44e70ffaa13ca7919
Python
1,796
52
# 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 os import glob import argparse from utils.dedup import deup import sys WORKDIR_ROOT = os.environ.get('WORKDIR_ROOT', None) if WORKD...
628c063affadc3b22890ad2db42dde72d519eb073f143c5243e518dcff4a3cd9
Python
1,797
57
import subprocess from anarci import anarci def get_seq(pdb_chain): command="grep -A1 %s data/databases/pdb_seqres.txt" % (pdb_chain) output = subprocess.getoutput(command) return output.split("\n")[1] def parse_anarci(in_seq): try: command="ANARCI --scheme aho -i %s" % in_seq outpu...
961ce77d00dd0b72f106873bc74a609e113d66fc17f095db82d951c4f51f534d
Python
1,797
46
import matplotlib.pyplot as plt import loompy from .colors import colorize def embedded_velocity(ds: loompy.LoomConnection, out_file: str = None) -> None: plt.figure(figsize=(12, 12)) if "UMAPVelocity" in ds.ca: plt.subplot(221) xy = ds.ca.UMAP uv = ds.ca.UMAPVelocity plt.scatter(xy[:, 0], xy[:, 1], c=col...
c9b459cd0e5a172be07e430ef971237d8329aabf688875dcc51916abd8fb8b07
Python
1,798
53
# @license # Copyright 2020 Google Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
147d286b6a2ef2857e5140f20f1460e4f5a0d22908872bc86ff02453e09d71db
Python
1,800
55
import os import urllib2 from os.path import join, basename, dirname, exists current_dir = dirname(__file__) processed_dir = 'processed' data_dir = 'external_validation' processed_dir = join(current_dir, processed_dir) data_dir = join(current_dir, data_dir) if not exists(data_dir): os.makedirs(data_dir) def d...
82d7d7f4f61091b7b04cd593defa6bc384475c64f5eb68c85a0184f2c8a6d338
Python
1,801
56
# @license # Copyright 2017 Google Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
12efc1bade39612f2ad527497f0a0beeeb6484318c712ef4d2069c23ce8d2134
Python
1,802
68
from pathlib import Path import click import xarray as xr def status_dataset(dataset: str) -> None: click.secho(f'\n{str(dataset)}', bold=True) dataset_path = Path(dataset) if not dataset_path.exists(): click.secho('Dataset does not exist!', fg='red') return try: chunking =...
e654a0bf36ce2c691ab0711e8065f64887e0789dfa58809ddd67e71f95a68bf6
Python
1,802
57
import torch import torch.nn as nn import torch.nn.functional as F class Swish(nn.Module): # @staticmethod def forward(x): return x * torch.sigmoid(x) class Hardswish(nn.Module): # export-friendly version of nn.Hardswish() @staticmethod def forward(x): # return x * F.hardsigmoid(x) ...
edfc9110d65057f921dc97089508b0ace0f5c4ef3d38a57efe0b2365f882aef5
Python
1,802
58
import matplotlib.pyplot as plt import glob, os import pandas as pd import seaborn as sns fig, ax = plt.subplots() # Define the folder path containing the text files folder_path = '/content/drive/MyDrive/red_blue/0.66_n/' noiselist = [] noiseA =[] val = [] # Iterate through all files in the folder for fi...
4ba405574a16330995c5c307ce6c1b7182b8f916b81764bf92d9e1607992ca81
Python
1,804
58
import torch import numpy as np def fori_loop(lower, upper, body_fun, init_val, att, mutation, target): val = init_val for i in range(lower, upper): val, att, mutation, target = body_fun(i, val, att, mutation, target) return val def fori_loop_reinforce_learn(lower, upper, body_fun, init_val, att...
d7da431c6678d874f4ecc4ede18f512c2e91f08d8f57e5d02250a8f590926487
Python
1,804
59
# This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import os import shutil import sys import tempfile import unittest from typing import Optional from unittest.mock import MagicMock class TestFileIO(unittest.TestCase): _tmpdir: Optional[st...
f8f10343191427bb679eea4841e60661c280c4d304677941871f778fd4005bbb
Python
1,805
71
import torch from torch.utils.data import Dataset, Subset import pandas as pd import numpy as np from typing import Union from pathlib import Path from rinalmo.data.alphabet import Alphabet from Bio import SeqIO class SpliceSiteDataset(Dataset): def __init__( self, ss_csv: Union[str, Path], ...
dd163b2d9fed188e8fa80bb85fcd5e65b7884aa74b2351f99dcaa60f85f1842b
Python
1,809
73
#%% from ambiguous.dataset.dataset import DatasetTriplet from torch.utils.data import DataLoader import matplotlib.pyplot as plt #%% # Manually load dataset import numpy as np idx=2000 set_type='train' img_size=28 image = np.load(f'/Users/guillaumeetter/Documents/datasets/amnistV2/{set_type}/{idx}_image.npy') labe...
4a5d2ddb436e17feafd86f448ba274a85965663f532b531223c6c34dfcb60576
Python
1,811
76
import argparse import os import csv import numpy as np from process_pretrain_data import get_kmer_sentence def Process(args): SCAN_LIST = [int(500/(args.slide-1))*i for i in range(args.slide)] old_file = open(args.file_path, "r", encoding="utf-8-sig") old_lines = list(csv.reader(old_file, delimiter="...
e49ddc39e9cc0a780fb78e7d68ad8e5737bdd6d649f45e570fc70e8fdf91294e
Python
1,811
48
from nipype.interfaces.base import BaseInterface, BaseInterfaceInputSpec, traits, File, TraitedSpec from traits.api import List # this VIF interface code was developed based on a draft from ChatGPT class VIFCalculationInputSpec(BaseInterfaceInputSpec): design_matrix = File(exists=True, desc='Path to design matrix ...
e95de45e2d9ff44da817efcb7a3bef66a86c0cd9030b8e2f934533dd0cf03fcf
Python
1,811
89
""" NeuroVFM: Vision Foundation Model for Medical Imaging A comprehensive framework for self-supervised pretraining and supervised fine-tuning of vision transformers on 3D medical imaging data (MRI, CT). """ __version__ = "0.1.0" # Data loading and preprocessing from .data import ( DatasetMetadata, CacheMana...
4b213e36146a18ed5e6f987072243bd78e2d9758b40b0fda8a1b5d88edf1b6a1
Python
1,812
63
import argparse import neuroglancer import neuroglancer.cli import numpy as np def add_example_layers(state): a = np.zeros((3, 100, 100, 100), dtype=np.uint8) ix, iy, iz = np.meshgrid( *[np.linspace(0, 1, n) for n in a.shape[1:]], indexing="ij" ) a[0, :, :, :] = np.abs(np.sin(4 * (ix + iy))) ...
e1c29bac8e1c04e82bf13c5ba7b1602b5ffda53a92b05c53bce2077ca05b1c46
Python
1,813
46
from typing import Any from collections import defaultdict import numpy as np class DatasetSplitter: """Handles dataset splitting while keeping time series grouped together.""" def __init__( self, data: list[dict[str, Any]], val_split: float, test_split: float, random_seed: int = 42 ): s...
b3cec17c4c1f7e2cb6ae51492f845381845fe5d200afe53ff99820dc65eb3b25
Python
1,815
57
#!/usr/bin/env python from __future__ import print_function from collections import OrderedDict import re regexes = { "qbic-pipelines/rnadeseq": ["v_pipeline.txt", r"(\S+)"], "Nextflow": ["v_nextflow.txt", r"(\S+)"], "RColorBrewer": ["v_rcolorbrewer.txt", r"(\S+)"], "reshape2": ["v_reshape2.txt", r"(\S...
f318b1a2c575ee9dd6fa45dd61e03d6dc93af6d83a0c5018c917bac6ca90a894
Python
1,815
52
import pytest from pgmpy.example_models import load_model from pgmpy.metrics import StructureScore @pytest.fixture def alarm_and_data(): alarm = load_model("bnlearn/alarm") data = alarm.simulate(int(1e4), show_progress=False) alarm_no_cpd = alarm.copy() alarm_no_cpd.cpds = [] return alarm, data...
e1c836c84feeef6c7a60e92a71f021843aa570badbfb69c758bedfbf9bd04dd5
Python
1,816
46
import numpy as np import numpy.testing as np_test import pytest from pgmpy.factors.discrete import NoisyORCPD, TabularCPD from pgmpy.inference import VariableElimination from pgmpy.models import DiscreteBayesianNetwork def test_class_init(): cpd = NoisyORCPD(variable="Y", prob_values=[0.7, 0.6, 0.8], evidence=[...
15ac9f817b8d31d43bdf59ea29f2974e944aae93e50c2f9bb7d10e39e48ecbe2
Python
1,818
61
# # Copyright 2017-2023 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with # Sandia Corporation, the U.S. Government retains certain rights in this software. # # See LICENSE for full license details # from __future__ import absolute_import from __future__ import print_function import pkg_resources...
353d0e76deeebb8e87abd12c1d7a84e3d93054801c7fea7846c0883e1dc22a99
Python
1,818
52
"""Regression test: FasterRCNNBoxScoreTarget must not hardcode cuda/mps. Mirrors the fix for SemanticSegmentationTarget (#546). The target must inherit the device of the model outputs instead of assuming cuda/mps. """ import numpy as np import torch from pytorch_grad_cam.utils.model_targets import FasterRCNNBoxScoreT...
f1951715722aaf417f6e212f14f6208790b916e6529deec191f7c31da4d5a8d2
Python
1,818
50
import torch from torch.nn import ModuleDict from scvi.module.base._decorators import auto_move_data from scvi.nn import Embedding class EmbeddingModuleMixin: """Mixin class for initializing and using embeddings in a module.""" @property def embeddings_dict(self) -> ModuleDict: """Dictionary of ...
f8543f3a2562531c40fa88b3823cd0e593c65b6c25bb754141af3f8dcb22770f
Python
1,818
55
"""Data modules for PyTorch Lightning.""" from argparse import Namespace from typing import Optional import torch import pytorch_lightning as pl from sklearn.model_selection import train_test_split from calm.alphabet import Alphabet from calm.dataset import SequenceDataset from calm.pipeline import ( Pipeline, ...
8e3ff85cbc9350ad2266ae22a570c2747183bf4856fdb7783fb7a18385505e87
Python
1,819
64
"""Shared path resolution for app-owned config and state files.""" from __future__ import annotations import os import sys from pathlib import Path APP_NAME = "NeuroSyncApp" CONFIG_DIR_ENV_VAR = "NEUROSYNCAPP_CONFIG_DIR" def repo_root() -> Path: """Return the repository root.""" return Path(__file__).resol...
8ebafc6b3efb70302e21e0f2419cdea8274940318242b681f46aa5676723d5f7
Python
1,820
60
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2016-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # # To run the integration tests you must first fetch all the required test d...
b957d21ee285c9103e960f3fb667e5b23fe30388e0f5efe9cb3d400b1b4cc395
Python
1,820
57
""" Training dependency probe: used by ``main.py`` and :mod:`dlbase.train` before Hydra runs. Import this submodule directly (``from dlbase.runtime_check import ...``); package :mod:`dlbase` does not eagerly import PyTorch (see :mod:`dlbase` lazy exports). """ from __future__ import annotations import sys ...
4a93652817daafc8bbda99a33fae9214ebfa8b3fed97aab3217c286f5922f773
Python
1,822
54
# Copyright 2021 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agr...
de7e6e1a50e8d62710d14e7d6aba81ecde82447d9889266af7dfb7e234553c42
Python
1,822
59
import jax import jax.numpy as jnp from folx.ad import is_tree_complex from .api import Array, ExtraArgs, FwdLaplArgs, MergeFn from .utils import get_reduced_jacobians, trace_jac_jacT def complex_abs_jac_hessian_jac( args: FwdLaplArgs, extra_args: ExtraArgs, merge: MergeFn, materialize_idx: Array | ...
469248040358814289faa83d74db6c5566af7b0f4316394a919c5366e78e6237
Python
1,823
51
#!/usr/bin/env python ##################### Imports ################################## import argparse import pandas as pd import re import numpy as np parser = argparse.ArgumentParser() parser.add_argument("--caller",help = "Precise the peak caller used to produce the files Genrich or Macs2", required = True) parser...
fe129fce1f0e80f035ccb65ea54edc2cb0844fd46d4c869a2c5a7fcf21974c72
Python
1,824
42
import os import numpy as np import os.path as op from glob import glob from scipy.io import loadmat base_dir = '/media/lukas/goliath/MVCA/ID1000' raw_dir = op.join(base_dir, 'raw') scan_infos = sorted(glob(op.join(raw_dir, 'ID*', '*DTI32', 'ScanInfo.mat'))) for scan_info in scan_infos: print(scan_info) si =...
b71845968713e1fbde732cd867f6744b065f80cea6328c1fb36ff980204a7cc7
Python
1,825
45
import numpy as np from scipy import stats import cv2 as cv img = cv.imread('D:/Dataprocess/DATA/20240425/Timewindow_averaged/Electrical_tw/serial45_tw/averaged_tw19.png',flags=-1) cv.imwrite('D:/Dataprocess/DATA/20240425/Timewindow_averaged/Electrical_tw/serial45_tw/average_tw20.png',img) # filename = 'D:/...
d096f9601bfb6e16bac25160f2a39f8840dadfcd7615be96e5c2f53a59f2fca8
Python
1,825
53
# 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 unittest import torch from tqdm import tqdm from fairseq import utils from fairseq.tasks.text_to_speech import batch_mel_cepstral_dis...
e9a39ca36ac6ca57e4046a4afd9d494ea6023d4c9bcd0f15ae14b28433350bc0
Python
1,825
65
from __future__ import annotations import hashlib import io from contextlib import suppress from typing import TYPE_CHECKING from typing import NamedTuple if TYPE_CHECKING: from pathlib import Path class Hexdigest(NamedTuple): md5: str | None sha256: str | None blake2_256: str | None class HashM...
9dea0bd5c9301bca0126c416c72d760e7991d075b7d364d12cf64712f4309ad7
Python
1,828
49
# -*- coding: utf-8 -*- """ @author: Jack Zhang """ from fish_single_layer_manual import volpy_process_session work_dir_trial_1 = '/data/zebrafish/230820/Fish2_1/stitched/aligned_layers' work_dir_trial_2 = '/data/zebrafish/230820/Fish2_2/stitched/aligned_layers' data_name_all = [ ...
202ef14fa70aa203ca1a0c7fda661259e40b984c0c6fedc9d75f69b4bdf0c646
Python
1,831
51
#!/usr/bin/env python3 import sys, requests, time, re from collections import Counter API = "https://www.peptideatlas.org/api/promast/v1/map" def read_fasta_peptides(path): pep = [] with open(path) as fh: seq = [] for line in fh: if line.startswith(">"): if seq: ...
d1211217af214e12697353991416e1031761e3d740fabff3076a2181149dc384
Python
1,831
53
# 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 unittest import torch from tqdm import tqdm from fairseq import utils from fairseq.tasks.text_to_speech import batch_mel_cepstral_dis...
17ee5b31c6f0a71a79d39ddf85fd8dcbb1b6cdb9e8067c5bb6efe4bf947e24d1
Python
1,832
69
# 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 torchaudio import argparse import json import pathlib def get_args(): parser = argparse.ArgumentParser( "Assuring genera...
33a0621e84f83595fe527540d61230d00257816e4b028d270fffeff77a97a95f
Python
1,833
61
""" Setup script for RAG-GNN package. """ from setuptools import setup, find_packages with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() setup( name="rag-gnn", version="0.2.0", author="Hasi Hays", author_email="hasih@uark.edu", description="Retrieval-Augmented G...
abd3267516b3fba406218fe578d1f39f9e528e4ca4a1c78ab78313f4025a313e
Python
1,834
51
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from fairseq.optim import LegacyFairseqOptimizer, register_optimizer @register_optimizer("lamb") class FairseqLAMB(LegacyFairseqOptimizer): ...
de6cc95a739dca1a016c6a7c6fdf067cf18ead0754726bd765bb0376b828982e
Python
1,834
56
"""Config validation and pipeline-label helpers.""" import pytest from crossda.config import ( Config, normalize_pipeline_labels, resolve_pipeline_spec, ) def test_default_config_constructs(): cfg = Config() assert cfg.method_mode in ("smoke", "mini", "svm_radial_add", "fair", "practical") a...
c15af4f6c86d67c000c7e02dbcaf5b9c82e3a26aa990cdd287be168fcbfb7239
Python
1,835
47
# 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.optim from . import LegacyFairseqOptimizer, register_optimizer @register_optimizer("adadelta") class Adadelta(LegacyFairseqOpt...
60ea364183e960be22392238068b97b3d9c518130b68880f3c263b376354e163
Python
1,840
87
""" @file logger.py @author Simon Yu @date 01/25/2023 @brief Logging functions. """ import header import type def log_trace(*args, **kwargs): if header.log_level >= type.LogLevel.trace: print("[TRACE]: ", end = "") print(*args, **kwargs) return def log_debug(*args, **kwargs): if hea...
7f759c6b324363738ee15856e89654d90e7b9ab2729c78c228eaf7a8736866d8
Python
1,842
52
"""Train/val/test sample ids from ``encoded_data.csv`` ``split`` column.""" from pathlib import Path import pandas as pd def train_val_test_ids_from_encoded_csv( data: str | Path | pd.DataFrame, ) -> tuple[list[str], list[str], list[str]]: """ Return sorted unique ``sample_id`` lists for each split in t...
7ebd4e4c1d8e54ffb039645b9e487a6232c1ba5bf814de1b59b90b2ebc8f21f2
Python
1,844
63
import torch.nn as nn class EncoderDecoder(nn.Module): def __init__(self): super(EncoderDecoder, self).__init__() self.encoder = nn.Sequential( #Conv1d(in_channels, out_channels, kernel_size,) nn.Conv1d(4, 6, 200, stride=1, padding=1), nn.ReLU(), nn....
8194cbdae717e225f8002b61d352f9f3bed69f27a92809b2ae62165a297bab73
Python
1,844
48
"""Tests for ``aestetik.dataloader.CustomDataset``. Covers issue #7 (positional indexing) by exercising __getitem__ both with string obs_names and with a non-contiguous train_size split. """ import numpy as np from aestetik.dataloader import CustomDataset def _attach_grid_and_clusters(adata, n_t=3, n_m=3): rng ...
b1b04434847fec5adf1ce906a09d7dd1e406e20f6e9a803d77a56c4b63757615
Python
1,844
49
import jax import jax.numpy as jnp from ...geom import masked_pairwise_self_distance from ...types import ElectronConfiguration def masked_jastrow_factor( electrons: ElectronConfiguration, spins: jax.Array, alphas: jax.Array, ) -> jax.Array: r"""Compute Jastrow factor that uses a double exponential. ...
946b1e1c817a0e04952a216e785fdf6bcbed329076e8d6e5c380f3ecc7707168
Python
1,847
66
"""Utility functions for brenda_references""" import string import nltk from aiotinydb.middleware import AIOMiddlewareMixin from rapidfuzz import fuzz from tinydb.middlewares import CachingMiddleware as SyncCachingMiddleware class CachingMiddleware(SyncCachingMiddleware, AIOMiddlewareMixin): """Adding async pow...
e200d1ee502716c6dd3dbffd7a0e46f15c237f053fb9bb349b119dbb45dce749
Python
1,848
48
# 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 from torch import nn from fairseq.models.transformer import Linear class StackedEmbedding(nn.Embedding): """Embedding modu...
4d22782a4d5086a8d20fa4ccc77b9923087661a6b000d1a0790f5a94c7f5c591
Python
1,849
57
import argparse from tqdm import tqdm from multiprocessing import Manager, Pool from scipy.io.wavfile import read from librosa.util import normalize import numpy as np import amfm_decompy.pYAAPT as pYAAPT import amfm_decompy.basic_tools as basic MAX_WAV_VALUE = 32768.0 parser = argparse.ArgumentParser(description=""...
60a59e03951070108e0ce0c9ab8b4bb2e8f0713c849996125a74681d568b847d
Python
1,850
58
"""Parsing and diffing two `evaluate` logs' class-metrics tables.""" import sys from pathlib import Path import pytest sys.path.insert( 0, str(Path(__file__).resolve().parents[2] / "scripts/dec04_full") ) from negative_ablation_compare import class_table, verdict # noqa: E402 REPORT = """ === Entity CLASS metr...
d341d0ecd1e90d3c91e670fbdcd23ec22e57c8fe67ee644f97d9445577ec4e3a
Python
1,851
60
import unittest from unittest.mock import patch from pyecharts import options as opts from pyecharts.charts import Tree TEST_DATA = [ { "children": [ {"name": "B"}, { "children": [{"children": [{"name": "I"}], "name": "E"}, {"name": "F"}], "name": "C...
9c9eb710438eb45aa99b2a1e049b55b261aa016794ac51ed7316ff07f7e7825b
Python
1,852
36
# Source code: # https://github.com/zbmed-semtec/doc2vec-doc-relevance-training/blob/main/code/train_model/train.py # This file includes the modifications to the source codes according to this project! import os import time import logging from gensim.models import Word2Vec import utilities as utilities def run(best_...
a6138ba3486aee0edc94df620e8039b869fdf1ec67f92be45c7e38bd40f6cd3f
Python
1,853
48
import numpy as np from Bio import SeqIO from code.pre_processing.sequence_encode import one_hot_encode from code.pre_processing.outer_concatenation import outer_concatenation, matrix_concatenation from pathlib import Path class DataProcess(object): def __init__(self, fasta_file, ...
75f2c0661ac85456af867ccba53aac33bc1fddfb9a0bc3b5e6efe88e874403dc
Python
1,854
44
import subprocess import os def get_allowed_n_proc_DA(): """ This function is used to set the number of processes used on different Systems. It is specific to our cluster infrastructure at DKFZ. You can modify it to suit your needs. Everything is allowed. IMPORTANT: if the environment variable nnUNet...
13cab02343cc3c7a1cdac547b70fe7d9d12416c891f6d9e22a7d6c7a37a78c9a
Python
1,856
47
from typing import Optional import requests from batchgenerators.utilities.file_and_folder_operations import * from time import time from nnunetv2.model_sharing.model_import import install_model_from_zip_file from nnunetv2.paths import nnUNet_results from tqdm import tqdm def download_and_install_from_url(url): ...
20da5a929a17c76cb35d042126dc0a82e7973ff5e7ceb9def3363bf7f22ae244
Python
1,856
50
import torch import collections from proteinworkshop.models.base import BenchMarkModel from src.models.unsupervised_model import UnsupervisedModel from src.models.contrastive_model import ContrastiveModel from src.models.dual_model import DualModel from loguru import logger as log def load_model(cfg, batch): log.i...
acf2489c58122c7be45601f3c3bc777f2014c13070d4235cbed236dd9daec319
Python
1,856
45
# # Copyright 2017-2023 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with # Sandia Corporation, the U.S. Government retains certain rights in this software. # # See LICENSE for full license details # # """ # Cores used to simulate and model memristive crossbars and peripheral circuitry # Algorith...
ae818b8f04fec63bb56330f0aeee2015c910ed36ef67557d1742f46e8d36326c
Python
1,856
43
"""How sensitive is the OCE 2F LCAO bonding eigenvalue to bond length? The 2F figure value uses h(r) = h0 · exp(-α (r - r0)), h0 = -8.0 eV, α = 1.5 Å⁻¹, r0 = 1.5 Å. Plot λ⁻(r) over the typical C–C bond range. """ from __future__ import annotations import sys from pathlib import Path ROOT = Path(__file__).resolve...
caa6c74aa4eb13f4c6036768779f2566eb0774047d697eebee989099b3644f45
Python
1,856
59
# Configuration file for the Sphinx documentation builder. # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, u...
6d7790f903ef70fb0ddc767db4970dfcb5959857226111bc9416b44b41b3321c
Python
1,858
78
import pathlib from unittest import mock import pytest import vak @pytest.fixture def parser(): return vak.__main__.get_parser() def test_parser_usage(parser, capsys): with pytest.raises(SystemExit): parser.parse_args(args=['']) captured = capsys.readouterr() assert c...
cf49a5a24a3ad2e2520b60406db7d5724824708009c6f0260c96b9ff09492dd1
Python
1,858
64
from ._arraylike_field import ( CategoricalJointObsField, CategoricalJointVarField, MuDataCategoricalJointObsField, MuDataCategoricalJointVarField, MuDataNumericalJointObsField, MuDataNumericalJointVarField, MuDataObsmField, MuDataVarmField, NumericalJointObsField, NumericalJoint...
e1893e915314eb68f2d0d35f7a035cd58324a0cec0d2255932883015bc8be9ea
Python
1,860
54
""" Set up simulation design for training """ import os import numpy as np import zarr import yaml from math import ceil from numcodecs import Blosc zarr_path = snakemake.output.zarr split_sizes = snakemake.params.split_sizes split_names = snakemake.params.split_names random_seed = snakemake.params.random_seed n_sim...
7f2609f9b7b3d053733b4257ac9a39e552f50e3782effd96a0ff0c44ef4959a0
Python
1,862
47
# coding=utf-8 # Copyright 2020 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
4e1582384a8498fcfd98ef368fa6d17dad01691dc1a4b4afaac3bda9e5896cdb
Python
1,864
49
import novae from novae._constants import Keys from novae.utils import get_reference def test_get_reference(): adatas = novae.toy_dataset() novae.spatial_neighbors(adatas) assert get_reference(adatas, "largest").n_obs == 1958 assert len(get_reference(adatas, "all")) == 3 assert get_reference(a...
fbb8cf76481d4cd511edac4c2cf3754310329ff7225e3704501cfb8f147fb211
Python
1,864
54
"""Constants used by vaktestdata and scripts that rely on it.""" import json import pathlib from .config_metadata import ConfigMetadata HERE = pathlib.Path(__file__).parent TEST_DATA_ROOT = HERE / ".." / ".." / "data_for_tests" CONFIG_METADATA_JSON_PATH = TEST_DATA_ROOT / "configs" / "configs.json" with CONFIG_METADA...
17c39da6e886e050fe40f974fab82a9adbf03f946e8c90ebeea0fb83eaefd83b
Python
1,865
54
# 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 unittest import torch from fairseq.data import MonolingualDataset from fairseq.tasks.language_modeling import LanguageModelingConfig,...
b831a2b52fa22e8d33fecbd69ec47a0db150b4aa7226e6793672f46e9524d36e
Python
1,865
39
# Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany # # 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://w...
67ef3352694add9dbe96d18c6325137494fe4aceb86e84661a5ab678ea82bf0d
Python
1,866
58
# 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 unittest import torch from fairseq.data import LanguagePairDataset, TokenBlockDataset from fairseq.data.concat_dataset import ConcatDa...
8cfe2a58d8e622785befba316c52e660e204d078c030e14be05aad34f4932cb3
Python
1,866
71
#!/usr/bin/env python3 # 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 argparse import re from collections import OrderedDict import torch from fairseq.file_io import PathManager ...
4edf05d3ea683e48e322b844de5d78d0dd988ae1148355ad97112adf0af324d2
Python
1,867
36
import pandas as pd import numpy as np import sys # python convert_cleansumstats_output_to_mixer_format.py /cluster/projects/p697/projects/SUMSTATv3/v3.1/STD_GRCh37/CTG_COG_2018.sumstats.gz CTG_COG_2018_mixer.sumstats.gz if __name__ == "__main__": fname = sys.argv[1] fname_out = sys.argv[2] print(f'process...
76328bfc6cdf147feb946e9926b6d0958bdb9b2d5837109722249466ef903dd6
Python
1,868
49
class ReportableException(Exception): """Simple exeception with message""" def __init__(self, msg): self.msg = msg class InvalidArguments(ReportableException): """Logical Error for unexpected arguments""" def __init__(self, msg): super(InvalidArguments, self).__init__("Invalid argument...
856d482a7cf0ce16e663973b6014afc63801bcfac4658beeb36b261d5c12ad02
Python
1,868
63
#!/usr/bin/env python # Author_and_contribution: Niklas Mueller-Boetticher; created template # Author_and_contribution: Kirti Biharie; implemented Davis-Bouldin score import argparse parser = argparse.ArgumentParser(description="Calculate Davies-Bouldin Score (scikit-learn)") parser.add_argument( "-l", "--label...
8fc48d1e4e71f99ed48d7b75899149bbc9cc379ab3491ff6530954b5ae6df2a4
Python
1,868
44
"""Small lightweight utilities used frequently in GOATOOLS.""" __copyright__ = "Copyright (C) 2016-2018, DV Klopfenstein, H Tang, All rights reserved." __author__ = "DV Klopfenstein" def extract_kwargs(args, exp_keys, exp_elems): """Return user-specified keyword args in a dictionary and a set (for True/False ite...
fad69747854874f5378420eb22f30575fb2925b46aadf7de14bc6046aa72f7c1
Python
1,868
58
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from enum import Enum class TextCompressionLevel(Enum): none = 0 low = 1 high = 2 class TextCompressor(object): def __init...
af83e81e5433904477bf8d5ee20926cfd85861b3b41fa996b132bcfdb6e66672
Python
1,869
33
import pytest import torch from scvi.model._utils import parse_device_args @pytest.mark.skipif(not torch.backends.mps.is_available(), reason="requires an MPS device") def test_auto_accelerator_falls_back_to_cpu_when_mps_available(monkeypatch): # Regardless of whether this suite is itself running under SCVI_ALLOW...
c6fbac1f92995d2c558f6a01d1ae1d93c4e1febbcdfc7211fbf76b527e4d2df9
Python
1,869
39
"""LOD/LOQ 95% CIs consistent with the paper's Table 3. Same estimator as paper2/interpret_food.lod_table (LOD = 3.3*sigma/|S|), cluster-bootstrapped over whole physical samples on the SAME hold-out predictions used for the published point values.""" import numpy as np, pandas as pd, os, sys sys.stdout.reconfigure(enco...
a929943403b7060aa9ae49ac63ba9f1f6dd17cbbbfe25a8df8e4022913a86c79
Python
1,871
59
# 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 logging import torch import torch.nn.functional as F logger = logging.getLogger(__name__) def _cross_entropy_pytorch(logits, target...
0810e630ecf8f459d53ad493073df1c1da734e46073b96edeb8b47e8d0f5405f
Python
1,872
65
# 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 os import torch from tqdm import tqdm from data_utils import load_audio_path from fairseq.data.codedataset import get_f0_by_filename d...
5d40e985fc0f19bf37bf1b1dc51654ea776fd6278bbf00df47bf2ad9194b7043
Python
1,872
60
# -*- coding: utf-8 -*- """ @Time:Created on 2019/4/30 16:10 @author: LiFan Chen @Filename: word2vec.py @Software: PyCharm """ from gensim.models import Word2Vec import pandas as pd import numpy as np def seq_to_kmers(seq, k=3): """ Divide a string into a list of kmers strings. Parameters: seq (strin...
ff1c14b64942ad2298b7d47f381216eaa9abf2ef30cbc2b457bdef643a461515
Python
1,873
51
#!/usr/bin/env python # -*- coding: utf-8 -*- """Functions to resample an image. Intended to downsample images to ~512x512 px""" from typing import Callable, List, Optional, Tuple import numpy as np from skimage.transform import rescale from .types import MetaLike_ND2 def resample_image( image: np.ndarray, me...
c3c70a2a0599662bbfdf4523112bda620845f13f3b6919c37236add8ccc54312
Python
1,875
56
#!/usr/bin/env python3 # 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. """ Helper script to pre-compute embeddings for a flashlight (previously called wav2letter++) dataset """ import argpa...
e9f86bec54c6c707feb50b5b0b4be42d479ecf1d5e66e1d76a8144feba448cf9
Python
1,875
52
"""Shared fixtures: synthetic EEG sessions so tests need no real data.""" from __future__ import annotations import numpy as np import pytest def make_synthetic_sessions(n_sessions=5, n_trials=40, n_ch=22, n_times=256, seed=0): """Deterministic synthetic motor-imagery sessions. Each session is a dict ``{"x...
e061fea8334e94ffff31e969549abd48381b101ec20d8061080d9d816881622b
Python
1,878
32
import matplotlib.pyplot as plt import numpy as np plt.style.use(['science','nature']) x_ax = np.load('new_inf_comp_x.npy') y_base = np.load('new_inf_baseline_y.npy').reshape(-1,1) y_sot = np.load('new_inf_sotmram_y.npy') y_sotnorm = 100*y_sot/y_base y_rram = np.load('new_inf_rram_y.npy') y_rramnorm = 100*y_rram/y_ba...
aab3ddfdb089dea5ad64763af74cf17fe348bd3b7706d320f2015fa9fd292b37
Python
1,879
55
## Wrapper for crystalgrw.cli.train.main ## import time import argparse from omegaconf import DictConfig, OmegaConf import torch import torch.multiprocessing as mp from crystalgrw.cli.train import run_train def main(rank, world_size, cfg): run_train(rank, world_size, cfg) if __name__ == "__main__": parse...
1f5d83299c880d1d3a6b49049de2fac6fcfb05ba723cb08de51bafed35093bad
Python
1,880
54
"""Shared helpers for the NONAN Python test suite. Design note -- why fixtures on disk instead of generating signals in each language: MATLAB and NumPy cannot draw the same random numbers. Any cross-language test that generates its own series is comparing two different realisations and can only ever check loose stati...
878c2f7695afe45bf3826ea9ca6880ed5788f9e7f7b384c18dcdd652060a8ba0
Python
1,880
54
import torch import torch.nn.functional as F from core.utils.utils import bilinear_sampler class CorrBlock: def __init__(self, fmap1, fmap2, num_levels=4, radius=4): self.num_levels = num_levels self.radius = radius self.corr_pyramid = [] # all pairs correlation corr = Cor...
db80b6df8b3ebf7386c649e9e6c6f9042125feed530b787afcc272ce7995e0b2
Python
1,880
63
try: from torch_geometric.data import LightningDataset except ImportError: from torch_geometric.data.lightning import LightningDataset from torch.utils.data import DataLoader class AbstractDataModule(LightningDataset): def __init__(self, cfg, train_dataset, val_dataset, test_dataset): super().__in...
dd7e501f3e6546a2c74059608a55d39469ad4ac9bc472843b20910e16533c7ed
Python
1,880
44
import numpy as np import pandas as pd import sklearn # The function is modified from https://github.com/jianhuupenn/SpaGCN/blob/master/SpaGCN_package/SpaGCN/util.py def refine(sample_id, pred, dis, shape="hexagon"): refined_pred = [] pred = pd.DataFrame({"pred": pred}, index=sample_id) dis_df = pd.DataFra...
e45df65b750123400c9b681933a4d34ce987867fe6465ef799189ee158b774bc
Python
1,880
60
from src.utils import read_gtf import polars as pl riboseq = read_gtf("nextflow_results/V47/orfanage/UCSC_tracks/riboseq.gtf") novel_CDS = read_gtf("nextflow_results/V47/orfanage/UCSC_tracks/novel_CDS.gtf") classification = pl.read_parquet("nextflow_results/V47/final_classification.parquet") peptides = read_gtf("ne...
8fef77567e06a946b46845c5422be402d4d5e1481b935e0a939ecd0b65a37ad8
Python
1,881
57
"""Shared helpers for syncing example READMEs to docs/examples/.""" from __future__ import annotations from pathlib import Path EXCLUDE_DIR_NAMES = { 'API (copy)', '__pycache__', '.gmx_mmpbsa_temp', } EXCLUDE_FILE_SUFFIXES = ( '.log', '.kate-swp', ) SKIP_DOCS_RELATIVE = { Path('gmx_MMPBSA_t...
a10ca1270b5b9d5044f8b6638a98edfac9f30a82a90844af1253e6b6322a2ec4
Python
1,881
63
#!/usr/bin/env python # Author_and_contribution: Niklas Mueller-Boetticher; created template # Author_and_contribution: Kirti Biharie; implemented Calinski-Harabasz score import argparse parser = argparse.ArgumentParser(description="Calculate Calinski-Harabasz Score (scikit-learn)") parser.add_argument( "-l", "...
4bd9316568ec833e1dbf6d290b6166efc90247ec8f5fc6fe1892f9f7dcab0ae2
Python
1,883
46
import matplotlib matplotlib.use('TkAgg') res = {"DTCR": {"PISTE": 0.9264718981831416, "TEIM": 0.9012353342571597, "ERGO": 0.934445901875, "epiTCR": 0.8943023353125001, "NetTCR-2.0": 0.9247589841503963}, "DTCR-R": {"PISTE": 0.8829555691267463, "TEIM": 0.8658527947723582, "ERGO": 0.913677704...
75991aca94292604ad7b41094cde5b7e3d60b15d8801b8c29c788b8e95fba932
Python
1,884
63
"""Lightning DataModule for NPZ patch folders (train/ / test/). Supports datasets: WMB, CA1, Simulation via registry (``datasets.plugins``). """ from __future__ import annotations import pytorch_lightning as pl from omegaconf import DictConfig from torch.utils.data import DataLoader from dlbase.registry ...
f14522bbda1ede3a477edc09dae8383f065e5a06a3c29e9f6453ece7202aa991
Python
1,884
49
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from fairseq.models import FairseqDecoder, FairseqEncoder # a container for different encoders with training samples from different modalit...
2ee067f403ec84853842deb2723eab1efb84a2188ebd9069b004f3fbf3cb6b3a
Python
1,886
68
# 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 random import numpy as np import torch from .shardedtensor import * from .load_config import * def set_seed(seed=43211): random.s...
49343d2b59600dbfc717ecccac610a83d3e630bf1875e10a37d9d98cd2bf60ad
Python
1,886
63
# 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 from fairseq.data import BaseWrapperDataset, data_utils class AddClassTargetDataset(BaseWrapperDataset): def __init__( ...
5cd6510a32ff6b0353849f4e6fe36c66f1efd7a3844200f5cc0135b788b51ee5
Python
1,889
67
from __future__ import annotations import json import os from pathlib import Path from typing import TYPE_CHECKING from typing import Any from poetry.core.constraints.version import Version if TYPE_CHECKING: from collections.abc import Callable VERSION_3_7_1 = Version.parse("3.7.1") def build_venv(path: Pat...