sha256
stringlengths
64
64
language
stringclasses
27 values
size
int32
1
491k
lines
int32
1
21.8k
content
stringlengths
1
200k
bc524626d5cddb1932a2fb2393c7e6a2d930c5beb6e9858a4158d0fcb49ddb65
Python
957
36
class Mode: """Novae mode class, used to store states variables related to training and inference.""" def __init__( self, zero_shot: bool = False, trained: bool = False, pretrained: bool = False, multimodal: bool = False, ): self.zero_shot = zero_shot ...
9a4aa9879dac9a6939a82091c3715c80d2e7a371eaa9c642d87660cef3dc6b94
Python
958
25
import numpy as np import tqdm import math from pyimzml.ImzMLParser import ImzMLParser from msi_visual.extract.base_msi_to_numpy import BaseMSIToNumpy class PymzmlToNumpy(BaseMSIToNumpy): def get_regions(self, input_path): return [0] def get_img_type(self): return np.float32...
d134ae8174abeb58ebf6f2bbb8a69d1ea6982c9727ee44bb745e71b87421fa04
Python
959
34
__author__ = 'heroico' import logging import sys def configureLogging(level=5, target=sys.stderr): logger = logging.getLogger() logger.setLevel(level) kludge=False if logger.hasHandlers(): kludge=True logger.handlers.clear() # create console handler and set level to info RED ...
5c5a5a2c4ccb39935548eb72e9dadf7d7b12e371c6072e7b84b8c39df6cc207f
Python
960
34
from __future__ import annotations import pandas as pd from PySide6.QtWidgets import QApplication from src.features.telemetry_alignment.telemetry_processing_widget import ( TelemetryPhotomOptoProcessingApp, ) def test_telemetry_qt_app_instantiates(): _app = QApplication.instance() or QApplication([]) wi...
64fa1b8bc40c82c1cdbb6046e2755ad08268eee072b21940e7e47db54400ca49
Python
960
45
from pgmpy.datasets._base import BaseDataset class CreditApproval(BaseDataset): """ References ---------- - :footcite:t:`ivandari_2022` """ _tags = { "name": "credit_approval", "n_variables": 16, "n_samples": 690, "has_ground_truth": False, "has_expert_...
2de61a2b7b115af5adadfceea8629bc0bad4b082d8fc30d2074e6b4d6f09f60a
Python
962
60
VALID_RECONSTRUCTION = [ "svrtk", "niftymic", "nesvor", ] VALID_SEGMENTATION = ["bounti", "fetalsynthseg"] VALID_SURFACE = [ "surfpype", ] VALID_PREPRO_TAGS = [ "mount", "input_stacks", "input_masks", "output_stacks", "output_masks", "singularity_path", "singularity_mount...
a472d85904a6c94f4e115d467789f00ed5e5d5f5c02eb62e43d5da0b19ebda3d
Python
962
41
"""Create individual experiment files for a parameter sweep.""" from itertools import product from pathlib import Path import yaml def set_value(dct, keys, val): for key in keys[:-1]: if isinstance(dct, dict) and key in dct: dct = dct[key] else: raise KeyError(f"{keys} do...
db8a8b7ef1ff960f308e52f25417bc049b4e9fb7ea34f409b1feba299e5b8bc5
Python
962
40
# isort: skip_file # else segmentation fault during imports import pyarrow # noqa: F401 from pathlib import Path import pandas as pd import scanpy as sc import novae def main(directory: Path) -> None: paths = list(directory.glob("*.h5ad")) data = { "slide_id": [], "mean_distances": [], ...
86bcb3bf8288de777ac47c75cf81b206872e2cbdad147a5358923809927f18cc
Python
963
37
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import Dataset import warnings warnings.filterwarnings('ignore') class MLP(nn.Module): def __init__(self): super(MLP,self).__init__() self.l1 = nn.Linear(400,20) self.l2 = nn.Line...
f3261c189767bf8ef6d5d1b25a675e6adedd913c3c25c32a8897171d579aecfa
Python
964
36
from pgmpy.datasets._base import BaseDataset class MyocardialInfarction(BaseDataset): """ References ---------- - :footcite:t:`springer_myocardial` """ _tags = { "name": "myocardial_infarction", "n_variables": 123, "n_samples": 1700, "has_ground_truth": False, ...
a53f8a4714a221bcebd8b7138bc24a6ed27537b67b848c3c74ea9ae1ce81bd10
Python
965
24
from typing import Type from nnunetv2.preprocessing.normalization.default_normalization_schemes import CTNormalization, NoNormalization, \ ZScoreNormalization, RescaleTo01Normalization, RGBTo01Normalization, ImageNormalization channel_name_to_normalization_mapping = { 'CT': CTNormalization, 'noNorm': NoNo...
04a17cd48afba1f10c519ebcdaf220cbd0595ac4b424543f980ac689ef5d68ca
Python
966
35
from argparse import ArgumentParser from pathlib import Path import pandas as pd def parse_args(): parser = ArgumentParser() parser.add_argument("input_dir", type=Path) parser.add_argument("output", type=Path) parser.add_argument("--pattern", default="*_GOF.csv") return parser.parse_args() def ...
60e28ab795613490ecf8c3debca35b95337974fd8572a883e34199327f079954
Python
966
44
import os import subprocess from create_input_json import createInputJson sorted_directories = [ '/path/to/kilosort/outputs' ] probe_type = '3a' json_directory = r'C:\Users\svc_neuropix\Documents\json_files' for directory in sorted_directories: session_id = os.path.basename(directory) input_json = os....
da0d2c92927c47c860d26e7df03a52f1d686fb45e9b66a11206fcd8811cd354f
Python
966
24
import pytest from pgmpy.models import DiscreteBayesianNetwork from pgmpy.structure_score import BDeu # Score values in the tests are compared to R package bnlearn class TestBDeu: def test_score(self, small_df, small_df_models): m1, m2 = small_df_models scorer = BDeu(small_df) assert sco...
757844e5a90b84bfad978c12025ff26a77c0f2971fc0fe963136af14310c403c
Python
967
47
#!/usr/bin/env -S uv run --script # /// script # requires-python = ">=3.11" # dependencies = [ # "msgpack", # "zstandard", # ] # /// import argparse import pathlib import pprint import struct import msgpack import zstandard def dump(filename: str): content = pathlib.Path(filename).read_bytes() magi...
299b01cf10b29aae8ce719c08e79b1b255cead8ed657f0bba082c9daacc4423f
Python
968
30
# # Copyright 2017 National Technology & Engineering Solutions of Sandia, LLC # (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government # retains certain rights in this software. # # See LICENSE for full license details # from dataclasses import dataclass from .base_parameters import BasePar...
8f6e28ae5e94f28a941a5f5d2d9c6e3b134ae3f738d861b7f0e3ffbf47bc4387
Python
968
39
import numpy as np import pandas as pd from scipy import sparse import torch def load_sparse_indices(path): coo = sparse.load_npz(path) indices = np.vstack((coo.row, coo.col)) return(indices) def sort_data(path): data = pd.read_csv(path) data.sort_values("OS_MONTHS", as...
c63860506360ca7bfd163dcca155ecae21dc29cd3bab4cb5802df9387f8a7951
Python
970
35
"""Shared pytest fixtures for the HIPPIE release test suite.""" from __future__ import annotations import os import shutil from pathlib import Path import pytest REPO_ROOT = Path(__file__).resolve().parents[1] TOY_DATASET = REPO_ROOT / "datasets_hippie" / "toy" @pytest.fixture(scope="session") def toy_dataset_di...
cfec6323968c7bbe45153e4f32aafbc1f7a76284dc4b6e426f5f320463279297
Python
970
29
import numpy as np from fairseq.data.audio.feature_transforms import ( AudioFeatureTransform, register_audio_feature_transform, ) @register_audio_feature_transform("global_cmvn") class GlobalCMVN(AudioFeatureTransform): """Global CMVN (cepstral mean and variance normalization). The global mean and var...
44d88887140fde44d3a7755028ff35fadb3030a6924dd1acb13619378b1be4e4
Python
971
26
## Users can modify the following paths to their own paths # NOTE: this script will be used by both python and bash scripts, so please use grammer that is compatible with both languages ## model SPLICEBERT="../../models/SpliceBERT.1024nt" SPLICEBERT_510="../../models/SpliceBERT.510nt" SPLICEBERT_HUMAN="../../models/...
5676e7e57525932ba138f571e4c0b7830069f09885ca0d5a8de9c061636395e0
Python
971
41
""" Hydra training entry (lives under ``dlbase/``). Prefer ``python main.py`` from repo root. Direct use:: python -m dlbase.train python -m dlbase.train model=<name> train.max_epochs=50 ``config_path`` points at the repository ``conf/`` directory (one level above this file). """ from __future__ import annotatio...
758bf285b004fc6cd047cacf4e741c5325eb88f40377792ff7f593f2fbb70953
Python
972
37
#!/usr/bin/env python3 import setuptools with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() d = {} with open("tangram/_version.py") as f: exec(f.read(), d) setuptools.setup( name="tangram-sc", version=d["__version__"], author="Tommaso Biancalani, Gabriele Scalia", ...
db85dd001c8fa337b74505a5897035b2d0fe4484515b198287d84d5fe764bddd
Python
972
34
import numpy as np from pytorch_grad_cam.base_cam import BaseCAM from pytorch_grad_cam.utils.svd_on_activations import get_2d_projection # https://ieeexplore.ieee.org/document/9462463 class LayerCAM(BaseCAM): def __init__( self, model, target_layers, reshape_transf...
289af96c0b7191c70465080118d15ad81e68a0e2809fc98359064b049551c0ef
Python
973
29
import argparse import webbrowser import neuroglancer import neuroglancer.cli if __name__ == "__main__": ap = argparse.ArgumentParser() neuroglancer.cli.add_server_arguments(ap) args = ap.parse_args() neuroglancer.cli.handle_server_arguments(args) viewer = neuroglancer.Viewer() with viewer.tx...
494df3a7688032ff53630d001982ff58ab2ca46f1788ccb2718f62243d24bf09
Python
974
32
import numpy as np from pytorch_grad_cam.base_cam import BaseCAM class XGradCAM(BaseCAM): def __init__( self, model, target_layers, reshape_transform=None): super( XGradCAM, self).__init__( model, target_layers...
3f0d7007d2f90c3bd5b05738a032bcee5c993882db275caaeedc05f621894954
Python
975
51
"""sub-package that parses config.toml files and returns config object""" from . import ( config, dataset, eval, learncurve, load, model, predict, prep, spect_params, train, trainer, validators, ) from .config import Config from .dataset import DatasetConfig from .eval i...
c2060c4d51a27c593a3d5a249cd3d625dfa450202fbf025f02a4d9dd4a874661
Python
977
30
import numpy as np import pandas as pd from anndata import AnnData from novae import utils from novae._constants import Keys def _fake_input(p: float) -> AnnData: obs = pd.DataFrame({Keys.IS_VALID_OBS: np.random.rand(1000) <= p}) obs.index = obs.index.astype(str) obsm = {Keys.REPR: np.random.rand(1000, 1...
9f19664520482af366569ff598db99f3dd8b628bc76bcfbbf1dc5c8c61beb230
Python
980
43
import os from fairseq.data.audio import ( AudioTransform, CompositeAudioTransform, import_transforms, register_audio_transform, ) class AudioFeatureTransform(AudioTransform): pass AUDIO_FEATURE_TRANSFORM_REGISTRY = {} AUDIO_FEATURE_TRANSFORM_CLASS_NAMES = set() def get_audio_feature_transform...
b3b95a84aef8fbe1a6b0830b351b1c0b56e007510a5b04deee6c269f93c1ded3
Python
981
30
"""Inverse-distance weighting and weighted oversampling.""" import numpy as np from crossda.pipelines.weighting import _weight_from_D, _merge_weighted def test_weights_sum_to_one_and_favour_near(): w = _weight_from_D(np.array([1.0, 2.0, 4.0])) assert np.isclose(w.sum(), 1.0) # Smaller distance -> larger...
da9d19081ba6ebb03d1dbb268946f6712eefcfb0dcb2a576a0c46bfa34ef4537
Python
981
31
import numpy as np from pytorch_grad_cam.base_cam import BaseCAM from pytorch_grad_cam.utils.svd_on_activations import get_2d_projection class HiResCAM(BaseCAM): def __init__(self, model, target_layers, reshape_transform=None): super( HiResCAM, self).__init__( ...
b3e356a1168207e3c8f05bff142794959b8aaccf9442a2e109c059b3d6c3fa99
Python
982
23
import torch import torch.backends.cudnn as cudnn def select_device(id, force_cpu=False): cuda = False if force_cpu else torch.cuda.is_available() cudnn.benchmark = True device = torch.device('cuda:{}'.format(id) if cuda else 'cpu') #device = torch.cuda.set_device(0 if cuda else 'cpu') if not cuda: ...
313f7c487c2821522496cf51bc27a83096630a79f3fc12118ebd7e6e8950e296
Python
983
31
from .BayesianNetwork import BayesianNetwork from .ClusterGraph import ClusterGraph from .DiscreteBayesianNetwork import DiscreteBayesianNetwork from .DiscreteMarkovNetwork import DiscreteMarkovNetwork from .DynamicBayesianNetwork import DynamicBayesianNetwork from .FactorGraph import FactorGraph from .FunctionalBayesi...
a4370843a018ca203a3e6c3a4db744a7659f8f8e68bb6b7f7ff510c34a80f293
Python
983
31
"""Render `d3text.metric_docs.glossary` into a page at build time. A page holds `<!-- metric-glossary: STAGE -->` where the table for `STAGE` should appear, so the reference page cannot drift from what a run logs. """ import re from mkdocs.structure.files import Files from mkdocs.structure.pages import Page import ...
d7c06844a2c517111b66037ce5c4f37f1420244b041a78560adcbdb30b2658af
Python
983
48
import socket # Check whether a port is in use def check_port_in_use(port, host='127.0.0.1'): s = None try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(1) s.connect((host, int(port))) return True except socket.error: return False finally: ...
3093db5e40cf0f05796fee8adc63790977719ba9c94977b582061b7dea2fb758
Python
984
26
""" Global reproducibility policy for DLBase and SpatialPheno. RNG state is set exclusively via :func:`pytorch_lightning.seed_everything` (Python ``random``, NumPy, PyTorch, ``PL_GLOBAL_SEED`` / worker env). We then align cuDNN with the former standalone ``setup_seed`` behavior (deterministic kernels; disable ben...
8518d19a3101b8fa88c3a0f42fc584f9c8ca06c36b1a8147ba6565c03395748f
Python
984
27
"""Typed options shared by the public CLI and inference runtime.""" from dataclasses import dataclass from pathlib import Path @dataclass(frozen=True) class CheckpointArguments: """Durable batching options shared by every inference command.""" checkpoint_batch_size: int | None = None checkpoint_dir: Pat...
9145191dc74713bb898de62b931b5baa95fa33faf78c54b1656ea3c72e4d1211
Python
984
32
from __future__ import annotations from pathlib import Path from tomlkit.items import Array from poetry.factory import Factory def get_self_command_dependencies(locked: bool = True) -> Array | None: from poetry.console.commands.self.self_command import SelfCommand from poetry.locations import CONFIG_DIR ...
314be0d4fe72330a81cdabf53606bcc88a59599b202a733a848b4e62a7734bb8
Python
986
38
import importlib.util import importlib.metadata from logging import getLogger from packaging import version logger = getLogger(__name__) """ Modified from transformers: utils/import_utils.py """ def _is_package_available(pkg_name: str) -> bool: # Check if the package spec exists and grab its version to avoid imp...
9c52485a954b18af9cc0ed125a1ebe7e4d5e9007e272724d5abe77f6cb09a097
Python
986
32
from __future__ import annotations from dataclasses import dataclass from typing import TYPE_CHECKING from poetry.core.packages.dependency_group import MAIN_GROUP from poetry.core.version.markers import BaseMarker from poetry.core.version.markers import EmptyMarker if TYPE_CHECKING: from collections.abc import ...
2cda9c8129eb8fa781acda5ef223295522a2b04fb2464ae99294249df5084c53
Python
987
41
from __future__ import annotations from typing import TYPE_CHECKING from typing import ClassVar from cleo.helpers import option from poetry.console.commands.command import Command if TYPE_CHECKING: from cleo.io.inputs.option import Option class EnvListCommand(Command): name = "env list" description =...
8ba512368d661d7f0c225e399f1b4f31ed2e8d1205bef3f3f98d0bf742d42e86
Python
989
25
"""Warmup + cosine decay (aligned with step_basic.set_lr).""" import math from torch.optim.lr_scheduler import LambdaLR from torch.optim import Optimizer def make_warmup_cosine_lambda(max_epochs: int, warmup_epochs: float, min_lr_ratio: float): def lr_lambda(epoch: int) -> float: if max_epochs <...
e512338a0d5b6d4b929017a4c7942b5cd3941e62c85b8b7050bf68cd62e5449f
Python
989
38
import subprocess import multiprocessing as mp from typing import Iterable, List from functools import partial import os import torch def run_command(gpus, command): gpu = gpus.pop() print(command) env = os.environ.copy() env["CUDA_VISIBLE_DEVICES"] = str(gpu) subprocess.run(command, env=env) ...
b2b5a630e2b532ccc74d4177d1fb0d80d197c402601ee622c53ffefb39071ad9
Python
992
28
# 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 from unittest import mock class TestIOPath(unittest.TestCase): def test_no_iopath(self): from .test_reproducibil...
78f6534f3728b920485d3d89e5f0192c0ef2cdbab7519fda59886503edab7091
Python
993
32
from __future__ import annotations import sys from pathlib import Path from poetry.console.commands.command import Command class DebugInfoCommand(Command): name = "debug info" description = "Shows debug information." def handle(self) -> int: poetry_python_version = ".".join(str(s) for s in sys...
a2a81bc5a56b53d7d9fbf4ec27403f854e6e2a74aa16b4ff5ff9bf4d4945baf4
Python
993
31
import sys import json from msi_visual.supervised.annotations import get_img, get_visualization, get_dataset from xgboost import XGBClassifier import joblib if __name__ == "__main__": path1 = r"E:\\MSImaging-data\\_msi_visual\\Extractions\\NRL4485-s2\\20_bins\\0.npy" path2 = r"E:\\MSImaging-data\\_ms...
1c155824fdfc357376e20ef51afb4e6c8282ba478322290e898a514505ce4b5c
Python
995
23
from paper2.parsers import oil_group_key, coffee_group_key, juice_group_key def test_oil_keys_strip_replicate(): assert oil_group_key("11_1") == "11" assert oil_group_key("11_17") == "11" assert oil_group_key("Z3") == "31" # appended pure-oil block: Z<brand> == <brand>1 assert oil_group_key(...
8b4640288055e20e0fadd5f1bdbb4c55ffbcfcb75aaf31c70db20d7829234d84
Python
995
32
import numpy as np import pytest import torch import scvi from scvi.data._utils import scipy_to_torch_sparse @pytest.mark.parametrize("sparse_format", ["csr_matrix", "csc_matrix", None]) def test_scipy_to_torch_sparse(sparse_format: str): adata = scvi.data.synthetic_iid(sparse_format=sparse_format) scipy_spa...
ec75fb8f59bf54c68caea18e64049cc5cce266bd0c6b800a26d06f47603280f4
Python
996
33
# 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 from tests.speech import TestFairseqSpeech S3_BASE_URL = "https://dl.fbaipublicfiles.com/fairseq/" class TestConvtransforme...
26b9bb8567042fc18807e6741f81678f1b872f7cd9cb7aad5c3df269df65925d
Python
997
41
from pgmpy.datasets._base import BaseDataset class Algeria(BaseDataset): """ References ---------- - :footcite:t:`uci_algerian_forest_fires` - :footcite:t:`peerj_pima` """ _tags = { "name": "algerian_forest", "n_variables": 15, "n_samples": 244, "has_ground...
56a74f2ed55eb87c605f05f625a2d6b422371ce9f75fc1408fac6a6186f0ad5b
Python
997
32
import torch import torch.nn as nn import numpy as np # Inspired by https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html class StandardScaler(nn.Module): def __init__(self) -> None: super().__init__() self.register_buffer("_mean", torch.tensor([0.0])) ...
b704a7ba76cbc566e6ccb6601189fd00ca9e8477d890a72c28ba8f55a947039e
Python
997
24
# Adopted from https://github.com/bioinformatics-sannio/ncrna-deep from rinalmo.utils.ncrna_classification.seqEncoders import * nlayers=[0,1,2,3] # deep architecture layers bnoise=[200] # boundary noise simulation t=[1,2,5,10] # number of random (non functional) seqs for each test seq padds = ['random'] # how paddin...
4f8cddc01dd698fd0828b3e9e9df96816a2d2b697c614558cb1a437ce9b3f27e
Python
998
36
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import json import logging import hydra import omegaconf import torch from omegaconf import OmegaConf from mattergen.common.utils.globals import MODELS_PROJECT_ROOT from mattergen.diffusion.config import Config from mattergen.diffusion.run impo...
ec6a767ca27de48f3499f1a8d89cb6044f1733539f9a27374ef12c0294d7a920
Python
998
28
import os import platform import site import shutil def add_custom_trainers_to_local_nnunetv2() -> str: # Locate the site-packages directory site_packages = site.getsitepackages()[0] if platform.system() == 'Windows': site_packages = os.path.join(site_packages, 'Lib', 'site-packages') source...
ff80b834e1b735a1b885e3140b5bf64b43efe4589b89b970d4b7b6dfb19c8af8
Python
998
36
from ._base import BaseCITest, get_ci_test from .chi_square import ChiSquare from .fisher_z import FisherZ from .g_sq import GSq from .gcm import GCM from .generalized_cov import GeneralizedCov from .hotelling_lawley import HotellingLawley from .independence_match import IndependenceMatch from .log_likelihood import Lo...
47ffe713457a62e7ea25c3713bf9dcd695ffac41914439a0dc32f24887a5017e
Python
999
39
import os import torch from model import FrePatchTST3_attn_ablation class Exp_Basic(object): def __init__(self, args): self.args = args self.model_dict = { 'FrePatchTST3_attn_ablation': FrePatchTST3_attn_ablation, } self.device = self._acquire_device() self.mode...
924b58627efa6f244063b8b6f09ff94690073661340ac21063cabdf599566572
Python
999
24
from ambiguous.dataset.dataset import * def test_aMNIST_dataset(): root = 'data/' trainset = aMNIST(root=root, download=True, train=True, transform=None) testset = aMNIST(root=root, download=True, train=False, transform=None) trainloader = DataLoader(trainset, batch_size=64, shuffle=True) testloade...
7cbccd0cb2270439feab8ad76d2004176c5757ac251b66a5244e7c892bc1646a
Python
1,000
42
import numpy as np import pandas as pd import pytest from pgmpy.estimators import BaseEstimator @pytest.fixture def dataset1(): return pd.DataFrame(data={"A": [0, 0, 1], "B": [0, 1, 0], "C": [1, 1, 0], "D": ["X", "Y", "Z"]}) @pytest.fixture def dataset2(): return pd.DataFrame( data={ "A...
8b19212d63237b5000aa3a4f3292611affffd55fdc736de173ab722da0f56f34
Python
1,002
35
import ants import os import sys ''' Atropos segmentation with possibility of multivariate input ''' def segment_with_atropos(imgPath, stimFolder): if type(imgPath) == list: img = [] for img_path in imgPath: img.append(ants.image_read(img_path)) mask = ants.get_mask(img[0]) ...
98355476cb3fdf63b0fa8677f813ca86bc3e17b0d36e3961ffa76ab354994fdc
Python
1,002
27
from argschema import ArgSchema, ArgSchemaParser from argschema.schemas import DefaultSchema from argschema.fields import Nested, InputDir, String, Float, Dict, Int from ...common.schemas import EphysParams, Directories class AutomergingParams(DefaultSchema): merge_threshold = Float(required=True, default=2.5, h...
420a7b333d6b49a6fc26f1fe8fda27c24ed36dae08c7245a49258ee65c499a59
Python
1,003
29
# Copyright 2020 The Lucent Authors. All Rights Reserved. # # 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 ...
db29cd216a57ff79e4b33f517aacd8ff625b0bb188888d3545068538feced489
Python
1,003
32
#!/usr/bin/env python3 """Combine prokaryote + eukaryote per-gene stats into the headline AA recovery. The headline gene-completion number is the equal-weighted mean of the per-gene mean AA recovery across all 12 benchmark genes (4 prokaryotic + 8 eukaryotic). Usage:: python summarize.py out/evo2_7b/evo2_7b_prok...
7e241731eb57146f0bf756fe7be43bb5baf77ea359158eb2fabe88d78aa80646
Python
1,004
23
import os import scanpy as sc import torch import torch_npu import scMulan from scMulan import GeneSymbolUniform adata = sc.read('Data/liver.h5ad', backup_url='https://cloud.tsinghua.edu.cn/f/45a7fd2a27e543539f59/?dl=1') adata_GS_uniformed = GeneSymbolUniform(input_adata=adata, output_d...
aceb8b9db62dcbb4603d55d5b21a9c9675ba62fe1bc78f34ca99fcadec3faedc
Python
1,004
38
from pgmpy.datasets._base import BaseDataset class ContraceptiveMethod(BaseDataset): """ References ---------- - :footcite:t:`uci_contraceptive_method` """ _tags = { "name": "contraceptive_method", "n_variables": 9, "n_samples": 1473, "has_ground_truth": False,...
3b4ac4ab0ff48836b51dae60d48fe6d2f7d958b31ccca158976cde9395ea0551
Python
1,005
33
"""Smoke test for scripts/microcircuits/run.py. Uses tests/fixtures/microcircuits_smoke.yaml with reduced number of pattern and epoch duration, to keep runtime well under the 60 s timeout. """ import subprocess import sys from pathlib import Path import pytest from conftest import SCRIPTS_DIR SCRIPT = SCRIPTS_DIR /...
f534755122a9cd4ab44dfb78c9de2485088ee4218e1f0dff63ccd083c4511361
Python
1,006
25
import time import os from tape.models.file_utils import url_to_filename, get_cache, get_etag from tape import ProteinBertModel from tape import TAPETokenizer from tape.models.modeling_bert import BERT_PRETRAINED_MODEL_ARCHIVE_MAP import torch def test_forcedownload(): model = ProteinBertModel.from_pretrained('be...
c851dcb66b6fe5276d559563eb36b56d763977cc6fab37fd8a84e7af63710ad1
Python
1,007
20
import pandas as pd import numpy as np def create_text_datasets(file_path, test_fuile, train_file, valid_file): main_file = pd.read_csv(file_path, sep='\t') test_file = np.load(test_file, allow_pickle=True) pmids = [np.int64(line[0]) for line in test_file] filtered_main_file = main_file[main_file['PMI...
56609a041cc90b6a6db6e1f830a979b8c1ebef72754e9155c72be214de47a881
Python
1,008
38
""" Common helpers for baseline models. """ from __future__ import annotations import torch import torch.nn as nn import timm class TimmClassifier(nn.Module): """ Thin wrapper around timm.create_model for classification baselines. """ def __init__(self, model_name: str, num_classes: int, pretrained:...
691ca399d4c735ca298b83ddcd6cdd4de02999691ea676210b0069385dd6b2d9
Python
1,008
38
import gl gl.resetdefaults() kframesperrotation = 180 gl.meshload('BrainMesh_ICBM152_smoothed.lh.mz3') gl.meshcurv() gl.overlayload('CIT168.mz3') gl.azimuthelevation(250, 35) gl.meshhemisphere(-1) for i in range(0, kframesperrotation * 7): rot = (i / kframesperrotation) if ((i % kframesperrotation) == 0): shade...
9b01348d7de38c752a4b777aee02a6d41eb2aba2982170c0026ec1172307810f
Python
1,008
28
import numpy as np from meld_classifier.paths import BASE_PATH from meld_classifier.meld_cohort import MeldCohort from meld_classifier.data_preprocessing import Preprocess #Generate feature names features = [] for d in [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]: features.append(f".combat.on_lh.gm_T1_{d}...
959b0cb20460d5d0a5cc1bfdcb913976d99f4ef8a318e947017c1a69afad03fb
Python
1,010
34
import torch def fasterrcnn_reshape_transform(x): target_size = x['pool'].size()[-2:] activations = [] for key, value in x.items(): activations.append( torch.nn.functional.interpolate( torch.abs(value), target_size, mode='bilinear')) ...
9bb6d9f69a75bc13cb01025f8a930f374439664e8edc763ae530b282f2154c2b
Python
1,011
27
import slicer from slicer.util import VTKObservationMixin from ..Widgets.ToolWidget import AbstractToolWidget from ..Effects.PointerEffect import AbstractPointerEffect class NoneToolWidget(AbstractToolWidget, VTKObservationMixin): def __init__(self): toolTip = 'None. Disable Effects.' AbstractToolWidg...
313fa1a52ea135f53fd0b7161e897aa1bcf76c8ae5cf6b21be3af8e9338c45ef
Python
1,012
28
from CurrentscapePipeline import CurrentscapePipeline output_dir = 'output_5s_simulation' cluster_seed = 0 random_seed = 30 e_input = 'synaptic_input/Espikes_d10_Ne2000_Re0.5_rseed1_rep0.dat' i_input = 'synaptic_input/Ispikes_d10_Ni200_Ri7.4_rseed1_rep0.dat' simulation_time = 5*1000 target = 'soma' # can be any dend...
3459d9df62e2ab27d9d104052c71b4896d951a68cad72bf989bb82740858f9f4
Python
1,012
32
""" Basic FISSA usage example. This file contains a step-by-step example workflow for using the FISSA toolbox. An example notebook is provided here: https://github.com/rochefort-lab/fissa/blob/master/examples/Basic%20usage.ipynb """ import fissa # On Windows, it is necessary to wrap the script in a __name__ check,...
80aeb57e46bdf9137e5633185e5fbdde0b3ea2c31791aa5e9be1706cfa8d1f5b
Python
1,012
38
from utils import general from models import models data_dir = "D:\Data\DIRLAB\DIRLAB_clean" out_dir = "D:\Data\DIRLAB\outtest" case_id = 8 ( img_insp, img_exp, landmarks_insp, landmarks_exp, mask_exp, voxel_size, ) = general.load_image_DIRLab(case_id, "{}\Case".format(data_dir)) kwargs = {}...
82fbb03c82690a86f8bf17e8a97f39cafd9a24960b32540a573037603fe5f9de
Python
1,012
29
def asymmetric_mad(data): """ Computes the asymmetric median absolute deviation in a vectorized manner. """ # Calculate the median for each column (axis=0) median = np.nanmedian(data, axis=0) # Calculate absolute deviations from the median # Broadcasting makes this efficient: `data` is (...
ba93ada913157808b7e368e5dbff1c076dc2d3bc12b7745e48ac1643df8e77ab
Python
1,012
29
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # type: ignore from pathlib import Path from read_version import read_version from setuptools import find_namespace_packages, setup setup( name="dependency-submitit-launcher", version=read_version("hydra_plugins/dependency_submitit_launche...
3bd08d16d34bc41c6cdf417d41f24f2d5046529c76a3f6ec9e25e3014c967a64
Python
1,014
46
def ants_transformation( in_nii: str, ref_nii: str, out_nii: str, in_tform: str, interpolation="Linear", ) -> str: """ Application of ANTs transform. Parameters ---------- in_nii : str Path to input nifti file. ref_nii : str Path to reference nifti file. ...
ad0f3e5444e82bd04ef148f19d01c05602b0c70b5454626ec0f1f2d4d5f45048
Python
1,015
25
# 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. proteinseq_toks = { 'toks': ['L', 'A', 'G', 'V', 'S', 'E', 'R', 'T', 'I', 'D', 'P', 'K', 'Q', 'N', 'F', 'Y', 'M', 'H', 'W', 'C', 'X', 'B',...
d6f342459e8625046057110973c852ae5d93b1aef461ebcbaa10b489da8065f5
Python
1,015
32
import argparse import neuroglancer import neuroglancer.cli import neuroglancer.webdriver ap = argparse.ArgumentParser() neuroglancer.cli.add_server_arguments(ap) ap.add_argument("--browser", choices=["chrome", "firefox"], default="chrome") args = ap.parse_args() neuroglancer.cli.handle_server_arguments(args) viewer ...
b66c7ee705d060ec34c1960b5ed57d1e4819cbe19257013cc5cdfccca3a00bb6
Python
1,016
21
# FTIR (mid-IR) assignments in WAVENUMBER cm-1 for edible fats/oils/pastes. # Refs: Guillen & Cabo (1997); Rohman & Che Man (2010); Vlachos et al. (2006). BANDS = [ ((3000, 3020), "=C-H stretch (cis C=C)", "Unsaturated fatty acids"), ((2900, 2940), "C-H asymmetric stretch (CH2)", "Lipid acyl chains"), ((284...
ebebae2512411e157f9853dee3966f7d3f4e22d59c0fe06137feccdc499a1615
Python
1,016
30
import unittest from pathlib import Path import torch from tangle_tracer.modules import NFTDetector class NFTDetectorTestCase(unittest.TestCase): """NFTDetectorTestCase class.""" @classmethod def setUpClass(cls) -> None: cls.model = NFTDetector() cls.rand_data = torch.rand(1, 3, 1024, 1024...
29c6a0d7243f249312f743bbe2b56d38c9cf3d3656b46d940db4f08e379931b6
Python
1,017
40
TEAL = "#4e938d" DARKTEAL = "#27474a" DARKERTEAL = "#225b62" PURPLE = "#8661c5" YELLOW = "#ffb900" MIDTEAL = "#49c5b1" GREY = "#d9d9d6" DARKYELLOW = "#A2790D" ORANGE = "#ffa38b" BRAND_LIGHT_BROWN = "#e1d3c7" BRAND_BROWN = "#bf9474" BRAND_DARK_BROWN = "#5c4738" BRAND_LIGHT_YELLOW = "#ffe399" BRAND_YELLOW = "#ffb900" BR...
51fb441658b7de7d914a501b5f3eab1f3079f3351b2efe2d61673d7eb81d9549
Python
1,018
38
import numpy as np def ball( radi: float, affine_matrix: np.ndarray, ) -> tuple: """ Morphological cell balls and midpoints. Parameters ---------- radi : float Radius of ball. affine_matrix : np.ndarray Affine matrix. Returns ------- tuple Tuple co...
207a29a7dd25f1228803aca66c22a6ec0a2139f4e68ac912861d4985f9ddd313
Python
1,019
29
import numpy as np import loompy from .heatmap import Heatmap from cytograph.species import Species def TF_heatmap(ds: loompy.LoomConnection, dsagg: loompy.LoomConnection, out_file: str = None, layer: str = "pooled") -> None: TFs = Species.detect(ds).genes.TFs enrichment = dsagg["enrichment"][:, :] enrichment = en...
96cc56a42ec83faddd58c3f42670094187eeda271c4d42490103db94ac947a76
Python
1,019
30
# @license # Copyright 2025 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...
a7cd2336f04ed975409b42e6fdbb521de679450df984dafb651f052b36007202
Python
1,021
30
import setuptools with open('README.md', mode='r', encoding='utf-8', errors='ignore') as fh: long_description = fh.read() with open("requirements.txt", "r") as f: requirements = f.readlines() setuptools.setup( name='msi-visual', version='1.0.0', author='Jacob Gildenblat', au...
c2317e78bed87273f511bd424fd0f44b9143b8200b9cc859305b7cbd9b0a1fed
Python
1,021
38
import pytest import numpy as np import os #from ecephys_spike_sorting.modules.quality_metrics.metrics import calculate_metrics #import ecephys_spike_sorting.common.utils as utils #DATA_DIR = os.environ.get('ECEPHYS_SPIKE_SORTING_DATA', False) def te_st_quality_metrics(): sample_rate = 30000.0 numChannels = 384 ...
e557be5cbb0ccd0b16b0fe0cda800536da8f3d1ae9719166db5457853e5ed03c
Python
1,024
45
""" Configuration file for the hybrid transformer model. All hyperparameters and paths are defined here for reproducibility. """ import os class Config: DATA_DIR = "./kvasir-dataset" CLASS_NAMES = [ "Dyed-lifted-polyps", "Dyed-resection-margins", "Esophagitis", "Normal-cecum",...
ee1c9caaab1a567f0ce92d76c8be1cb98e8e8bef0897cb993143713ae9c5c32d
Python
1,025
40
import numpy as np import pytest from scvi.data import synthetic_iid from scvi.external import SCBASSET _DNA_CODE_KEY = "code" def _get_adata(sparse_format: str | None = None): dataset1 = synthetic_iid(batch_size=100, sparse_format=sparse_format).transpose() dataset1.X = (dataset1.X > 0).astype(float) d...
f35ad083d734c90e88efe73a8d2d41d539752749b54af3b6f9295b695a20f1a7
Python
1,028
32
# code from https://github.com/theislab/scanpy/blob/master/docs/extensions/typed_returns.py # with some minor adjustment from __future__ import annotations import re from collections.abc import Generator, Iterable from sphinx.application import Sphinx from sphinx.ext.napoleon import NumpyDocstring def _process_retu...
2a1a339662972047365a83fce66caa10990c5721307d65283526452003ab1446
Python
1,030
29
import numpy as np def asymmetric_mad(data): """ Computes the asymmetric median absolute deviation in a vectorized manner. """ # Calculate the median for each column (axis=0) median = np.nanmedian(data, axis=0) # Calculate absolute deviations from the median # Broadcasting makes this effi...
216c8a0f0c223b0724989eca2e2e94c14314b6d0b9cc249969c96baf488adc4a
Python
1,033
31
import numpy as np from meld_classifier.paths import BASE_PATH, CLIPPING_PARAMS_FILE from meld_classifier.meld_cohort import MeldCohort from meld_classifier.data_preprocessing import Preprocess #Generate feature names features = [] for d in [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]: features.append(f"....
da62f3c2b86299b960fc354ff02c85f7f2ed639f83728f28cbe8a74be82b8426
Python
1,033
32
# -*- coding: UTF-8 -*- """The classic GOEA algorithm: score every GO term independently.""" __copyright__ = "Copyright (C) 2010-present, H Tang et al., All rights reserved." from goatools.goea.algorithms.base import GoeaAlgorithm, GoeaAlgoResult class ClassicAlgorithm(GoeaAlgorithm): """Score each GO term on i...
fa0466b74f9add201e8163df632f126983f1b1503003f9deb02d14fcfb8b2962
Python
1,033
28
# This is just for downloading the generator. See `discrimination/` for the discrimination checkpoints import os import requests import argparse parser = argparse.ArgumentParser(description='Download a model!') parser.add_argument( 'model_type', type=str, help='Valid model names: (base|large|mega)', ) mod...
94491e443da33a59ceb91663dfdd083e368346f8eff91359c36d6e86a0b931fd
Python
1,034
36
from __future__ import annotations import logging import os import webbrowser from pathlib import Path from src import path_config logger = logging.getLogger(__name__) def is_wsl() -> bool: """Return True when running under Windows Subsystem for Linux.""" return bool(os.environ.get("WSL_DISTRO_NAME")) de...
cb78c62831859158e5f3d94de7a2c263c26fb628a92ed9e4ff4ece00acc148b7
Python
1,034
38
"""Create individual experiment files for a parameter sweep.""" from itertools import product from pathlib import Path import yaml def set_value(dct, keys, val): for key in keys[:-1]: if isinstance(dct, dict) and key in dct: dct = dct[key] else: raise KeyError(f"{keys} do...
45432d349d8aa471a7a8ff137fc3ecdb8e2c7b987a3c36bfebe6a0f5a5c33889
Python
1,035
31
import sys import os f1 = sys.argv[1] output_folder = os.path.dirname(f1) fp=f1.strip().split('/')[-1].split('_')[0] mode = sys.argv[2] chromosomes = ['chr' + str(i) for i in range(1, 23)] chromosome_dict = {chromosome: -1 for chromosome in chromosomes} file_list=[] with open(f1,'r') as all: for chr_n...
d1d5113ac3a012344fe68ef808adc66f380f50ad2bbdc636cfddb25cbea060f0
Python
1,036
31
from brenda_references.docdb import BrendaDocDB import pathlib TEST_DIR = pathlib.Path(__file__).parent.parent / "tests" if __name__ == "__main__": with ( BrendaDocDB() as maindb, BrendaDocDB( path=str(TEST_DIR / "test_files/testdb.json"), create=True ) as testdb, ): ...
d52d29ced16f76af6b459ca4c5f4e82aec840a1fd2bc06d91c325cfa1ced0806
Python
1,037
30
import numpy as np # some def asymmetric_mad(data): """ Computes the asymmetric median absolute deviation in a vectorized manner. """ # Calculate the median for each column (axis=0) median = np.nanmedian(data, axis=0) # Calculate absolute deviations from the median # Broadcasting makes th...
4f5154815dc778c67043d8129ecf40f9a92e281bf45985fe5d4dfd5ec7cf0f8d
Python
1,039
38
import logging log = logging.getLogger(__name__) class ColorFormatter(logging.Formatter): grey = "\x1b[38;20m" blue = "\x1b[36;20m" yellow = "\x1b[33;20m" red = "\x1b[31;20m" bold_red = "\x1b[31;1m" reset = "\x1b[0m" prefix = "[%(levelname)s] (%(name)s)" suffix = "%(message)s" F...