sha256 stringlengths 64 64 | language stringclasses 27
values | size int32 1 491k | lines int32 1 21.8k | content stringlengths 1 200k |
|---|---|---|---|---|
e81f4bc9a4690f50f496c16cda6774388dc5ef247f49a801b2512dc29e932770 | Python | 475 | 17 | """One-shot import of plugin registration modules (datasets / models / tasks)."""
from __future__ import annotations
_loaded = False
def ensure_plugins_loaded() -> None:
"""Import plugin side-effect modules exactly once per process."""
global _loaded
if _loaded:
return
import dat... |
65028be86aac2be178072e8e139fae64fb5666b2c4d74c06467b21a1913ad5ff | Python | 476 | 19 | from PyQt5 import QtCore, QtGui, QtWidgets
class alert_dialog(QtWidgets.QMessageBox):
def __init__(self, msg, _parent, icon=QtWidgets.QMessageBox.Information):
super().__init__(parent=_parent)
self.setText(msg)
self.setIcon(icon)
self.setWindowTitle("Info")
self.setStandardButtons(QtWidgets.QMessageBox.Ok)
... |
e8d2218f23cfd5dc00295db23b5f94b551891e5b2136d4a518a0702d22645e5f | Python | 476 | 13 | # 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.
"""isort:skip_file"""
from .fairseq_nat_model import *
from .nonautoregressive_transformer import *
from .nat_crf_transformer import *
from .i... |
eda4049f3fdb36a54a63cfb953968ab145e04fab4512d28b83ea01e55485ce98 | Python | 476 | 16 | import argparse
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.txn() as s:
s... |
942354548ca2627b9f00ff8f58efe9515a5eaadad1aff52e08789cded221281c | Python | 477 | 19 | import json
import pathlib
from brenda_references import relation_records
TEST_FILES = pathlib.Path(__file__).parent / "test_files"
with (TEST_FILES / "3170582.json").open() as test_file:
test_doc = json.load(test_file)
def test_relation_records() -> None:
assert relation_records(test_doc) == [
{
... |
b3adfe17644837bdf9217cbadb66ebc12b0b784ebcd529c2f84f612839669cd9 | Python | 477 | 17 | from typing import NamedTuple
class _METRIC_KEYS_NT(NamedTuple):
TRAINING_KEY: str = "training"
VALIDATION_KEY: str = "validation"
# classification
ACCURACY_KEY: str = "accuracy"
F1_SCORE_KEY: str = "f1_score"
CALIBRATION_ERROR_KEY: str = "calibration_error"
AUROC_KEY: str = "auroc"
CL... |
9fca2307b626465a3dcb65ec771b1f0413f404652b2f996a65e39f487c9ff1bc | Python | 478 | 19 | # Tokens
ADENINE_TKN = 'A'
CYTOSINE_TKN = 'C'
URACIL_TKN = 'U'
GUANINE_TKN = 'G'
THYMINE_TKN = 'T'
INOSINE_TKN = 'I'
ANY_NUCLEOTIDE_TKN = 'N'
# Tokens from https://en.wikipedia.org/wiki/FASTA_format
RNA_TOKENS = [ADENINE_TKN, CYTOSINE_TKN, GUANINE_TKN, THYMINE_TKN, INOSINE_TKN, "R", "Y", "K", "M", "S", "W", "B"... |
ccad07511ebae77f04b643263b0c7036bda3d8486d08a05543bdfdf69bdede30 | Python | 478 | 22 | """
Minimal example for generating the four-channel OSH representation.
"""
from pathlib import Path
import numpy as np
from PIL import Image
from osh import build_multiscale_osh
INPUT_IMAGE = "input.png"
OUTPUT_FILE = "osh_representation.npy"
img = Image.open(INPUT_IMAGE).convert("L")
img = np.asarray(img, dtype=n... |
7cc26670ae509dc437dce4e0e3afdbeb1eb010c506ebab7cdac20bb2429c7a0f | Python | 479 | 22 | """Create individual experiment files for a parameter sweep."""
from itertools import product
from pathlib import Path
import yaml
FNAME = Path("exp.yaml")
with open(FNAME, "r") as f:
data = yaml.safe_load(f)
INIT_NOISE = [0.0, 0.2, 0.4, 0.6, 0.8, 1.0]
for i, (noise,) in enumerate(
product(
INIT_NO... |
4020857e17b70c2ff02cdc161f2376b4541567f38c9b126d8b4b53c8dcd3e479 | Python | 481 | 18 |
import numpy as np
from tractseg.experiments.base import Config as BaseConfig
class Config(BaseConfig):
EXPERIMENT_TYPE = "dm_regression"
LABELS_TYPE = "float"
THRESHOLD = 0.01 # Binary: 0.5, Regression: 0.01 ?
LR_SCHEDULE = False
# DATASET = "HCP" # HCP / HCP_32g
# RESOLUTION = "1.25m... |
90966ba944e627420b574074103149d108bcfd62778c60bd2d6713881bd616e3 | Python | 481 | 17 | # 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 .image_dataset import ImageDataset
from .path_dataset import PathDataset
from .mae_image_dataset import MaeImageDataset
from .mae_finetun... |
2271f723feff58adf2bc3d0975e5d67cdfcd1b3f08a61b061ed26591336d8309 | Python | 482 | 15 | # 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 importlib
import os
for file in sorted(os.listdir(os.path.dirname(__file__))):
if file.endswith(".py") and not file.startswith("_... |
e7f06fe088a9a3c33b03739778d4ac60ef61b746aeadb73df1069396cd80b219 | Python | 482 | 19 | """
SemanticST: Spatially informed semantic graph learning for effective clustering and integration of spatial transcriptomics.
"""
__version__ = "0.1.0"
__author__ = "Roxana Zahedi"
__email__ = "r.zahedi_nasab@unsw.edu.au"
# Import core functions for easier access
from .SemanticST_main import *
from .Semantic_graphs... |
90f5011b07157d8013c00aa3ed6c960c84065cfe59d9c969f98bc4c4b4cf606e | Python | 483 | 18 | import gl
gl.resetdefaults()
gl.meshload('BrainMesh_ICBM152.rh.mz3')
gl.meshcurv()
gl.overlayminmax(1,-1,1)
gl.overlaycolorname(1,'surface')
gl.overlayinvert(1,1)
gl.overlayload('motor_4t95vol.nii.gz')
gl.overlaycolorname(2,'kelvin')
gl.overlayminmax(2,2,7)
gl.overlayload('scalp.mz3')
gl.overlaycolorname(3,'gold')
#gl.... |
dabd8640eab4196468e875a377cff1a7a2af4317e237635b0e2e6d5fceb30a02 | Python | 484 | 19 | from __future__ import annotations
import sys
from pathlib import Path
from typing import TYPE_CHECKING
from poetry.utils.env import SystemEnv
if TYPE_CHECKING:
from pytest_mock import MockerFixture
def test_get_marker_env_untagged_cpython(mocker: MockerFixture) -> None:
mocker.patch("platform.python_ver... |
8d7389266302fbb9d3953396f9ee9ffaf1dcc3a87f2d67d0bab98c903484a134 | Python | 485 | 14 | from paper2.preprocess_select import choose_preprocess, CANDIDATES
from paper2.loaders import load_coffee, load_juice
def test_returns_valid_candidate():
p, r2 = choose_preprocess(load_coffee(), seed=0)
assert p in CANDIDATES
assert -5.0 <= r2 <= 1.0
def test_aqueous_juice_prefers_a_derivative():
""... |
c6300b19207ec668fcc267c97f1559f0f74bf87390d32c89016806bcd4e41b1c | Python | 485 | 20 | import threading
from benchmark.runner import JobManager
from configs import LOGGER
from utils.argparser import get_args_cli
from utils.helper import UploadS3Thread
def start_s3_sync():
stop_flag = threading.Event()
upload_s3_thread = UploadS3Thread(stop_flag)
upload_s3_thread.start()
if __name__ == "_... |
cf72d4f75fad786c1b203e76a216d91bc7e46f169904da27e31adce10aa1d7fc | Python | 485 | 18 | # 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 . import BaseWrapperDataset
class RollDataset(BaseWrapperDataset):
def __init__(self, dataset, shifts):
super... |
0bc20176f7fa6e94e85ed597e48d0e38892ae0dd52793a947b838517411a06ca | Python | 486 | 28 | from torch.nn.functional import one_hot
from ._base_components import (
Decoder,
DecoderSCVI,
DecoderTOTALVI,
Encoder,
EncoderTOTALVI,
FCLayers,
LinearDecoderSCVI,
MultiDecoder,
MultiEncoder,
)
from ._embedding import Embedding
__all__ = [
"FCLayers",
"Encoder",
"Encode... |
44d6b297f9d1f29e444e7899740a3b7634cf57bcec5fc825eeacc5d195fb5f54 | Python | 486 | 16 | """
Optimizer and Learning Rate Scheduler Utilities
Provides optimizer setup (SGD, Adam, AdamW) and learning rate scheduling
(cosine with warmup, step LR, cosine annealing with warm restarts).
"""
from neurovfm.optim.utils import get_optimizer_scheduler, get_optimizer_scheduler_ez
from neurovfm.optim.cosine_schedule_... |
8f5e8d6f987dbf388e7f9da7d2e974fc874f74bc1f5043649437688f14f34e0a | Python | 486 | 20 |
import numpy as np
from tractseg.experiments.base import Config as BaseConfig
class Config(BaseConfig):
EXPERIMENT_TYPE = "peak_regression"
CLASSES = "20" # All / 11 / 20 / CST_right
BATCH_SIZE = 44 #torch 0.3: 44
LOSS_WEIGHT = 5
LOSS_WEIGHT_LEN = -1 # nr of epochs
LABELS_TYPE = "floa... |
5eeba70f23c9f743350691603afaf93e51ef1601c6bc96340596c9e1575eb72c | Python | 487 | 19 | import pytest
import torch
TRAINER_TABLE = [
{"accelerator": "cpu", "devices": 1}
]
if torch.cuda.is_available():
{"accelerator": "gpu", "devices": [0]}
@pytest.fixture(params=TRAINER_TABLE)
def trainer_table(request):
"""Parametrized 'trainer' table for config file
Causes any test using this :func... |
b51b1cb1391a019b3e88c48352803370265f1bccdd0a5498da95747d68a02020 | Python | 487 | 15 | from .base import BaseParameterEstimator, DiscreteParameterEstimator, GaussianParameterEstimator
from .discrete_bayesian import DiscreteBayesianEstimator
from .discrete_em import DiscreteEM
from .discrete_mle import DiscreteMLE
from .linear_gaussian_mle import LinearGaussianMLE
__all__ = [
"BaseParameterEstimator"... |
b6e6adf068075f77cdce41a5c485809f5126d59e66854433d545429c7b2c7b43 | Python | 487 | 15 | # 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 importlib
import os
for file in os.listdir(os.path.dirname(__file__)):
if file.endswith(".py") and not file.startswith("_"):
... |
d053a1a526d479f7fce785c7cfcb9fa3db263a29859a608ec418ea04675d3786 | Python | 487 | 21 | from PyQt5.QtWidgets import QDoubleSpinBox
__author__ = 'Robbert Harms'
__date__ = "2017-01-26"
__maintainer__ = "Robbert Harms"
__email__ = "robbert@xkls.nl"
class QDoubleSpinBoxDotSeparator(QDoubleSpinBox):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def valueFromText(s... |
1ca0a04dd841e7942243ea2d7533e0f1e7f4d409f5ceb9cda446387185ada63a | Python | 488 | 12 | """
Run this to generate a macOS PKG background with
the conda-forge anvil logo in the bottom left corner
"""
# needs 'pillow' package
from PIL import Image, ImageOps
# logo taken from https://github.com/conda-forge/marketing/084d589/main/logo/just_anvil_black.png
logo = Image.open("just_anvil_black.png")
background... |
e017a63c9a9cf5397ec8298782b68688e434bc145a710d9330b5153ff8540945 | Python | 488 | 21 | # -*- coding: utf-8 -*-
# Copyright (C) 2018, 2023 Phillip Alday <me@phillipalday.com>
# License: BSD (3-clause)
"""Epoch manipulation tests."""
from nose.tools import assert_dict_equal, assert_raises
from philistine import invert_dict
def test_invert_dict():
"""Test that dictionary inversion works."""
d = ... |
202247001430a56ea98591ef293a9389210959848d2978e126cdae444fce9338 | Python | 489 | 22 | #!/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 regex
import sys
def main():
filter_r = regex.compile(r"[^\p{L}\p{N}\p{M}\' \-]")
for line in sys.std... |
a34994eb7f226a828749de8118f0b2b2433258dafc4d9ac537b2fad1daf75eb8 | Python | 489 | 19 | from ... import options as opts
from ... import types
from ...charts.chart import ThreeAxisChart
from ...globals import ChartType
from ...options import InitOpts, RenderOpts
class Surface3D(ThreeAxisChart):
"""
<<< 3D Surface-Chart >>>
"""
def __init__(
self,
init_opts: types.Init = I... |
3b7e64c0a2918c9f21da489862e59eeac8afbe29a8c4a966a1852d1ac665b0cb | Python | 490 | 21 | import unittest
from pyecharts.faker import Faker, Collector
class TestFaker(unittest.TestCase):
def test_rand_color(self):
rand_color = Faker.rand_color()
assert rand_color is not None
def test_img_path(self):
self.assertEqual(Faker.img_path(path="/usr/local"), "/usr/local")
d... |
4c52d54c0d6dc6148541404532e224636445e11bffccd31daa7272238f71db5b | Python | 492 | 13 | # 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 .berard import * # noqa
from .convtransformer import * # noqa
from .multi_modality_model import * # noqa
from .s2t_conformer import * ... |
ed48436bc80f5d85cebc1602559b3fc47e35f2f901c8976ab46033ab6bd0068b | Python | 492 | 23 | #!/usr/bin/env python3
from .distr import STDDMaker
from .funcs import (
alpha_PSP,
cutoff_PSP,
exp_PSP,
exp_window,
rect_PSP,
tail_PSP,
valpha_PSP,
vcutoff_PSP,
vexp_PSP,
vrect_PSP,
vtail_PSP,
)
from .ppd import PPDMaker
__all__ = ["rect_PSP", "exp_PSP", "cutoff_PSP", "tai... |
0054cff8dcaa794e1dd8f3e1dc07fde884185199d338a3e042d5c4bbc04acac7 | Python | 493 | 17 | from ._base_components import BSSeqMixin, BSSeqModuleMixin, DecoderMETHYLVI
from ._constants import METHYLVI_REGISTRY_KEYS
from ._methylanvi_model import METHYLANVI as METHYLANVI
from ._methylanvi_module import METHYLANVAE
from ._methylvi_model import METHYLVI as METHYLVI
from ._methylvi_module import METHYLVAE
__all_... |
9f428e958f7fe87132dbb4a39d1bb53af93258fbd2f84b84a2ac9d0c382eb8a6 | Python | 495 | 15 | from typing import Dict, Tuple
import jax.numpy as jnp
from typing_extensions import TypeAlias
RNGKey: TypeAlias = jnp.ndarray
Embedding: TypeAlias = jnp.ndarray
Tokens: TypeAlias = jnp.ndarray
Labels: TypeAlias = jnp.ndarray
Images: TypeAlias = jnp.ndarray
AttentionMask: TypeAlias = jnp.ndarray
SequenceMask: TypeAli... |
ebeb2ec40acd18db79f90e78eb03c1010d5500d66fbb01424027e5e015fe928e | Python | 496 | 14 | from .egnn_model import EGNN_simple, EGNN_simple_masked, EGNN_simple_mhc_masked
from .stag_model import STAG, STAG_masked, STAG_mhc_masked
from .egnn_dual_model import (
EGNN_dual_simple,
EGNN_dual_HLA_simple,
EGNN_dual_simple_v2,
EGNN_dual_HLA_simple_v2,
EGNN_dual_simple_v3,
EGNN_dual_HLA_simpl... |
671b8e4cf0c2bf8590322a2535af3f757ada169cd823b5170b9b6ec8d44a159e | Python | 497 | 16 | from __future__ import annotations
from poetry.core.masonry.api import build_sdist
from poetry.core.masonry.api import build_wheel
from poetry.core.masonry.api import get_requires_for_build_sdist
from poetry.core.masonry.api import get_requires_for_build_wheel
from poetry.core.masonry.api import prepare_metadata_for_b... |
2785f8208cd8240e2415e69a9c51696614c7fa5cc4be97b1ca680f1cfced1486 | Python | 499 | 21 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import unittest
from tractseg.data import dataset_specific_utils
class test_functions(unittest.TestCase):
def setUp(self):
pass
def test_bundle_names(self):
bundles = dataset_speci... |
d219f88dba2cfe280068eedbd945939f5c6bd50f2284891340093f31d5d15615 | Python | 502 | 17 | from distutils.core import setup
from Cython.Build import cythonize
from distutils.extension import Extension
import numpy as np
ext_modules=[
Extension("moving_least_squares", \
sources=['src/moving_least_squares.pyx'], \
include_dirs=[np.get_include()])
]
setup(name='moving_l... |
12a60c79b47b6a257f2016fbef71c5ed95b40d2b1cc8ca1d34b7d6b74d32b6a5 | Python | 503 | 15 | import os
here = os.path.abspath(os.path.dirname(__file__))
about = {}
with open(os.path.join(here, "pyecharts", "_version.py")) as f:
exec(f.read(), about)
UNINSTALL = "{} uninstall pyecharts -y"
INSTALL = "{} install -U dist/pyecharts-{}-py3-none-any.whl --no-cache-dir"
os.system("python setup.py bdist_wheel")... |
6a0ebb02a280bb3c11a16e4ac4f0e36649863d5503d73dc4edbc0187504edcff | Python | 504 | 16 | import argparse
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.txn() as s:
s... |
fbd288104b1ddf1078bdd5fe676bcfff777a10348dd5407662a6c48e6bda36ba | Python | 504 | 12 | from distutils.core import setup
from setuptools import find_packages
setup(name='mutex',
version='1.0.1',
description='A simple algorithm to estimate the significance of a mutual exclusive pattern or co-occurrence',
author='Michael P Schroeder',
author_email='michael.p.schroeder@gmail.com',
... |
6443d3d8f05860d0e1adfdf3832b30bac2790a8532666988a32945ea1d797914 | Python | 505 | 21 | from __future__ import annotations
import runpy
from typing import TYPE_CHECKING
import pytest
if TYPE_CHECKING:
from pytest_mock import MockerFixture
def test_module_entrypoint_exits_with_application_status(mocker: MockerFixture) -> None:
main_mock = mocker.patch("poetry.console.application.main", side_... |
6f9d5d63b276843d13bec9e637d98a008e14e2ee1a0fb251b24726cf353ca036 | Python | 506 | 15 | import pandas as pd
from st_risk.data.harmonize import choose_reference_celltype_column, intersect_gene_names
def test_intersect_gene_names_preserves_shared_order():
visium = pd.Index(["A", "B", "C"])
ref = pd.Index(["B", "C", "D"])
shared = intersect_gene_names(visium, ref)
assert list(shared) == ["... |
142f9ee88925f447afaceecb0bd3c85a7cf86d28c6e38cb7e24c44af3a0d006d | Python | 509 | 28 | from . import functional as F
__all__ = [
"Accuracy",
]
class Accuracy:
"""standard supervised learning classification accuracy.
Parameters
----------
y_pred : torch.Tensor
y_true : torch.Tensor
Returns
-------
acc : float
between 0 and 1. Sum of predicted labels that e... |
7a272cdef60024a07eb1efed75271dcb3d5efb514824b68c838efc4039bee018 | Python | 509 | 19 | from __future__ import annotations
import json
from pathlib import Path
from typing import Any
import anndata as ad
def load_manifest(path: str | Path) -> dict[str, Any]:
with Path(path).open("r", encoding="utf-8") as handle:
data = json.load(handle)
if not isinstance(data, dict):
raise Valu... |
cdae4d204ac81e42a3ddde8df22df0ca568ca787244db52fe1321585ac648d3e | Python | 509 | 27 | import jax
import pytest
from oneqmc.molecule import Molecule
from oneqmc.types import Psi
@pytest.fixture
def mol():
return Molecule.from_name("LiH")
@pytest.fixture
def rng():
return jax.random.PRNGKey(12)
@pytest.fixture
def wf():
def _wf(*args, return_finetune_params=False, return_det_dist=False)... |
acea415eed3d1abdc2c49f0596486a5301b94c458f47564e52f93cbe0ee0cbc8 | Python | 510 | 21 | import pandas as pd
from torch.utils.tensorboard import SummaryWriter
import vak.common.tensorboard
FILENAME_SUFFIX = "FakeModelName"
def test_summary_writer(tmp_path):
writer = vak.common.tensorboard.get_summary_writer(
log_dir=str(tmp_path), filename_suffix=FILENAME_SUFFIX
)
assert isinstance... |
b0d584195531c81f98eedff6fd94a65a4c6d388b83ebac240e8efe38c03a0003 | Python | 510 | 17 | import importlib
import os
# ASG loss requires flashlight bindings
files_to_skip = set()
try:
import flashlight.lib.sequence.criterion
except ImportError:
files_to_skip.add("ASG_loss.py")
for file in sorted(os.listdir(os.path.dirname(__file__))):
if file.endswith(".py") and not file.startswith("_") and f... |
69ac2952e5134620efe323f838d27b4d31e1172a1278b363c86113a63d53e0cd | Python | 512 | 21 |
import numpy as np
import time
def total_ion_count(img):
return img / (1e-6 + np.sum(img, axis=-1)[:, :, None])
def median_ion(img):
return img / (1e-6 + np.median(img, axis=-1)[:, :, None])
def spatial_total_ion_count(img):
t0 = time.time()
processed = total_ion_count(img)
pr... |
ae5879670d7fdaf003673f36091be39185caffc94f87fe6f70f2fb48221ed71c | Python | 513 | 16 | import pandas as pd
def preprocess_synaptic(segments, values):
currents = list(segments.keys())
dfs = []
for curr in currents:
seg = segments[curr]
val = values[curr]
df = pd.DataFrame(data=val, index=seg)
df = df.reset_index()
df_summed = df.groupby('index', as_ind... |
45300ed9b3f65f66ad26a1f4ed992959cba1a5bacbfca4cf3b56c7fb5d326863 | Python | 514 | 19 | """
PyTorch Lightning Systems for Vision Model Training
Training systems for self-supervised pretraining and supervised fine-tuning.
"""
from .pretraining import VisionPretrainingSystem, VisionNetwork
from .classification import VisionClassificationSystem
from .utils import NormalizationModule
from .llm_sft import Vi... |
c2453b9d0403848262b6259511a563c65d748b44ce37398281d5c266a874afca | Python | 514 | 14 | # 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 importlib
import os
# automatically import any Python files in the criterions/ directory
for file in sorted(os.listdir(os.path.dirnam... |
cd3ff141019505dd2f4a5ef5dc1fb5e3485e704f0bf5134033e8b72f34e2d822 | Python | 515 | 17 | """TaskModule wrapper for dynamic segmentation with CID attribution."""
from __future__ import annotations
from omegaconf import DictConfig
from dlbase.registry import TaskModule
from tasks.dynamic_segmentation_CID.run_CID import run_dynamic_segmentation_CID_training
class DynamicSegmentationCIDTask(Task... |
f2d31568730120335a4393b9d94d402f48de5b5ee665c9cc24e15951ea1bad79 | Python | 516 | 20 | """
Dataloader utils for project
(highly inspired by/credit to: https://github.com/neuroailab/VisualCheese)
"""
import numpy as np
def duplicate_channels(gray_images):
"""
Converts single channel grayscale images into rgb channel images
Input:
gray_images : (N,H,W)
Output:
rgb : (N,H... |
a60db3062260a0bdfaab36e2f66eded0daab0766b4a384c0a97d9830fe007c52 | Python | 517 | 13 | import torch
from torch.optim.lr_scheduler import CosineAnnealingLR
from nnunetv2.training.nnUNetTrainer.nnUNetTrainer import nnUNetTrainer
class nnUNetTrainerCosAnneal(nnUNetTrainer):
def configure_optimizers(self):
optimizer = torch.optim.SGD(self.network.parameters(), self.initial_lr, weight_decay=sel... |
0635030965b2b4a9f4c81f1ba38ceae4adc9092f587859e28705abc24d47e460 | Python | 518 | 10 | import numpy as np
filepath_1 = 'D:/Dataprocess/DATA/20240517/SerialAveraged_results/Electrical_Serialaveraged/Averaged_result32'
filepath_2 = 'D:/Dataprocess/DATA/20240517/SerialAveraged_results/Electrical_Serialaveraged/Averaged_result94'
for i in range(450):
img1 = np.load(filepath_1+'/averaged%d.npy'%(i+1))... |
14d4011274150235bfa223c1597ca38096fae2281ec72466e0ac4640abf15051 | Python | 519 | 25 | from pgmpy.datasets._base import BaseCovarianceDataset
class Spartina(BaseCovarianceDataset):
"""
References
----------
- :footcite:t:`spirtes_glymour_scheines_2001`
"""
_tags = {
"name": "spartina",
"n_variables": 15,
"n_samples": 45,
"is_continuous": True,
... |
45960a24dfe84c20b9f7088652a34a69e5f5caaf37a18ca665c9fe8d09f9cded | Python | 519 | 4 | cn = {'P':0,'M':1,'A':2,'B':3}
radii = {'ALA':3.20,'LEU':4.24,'ARG':5.60,'LYS':5.02,'ASN':4.04,'MET':4.47,'ASP':4.04,'PHE':4.99,'CYS':3.65,'PRO':3.61,'GLN':4.64,'SER':3.39,'GLU':4.63,'THR':3.56,'GLY':1.72,'TRP':5.38,'HIS':4.73,'TYR':5.36,'ILE':3.94,'VAL':3.55}
# radius from https://www.ncbi.nlm.nih.gov/pmc/articles/PMC... |
b3ac53f8a6eb1dee73967fe8ceb0e3e0333065ebe777affdc80f11b6a136c44a | Python | 520 | 23 | from mne.utils import check_version
import mne_icalabel.config as iclabel_config
if not check_version("mne_icalabel", "0.5.0"):
raise ImportError(
"mne_icalabel version 0.5.0 or higher is required. "
"Please upgrade mne_icalabel."
)
IC_COLORS = [
"#2c2c2c",
"#003e83",
"cyan",
"g... |
e60ed839efbf60cd32bbd992cbc80d9ce21ac79be87f6b37e20bb57488490623 | Python | 520 | 14 | # 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 importlib
import os
# automatically import any Python files in the criterions/ directory
for file in sorted(os.listdir(os.path.dirnam... |
aae7cdfd0ab2dcea97d91ea706c0031366d2d0fa77537df6913839a85c3a501f | Python | 521 | 24 | from distutils.core import setup
from setuptools import find_packages
requirements = [
"numpy",
"networkx",
"pandas",
"torch",
"shap",
"matplotlib",
]
setup(
author="Erik Hartman",
author_email="erik.hartman@hotmail.com",
name="binn",
version="0.1.1",
packages=find_packages... |
b2f95b84085b4e2f28f4ae1eb0fad1ea658be164d3a1d24d7d05e1e4a679886e | Python | 522 | 13 | def test_basic():
import torch
from tape import ProteinBertModel, ProteinBertConfig, TAPETokenizer # type: ignore
config = ProteinBertConfig(hidden_size=12, intermediate_size=12 * 4, num_hidden_layers=2)
model = ProteinBertModel(config)
tokenizer = TAPETokenizer(vocab='iupac')
sequence = 'GCT... |
079368396da2c4ae870246ebe847d7bbec03fdcdea1a9cdc54f2bd7e545a7989 | Python | 523 | 17 | import torch
from neurovfm.pipelines import load_encoder
# 1. Load encoder + preprocessor from your HF repo
encoder, preproc = load_encoder(
"mlinslab/neurovfm-encoder", # your repo ID
device="cuda" if torch.cuda.is_available() else "cpu",
)
# 2. Preprocess a study (directory or single file)
batch = preproc... |
9e0646cee79dceeb84d36bfadf6a7767c0c1a793bf282fea7af23468d26a6049 | Python | 524 | 26 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from tractseg.experiments.tract_seg import Config as TractSegConfig
class Config(TractSegConfig):
EXP_NAME = os.path.basename(__file__).split(".")[0]
MODEL = "UNet3D_Pytorch_DeepSup_sm"
DIM = "3D"
FP16 = False
UPSAMPLE_TYPE = "trilinear"
... |
fc57036857f822fd9e1b93b65e6fc11388aa767deaf59a00a71608b0d6818b48 | Python | 524 | 21 | import sys
sys.path.insert(0, "../")
from model.embedding import embed
import scanpy as sc
import os
model_dir = "../model/assets"
adata_path = "./data/neftel_ss2.h5ad"
adata = sc.read_h5ad(adata_path)
batch_key = "sample" # The batch identity is used for highly variable gene selection
bio_key = "subtype"
embed_ada... |
c32631e3631876042c0c8b534dd4d07c21ba35caada14261b482c0ac6237d1ab | Python | 526 | 17 | # 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.
"""isort:skip_file"""
from .multihead_attention import ModelParallelMultiheadAttention
from .transformer_layer import (
ModelParallelTrans... |
d4d00668be53f661ebb129dfaf2a33cdd2be72915c94f7f7de43ecc14004442d | Python | 527 | 18 | import importlib.metadata
import logging
__version__ = importlib.metadata.version("novae")
from ._logging import configure_logger
from ._settings import settings
from .model import Novae
from . import utils
from . import data
from . import monitor
from . import plot
from .utils import spatial_neighbors, batch_effect_... |
330659734b9e605953fb076ae11ec9f8bafabd733300934f3d25056c3fa4009d | Python | 529 | 15 | class NonexistentCoordinatesException(Exception):
def __init__(self, error_msg, coord_name):
self._error_msg = error_msg
self._coord_name = coord_name
def __str__(self):
return f"当前地点: {self._coord_name} 坐标不存在, 错误原因: {self._error_msg}"
class WordCloudMaskImageException(Exception):
... |
48c490952f39ff01c3d1d647e1d274a1f04a1a5528dd9aec026f00be883357dd | Python | 529 | 25 | from ..render import engine
class ChartMixin:
def add_js_funcs(self, *fns):
for fn in fns:
self.js_functions.add(fn)
return self
def add_js_events(self, *fns):
for fn in fns:
self.js_events.add(fn)
return self
def load_javascript(self):
ret... |
74a8243b56f8ac425307f083d9153635826001d511d0a93a2cc752dcaffc2ef6 | Python | 529 | 16 | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
from enum import Enum
from typing import Mapping, Union
class ModelTarget(Enum):
"""Specifies what the score model is trained to predict.
Only relevant for fields that are corrupted with an SDE."""
score_times_std = "score_times_st... |
de1a5ffb0292fe59a75ffdb7572bafbcbb6cb00235ca9ebee582997282b54800 | Python | 531 | 11 | from views import _1_overview as page_1_overview
from views import _2_benchmark as page_2_benchmark
from views import _3_stability as page_3_stability
from views import _4_config as page_4_config
from views import _5_subject as page_5_subject
from views import _6_da as page_6_da
from views import _7_mechanism as page_7... |
538b212e324eb2a09b7c2855e8e6536007a575045bfc6fce2d965e4c364f0145 | Python | 532 | 23 | from __future__ import annotations
import subprocess
from setuptools import setup
if subprocess.call(["exit-code"]) != 42:
raise RuntimeError("Wrong exit code.")
kwargs = dict(
name="project-with-setup-calls-script",
license="MIT",
version="0.1.2",
description="Demo project.",
author="Sébast... |
641c316ccfd2de83d41ebbb53c59447891929bfe8f6530f89f33a25a451fb4f5 | Python | 532 | 17 | from __future__ import annotations
from poetry.console.commands.env_command import EnvCommand
class DebugTagsCommand(EnvCommand):
name = "debug tags"
description = "Shows compatible tags for your project's current active environment."
def handle(self) -> int:
for tag in self.env.get_supported_ta... |
05dfaeae240707dad3957e0dcc776135141d874da4c1d38a0f9869aa5c4c60bf | Python | 534 | 21 | import torch
def accuracy(tp, tn, all):
acc = ((tp + tn) / all)
return torch.round(acc * 100, decimals=2)
def precision(tp, fp):
pre = (tp / (tp + fp))
return torch.round(pre * 100, decimals=2)
def recall(tp, fn):
sn = (tp / (tp + fn))
return torch.round(sn * 100, decimals=2)
def specificity... |
ab03baf4f252f898dec8f924f65531ecd841d0ce97e2647f35d390eeea4a452b | Python | 534 | 17 | import unittest
from GMXMMPBSA.utils import residue_names_match
class ReferenceResidueMatchingTest(unittest.TestCase):
def test_terminal_prefixes_match_base_residue_names(self):
self.assertTrue(residue_names_match('NVAL', 'VAL'))
self.assertTrue(residue_names_match('ALA', 'CALA'))
def test_u... |
65348565a4cbdd9587c2ea23fc188071a66f03308dc9b07b19fbdfa755321d43 | Python | 535 | 22 | import subprocess
def capture(command):
result = subprocess.run(command, capture_output=True, text=True)
return result.stdout, result.stderr, result.returncode
def test_cli_just_vak():
command = ["vak"]
out, err, returncode = capture(command)
assert returncode > 0
assert out == ''
assert... |
4d0c75dd9622427ed902f910f1c7c3771ae9c278fae978ed92a66b5f0060cac1 | Python | 536 | 22 | """GEARS version file
"""
# Based on NiLearn package
# License: simplified BSD
# PEP0440 compatible formatted version, see:
# https://www.python.org/dev/peps/pep-0440/
#
# Generic release markers:
# X.Y
# X.Y.Z # For bug fix releases
#
# Admissible pre-release markers:
# X.YaN # Alpha release
# X.YbN # Beta release
# ... |
c870a14efb2f07e620940816e592c1b4a3f833e9021578f7f72a877cf784a12c | Python | 537 | 11 | import numpy as np
def eigs(p): return np.linalg.eigvals(np.load(p))
wr = eigs(r".\exp_remote_sim\K_weight.npy")
wc = eigs(r".\exp_recent_sim\K_weight.npy")
def summary(name, w):
m=np.abs(w)
print(name, "mean|eig|={:.4f} near-unit(|eig|>0.95)={}".format(m.mean(), (m>0.95).sum()))
summary("REMOTE(sim)", ... |
c6deb066a4e64a7bf37a9c1be33dc9e602dbdce3fb0d854da87752879c495a7b | Python | 538 | 20 | import torch
def accuracy(y_pred, y_true):
"""standard supervised learning classification accuracy:
Sum of predicted labels that equal true labels, divided by number of true labels.
Parameters
----------
y_pred : torch.Tensor
y_true : torch.Tensor
Returns
-------
acc : float
... |
d561751c4f4f27c74e777b8a9aa4bd3f2be82441c8d2feafbe950e6f68dee6f6 | Python | 538 | 17 | """Helper functions that return names of directories
generated during a run of a learning curve."""
def train_dur_dirname(train_dur: float) -> str:
"""Returns name of directory for all replicates
trained with a training set of a specified duration,
``f"train_dur_{train_dur}s"``.
"""
return f"train... |
20e83926edff9961a0c1d484e8f08a4164aee23332c21fc157a3afe34a32163d | Python | 539 | 20 | import ramanspy as rp
from . import utils
PREPROCESSING_PIPELINE = rp.preprocessing.Pipeline([
rp.preprocessing.misc.Cropper(region=(300, None)),
rp.preprocessing.despike.WhitakerHayes(kernel_size=3, threshold=6),
rp.preprocessing.denoise.Whittaker(lam=1e3, d=3),
rp.preprocessing.baseline.ASLS(lam=1e... |
d855b4a22e8b80bc1691d5a4e91c44d4fb08aea12d0e1522da41b1f03f8badc6 | Python | 539 | 12 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from tractseg.experiments.tract_seg import Config as TractSegConfig
class Config(TractSegConfig):
EXP_NAME = os.path.basename(__file__).split(".")[0]
DATASET_FOLDER = "HCP_preproc" # name of folder that contains all the preprocessed subjects (each... |
61b87ec09b8620cbf4e2ce8f0d14f9d3dc5bc381ba162957a159f8273e2c70af | Python | 540 | 21 | #!/usr/bin/env python
from setuptools import find_packages, setup
setup(
name="SubClustGO",
version="0.0.1",
description=".",
author="Gökçe Uludoğan",
author_email="",
url="",
install_requires=["lightning", "hydra-core"],
packages=find_packages(),
# use this to customize global com... |
6b19d457c01ec1dd44e99d6bed265218384082c90e6505493f50ec549144e1b2 | Python | 540 | 23 | #!/usr/bin/env python3
import aws_cdk as cdk
from aws_batch.aws_batch_stack import AwsBatchStack
# --------------------------------------------------------------
# User defined values
# --------------------------------------------------------------
ebs_volume_size = 3000
# ------------------------------------------... |
dbfc74c70c7af0456454988c8050b637b519f7837695571f608e60f736d45670 | Python | 540 | 9 | """Garfield: Graph-based Contrastive Learning enable Fast Single-Cell Embedding"""
from ._settings import settings
from ._version import __version__
from . import data, model, modules, nn, preprocessing, trainer, plot, analysis
from .model.Garfield import Garfield
from .data.lightning_datamodule import GarfieldDataModu... |
3dbfdd07a2581a53f19a17ce00fd90ca637acf0fd6e1cdeb981daacba3b84639 | Python | 541 | 16 | import numpy as np
from st_risk.risk.neighbors import inverse_distance_weights, knn_indices
def test_knn_indices_returns_expected_shape():
coords = np.array([[0.0, 0.0], [1.0, 0.0], [2.0, 0.0]])
idx = knn_indices(coords, k=1)
assert idx.shape == (3, 1)
def test_inverse_distance_weights_normalizes_rows(... |
c59c475f52e7b4bc56a7a970978013f80c30f9585be96b3a7b818c450f405b17 | Python | 541 | 19 | import pytest
# this constant defined "by hand" declares all the models for which there are fixtures,
# instead of computing something dynamically e.g. from ``vak.models``.
# Should be used throughout fixtures when we need to get things "by model"
MODELS = [
"TweetyNet",
]
@pytest.fixture
def default_model():
... |
365d39ce2c8982d0f4c300a83acf8bcfdb65ffa003d5cbebf27dc5fec9c08b2e | Python | 542 | 23 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0... |
742adb339d12f822e8a9f5c7a9754045d811d6ca697ef72123c8997fd2b65950 | Python | 542 | 20 | import numpy as np
import pytest
from scvi.data import synthetic_iid
@pytest.fixture
def adata():
anndata = synthetic_iid()
raw_counts = anndata.X.copy()
anndata.layers["raw"] = raw_counts
anndata.obs["cont1"] = np.random.normal(size=(anndata.shape[0],))
anndata.obs["cont2"] = np.random.normal(si... |
a35f201ec76577f4d331c9ea481a10d29a7741a56a062b15e1aa3cbbbae29511 | Python | 543 | 23 | from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any
import pandas as pd
@dataclass(slots=True)
class BaseSpatialModelOutput:
abundance: pd.DataFrame
uncertainty: pd.DataFrame | pd.Series | None = None
metadata: dict[str, Any] = field(default_factory=dict)
... |
c536313c02b8b512b3eca48306a3ee8282935ecb12038a1ffbaf8edc0040d73c | Python | 544 | 14 | from dual_echo_pcasl_ETLAS2_scripts import fit_calibrated_fmri_glm
import click
@click.command()
@click.argument('subject')
@click.argument('session')
@click.option('--rawdata_folder', default="/mnt/projects/ETLAS2/data/rawdata")
@click.option('--dual_echo_pcasl_folder', default="/mnt/scratch/projects/ETLAS2/data/der... |
da073927c437940baa2e4c97c1a0fd418f63fee099a07f33102f57b77ee15b6b | Python | 544 | 26 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from glob import glob
from vlpp.utils import add_suffix
from vlpp.registration import estimatePet2Anat
def main():
anat = "${anat}"
pet = "${pet}"
output = "${participant}${suffix.pet2anat}"
if "${transitional}" == "false":
estimatePet... |
fe5ff59200d240590f12c4a839b6172a1efdcdb255a6a428b84b82ada4d8d5a7 | Python | 544 | 25 | from __future__ import annotations
from typing import TYPE_CHECKING
from poetry.console.commands.command import Command
if TYPE_CHECKING:
from poetry.utils.env import Env
class EnvCommand(Command):
def __init__(self) -> None:
# Set in poetry.console.application.Application.configure_env
se... |
3da001cdea27df6aa5e7eee320716b37472497780c043f4a0c798a6c495fcd3f | Python | 546 | 23 | # 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 . import FairseqDataset
class RawLabelDataset(FairseqDataset):
def __init__(self, labels):
super().__init__()... |
5d19c9a2c464a6e1dd58a0d62bca86f6ad4965408e3d80877add5013987682ec | Python | 547 | 12 | from paper2.validate2 import repeated_group_cv
from paper2.loaders import load_coffee
def test_pooled_fold_count_equals_repeats_times_splits():
ds = load_coffee()
params = {"KAN": {"width_hidden": (3,), "grid": 5, "n_components": 8}}
cv = repeated_group_cv(ds, ["PLS", "KAN"], repeats=2, n_splits=3,
... |
31de3649246696820edc40e9a050799f2fd2df9a84d7490a385c564595fddb2b | Python | 549 | 22 | from __future__ import annotations
from typing import TYPE_CHECKING
from poetry.repositories import Repository
if TYPE_CHECKING:
from poetry.core.packages.package import Package
class LockfileRepository(Repository):
"""
Special repository that distinguishes packages not only by name and version,
b... |
f33020ce00973acbb2fc35c2682ce4aa17b9f5d4127baae37e054b68cd6a612c | Python | 549 | 24 | """Constants used by :mod:`vak.prep`.
Defined in a separate module to minimize circular imports.
"""
from . import frame_classification, parametric_umap
VALID_PURPOSES = frozenset(
[
"eval",
"learncurve",
"predict",
"train",
]
)
INPUT_TYPES = {"audio", "spect"}
DATASET_TYPE_... |
30656e822a9cd530865df1c6df6a6df199299fd407c3ecc56ccb0ad4e2c2c284 | Python | 550 | 18 | import json
import pandas as pd
# Load the JSON data
with open('test_losses_DIFF_conn_2_2PC.json', 'r') as file:
data = json.load(file)
# Convert the JSON data into a long-format DataFrame
long_format = pd.DataFrame(
[(key, value) for key, values in data.items() for value in values],
columns=['Group', 'Va... |
52db3666dbce1ece7d9f77b7baf85b4435283e16796f74aa57460e68307641de | Python | 552 | 14 | from os.path import join, realpath, dirname
BASE_PATH = dirname(realpath(__file__))
DATA_PATH = join(BASE_PATH, '_database')
GENE_PATH = join(DATA_PATH, 'genes')
PATHWAY_PATH = join(DATA_PATH, 'pathways')
REACTOM_PATHWAY_PATH = join(PATHWAY_PATH, 'Reactome')
PROSTATE_DATA_PATH = join(DATA_PATH, 'prostate')
RUN_PATH = ... |
914255f3ce398792a0b45cc67b711f15f77c752cd07d5386ac183a2df0d94a34 | Python | 552 | 32 | """
Test packages' installation.
"""
import pytest
class TestClass:
def test_mapca(self):
import mapca
def test_nibabel(self):
import nibabel
def test_nilearn(self):
import nilearn
def test_numpy(self):
import numpy
def test_sklearn(self):
import sklearn... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.