sha256 stringlengths 64 64 | language stringclasses 27
values | size int32 1 491k | lines int32 1 21.8k | content stringlengths 1 200k |
|---|---|---|---|---|
fbbac41902c9eccac6fa4a6c5c2b8bfac0c31eec17ea21a142bcc472a634bdc6 | Python | 718 | 30 | from __future__ import annotations
import logging
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from logging import LogRecord
from cleo.io.io import IO
class IOHandler(logging.Handler):
def __init__(self, io: IO) -> None:
self._io = io
super().__init__()
def emit(self, reco... |
b125060ef7a1ccd4559a72e55c65153cb7803970ce90dd435f0b1c5f4db5f044 | Python | 720 | 31 | from pydantic import BaseModel
class DataConfig(BaseModel):
train_dataset: str = "all"
val_dataset: str | None = None
class PostTrainingConfig(BaseModel):
n_domains: list[int] = [7, 10]
log_umap: bool = False
log_metrics: bool = False
log_domains: bool = False
save_h5ad: bool = False
... |
f0ed1ae78629ad2d83a684e0d355b49fda24cfcb83b540b6b8fe8e861d6836a2 | Python | 723 | 30 | import torch
from torch.utils.data import Dataset
import pandas as pd
from typing import Union
from pathlib import Path
from rinalmo.data.alphabet import Alphabet
class ncRNADataset(Dataset):
def __init__(
self,
csv_path: Union[Path, str],
alphabet: Alphabet
):
self.data = p... |
3fd2d2ae739a46639c7d4152a4812528ac2bad64809b4cabdf0cfadd1dfeb5f8 | Python | 726 | 22 | """Dataset adapters: a `Schema`, and the loader that indexes its splits.
One module per corpus. `BRENDA_SCHEMA` and `brenda_dataset` resolve lazily
(PEP 562): importing this package, or any of its other submodules, does not
pull in the BRENDA data layer (`brenda_references` and its dependencies).
Only accessing one of... |
6b79735e50eb2dc5bfa95a312f163cb396b8c351499d422490444363066b1bad | Python | 726 | 23 | import pytest
import torch
import vak.nn.functional as F
# adapted from kornia, https://github.com/kornia/kornia/blob/master/test/utils/test_one_hot.py
def test_onehot():
num_classes = 4
labels = torch.zeros(2, 2, 1, dtype=torch.int64)
labels[0, 0, 0] = 0
labels[0, 1, 0] = 1
labels[1, 0, 0] = 2
... |
6d88f6a9b1683c3bbc00b40a1bdc79082ae4e9756827db5d5626b272839911ab | Python | 726 | 19 | from pathlib import Path
import re
import polars as pl
from src.utils import fastq_dir_to_samplesheet
fastq_dir_to_samplesheet("data/SFARI_data", "assets/samplesheet.csv", strandedness="unstranded")
pattern = re.compile(r'([^_/]+_[^_/]+_[^_/]+)_')
pl.read_csv("assets/samplesheet.csv")\
.with_columns(
pl.c... |
40ba41dd56a65cc0a484ece69216c7d096a125aabae685b42ae3baccc31865ce | Python | 727 | 23 | #!/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.
# Use: echo {text} | python tokenize_indic.py {language}
import sys
from indicnlp.normalize.indic_normalize import In... |
4800ef35ad366ed19c298e68a111d45ba92371220f22f9fb69f02cceb2c1aa87 | Python | 727 | 22 | from __future__ import annotations
from typing import TYPE_CHECKING
from poetry.repositories.exceptions import PackageNotFoundError
from poetry.repositories.legacy_repository import LegacyRepository
from poetry.repositories.link_sources.html import HTMLPage
if TYPE_CHECKING:
from packaging.utils import Normaliz... |
d10bee7a01070526f71c87da44a9bd929b396c5f4d50b1b40ed7342662ff31f8 | Python | 727 | 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.
"""
Layer norm done in fp32 (for fp16 training)
"""
import torch.nn as nn
import torch.nn.functional as F
class Fp32GroupNorm(nn.GroupNorm):... |
ea14cc56d466c5f188394d7e088f5b5c9e6d20dca1c73af7c92ef2cebf97b338 | Python | 727 | 33 | import asyncio
import sys
from multiprocessing import freeze_support
if sys.platform == 'win32':
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
import nest_asyncio
try:
from rnalysis.gui import gui
except Exception as e: # if running into related to cache, delete the cache and try a... |
210b2f2b89535d3ac16460ca7d1e41d9acd47df11bab4ec10a6c6f1669f18e48 | Python | 729 | 32 | # 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 . import BaseWrapperDataset
class ListDataset(BaseWrapperDataset):
def __init__(self, dataset, sizes=None):
super().__init_... |
44d64e211302deb89d61f5f989cf60cd64fcb601cdeaaf643f940cf03d4d9d48 | Python | 730 | 16 | """patternsim — minimal pattern-analysis code for
"Music Evokes Shared Neural Representations of Imagined Narratives Across
Sensory Modalities" (Nature Communications).
A focused, runnable subset of the full analysis package covering three methods:
- neural pattern similarity (single-condition and triple / across-cond... |
8f085ac5de0098045013bbad2aa17316e3735980b34748f75dda2db437dad61e | Python | 731 | 31 | import cv2
import sys
import numpy as np
import random
from msi_visual.metrics import MSIVisualizationMetrics
from msi_visual.normalization import total_ion_count
src = cv2.imread(sys.argv[1])[:, :, ::-1]
dst = cv2.imread(sys.argv[2])[:, :, ::-1]
img = total_ion_count(np.load(sys.argv[3]))
res = cv2.seam... |
362d5196985c9dc8d95f7da4bea6ea5cf3c6f937168b7b894832045256edd822 | Python | 733 | 15 | import pytest
class TestBICGauss:
def test_local_score_no_parents(self, bic_gauss_score):
assert bic_gauss_score.local_score(variable="A", parents=()) == pytest.approx(-124.3254, abs=1e-3)
assert bic_gauss_score.local_score(variable="B", parents=()) == pytest.approx(-261.6093, abs=1e-3)
def t... |
9d77a5e37d5ee47828aa04116a6db33d12968787c0281f631913487d1182abfa | Python | 736 | 26 | """fixtures for testing ``torch``-specific functionality"""
# adapted from kornia, https://github.com/kornia/kornia/blob/3606cf9c3d1eb3aabd65ca36a0e7cb98944c01ba/conftest.py
from typing import Dict
import pytest
import torch
def get_test_dtypes() -> Dict[str, torch.dtype]:
"""Creates a dictionary with the dtypes... |
b665a6bb874d78257757d014b528f4a3ef15730384d787ea43d083596b3a31ed | Python | 736 | 23 | import pytest
import numpy as np
import os
#from ecephys_spike_sorting.modules.noise_templates.id_noise_templates import id_noise_templates_rf
#import ecephys_spike_sorting.common.utils as utils
#DATA_DIR = os.environ.get('ECEPHYS_SPIKE_SORTING_DATA', False)
def test_noise_templates():
sample_rate = 30000.0
para... |
75841e5ede73161e7b70dc2d70fbdb07b2f0330c6c897ac7147c43693aa333a2 | Python | 737 | 30 | from ._base import BaseStructureScore, get_scoring_method
from .aic import AIC
from .aic_cond_gauss import AICCondGauss
from .aic_gauss import AICGauss
from .bdeu import BDeu
from .bds import BDs
from .bic import BIC
from .bic_cond_gauss import BICCondGauss
from .bic_gauss import BICGauss
from .k2 import K2
from .log_l... |
f2245d49deee137a782a89dd3fe75f2d98285e419835e8e83ddeb70365cfe05d | Python | 737 | 20 | from typing import Any, Dict, Optional, Union
from lightning.pytorch.callbacks import Callback
from lightning.pytorch.core.module import LightningModule
from lightning.pytorch.trainer.trainer import Trainer
class LossHistoryCallback(Callback):
def __init__(self):
super().__init__()
self.losses = ... |
a98458bd2134dfaf7552a6a188afeee72eb2ffd7467e7b48593ec0410465ed8d | Python | 738 | 26 | # flake8: noqa
# There's no way to ignore "F401 '...' imported but unused" warnings in this
# module, but to preserve other warnings. So, don't check this module at all.
from .metrics import is_sklearn_available
from .processors import (
DataProcessor,
InputExample,
InputFeatures,
SingleSentenceClassif... |
01b2270bc0e6b79cd551c970e47f6c7ecdbbd135a41350f58067b9364de4a3c4 | Python | 739 | 27 | # flake8: noqa
# There's no way to ignore "F401 '...' imported but unused" warnings in this
# module, but to preserve other warnings. So, don't check this module at all.
from .metrics import is_sklearn_available
from .processors import (
DataProcessor,
InputExample,
InputFeatures,
SingleSentenceClassif... |
12239b007c5c61b4b2d8230a799ed23dc98c8edd9207bfb5e96c5b27ad3513be | Python | 739 | 24 | """
Ridge-regression baseline for fMRI ROI time-series forecasting.
The shared training utilities flatten each input window from ``(N, M, ROI)`` to
``(N, M * ROI)`` and each target from ``(N, H, ROI)`` to ``(N, H * ROI)`` before
fitting this estimator. Predictions are reshaped back to the forecasting tensor
shape by `... |
34dea623d9e7cdcfe3aeb73943d7efa9ec6c48c46be4159aeb0a55e7320f66f5 | Python | 739 | 24 | import matplotlib.pyplot as plt
import numpy as np
import loompy
import os
def mito_genes_ratio(ds: loompy.LoomConnection) -> None:
mito_genes = ds.ra.Chromosome == "MT"
if mito_genes.sum() == 0:
mito_genes = ds.ra.Chromosome == "chrM"
exp_mito = ds[mito_genes, :]
sum_mito = exp_mito.sum(axis=0... |
d3bbe6a835772475d5c2729a580b803ba70c285c732044e77886e5ae0d41e887 | Python | 740 | 17 | # Copyright 2022 InstaDeep Ltd
#
# Licensed under the Creative Commons BY-NC-SA 4.0 License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://creativecommons.org/licenses/by-nc-sa/4.0/
#
# Unless required by applicable law or a... |
d79fec74ff355ba0577dfd29eb6035f3b8e95fba3ca9869e7a036550f2956cc1 | Python | 742 | 25 | """
This module provides the `Target` base class, which defines the
interface for target feature classes. Target feature classes are classes
which define a way to access a "target feature" such as a label or
annotation on an input sequence.
"""
from abc import ABCMeta
from abc import abstractmethod
class Target(meta... |
7d063f2828931a23aac831297213d7a2994f41d444ce66f1786cecc4bb403173 | Python | 743 | 27 | import importlib.metadata
from .interpreter import forward_laplacian
from .operators import (
ForwardLaplacianOperator,
LaplacianOperator,
LoopLaplacianOperator,
ParallelLaplacianOperator,
)
from .vmap import batched_vmap
from .wrapped_functions import deregister_function, register_function
from .wrapp... |
89f674837c906e9fc9b1b1f565b063d4a564eb479f6e0d968d51a39ba9c8aa66 | Python | 743 | 27 | """Deployment-oriented knowledge distillation for nnU-Net v2."""
from __future__ import annotations
from .config import DistillationConfig, get_baseline_config, get_logits_config
def __getattr__(name: str):
if name == "DistillationTrainer":
from .distiller import DistillationTrainer
return Disti... |
bbe982d28eec0100a47313bb8c8dfb656ccd1b3bb6c2109ae98b951227dc998f | Python | 744 | 21 | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
from typing import Protocol
from mattergen.diffusion.corruption.corruption import Corruption
from mattergen.diffusion.corruption.sde_lib import ScoreFunction
from mattergen.diffusion.sampling.predictors import Predictor
from mattergen.diffusion.... |
d18dc83e6451fbb84f02a0a41df495be38aa77b443bf1ce2f17af8a0741bf45e | Python | 744 | 29 | import pandas as pd
import pytest
from pgmpy.causal_discovery import ChowLiu
@pytest.mark.parametrize(
"data",
[
pd.DataFrame(
{
"const": [1.0, 1.0, 1.0, 1.0, 1.0, 1.0],
"x": [1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
"y": [2.0, 1.0, 3.0, 2.0, 1.0, 3.0... |
6373b4c65d4f00bf1297da5cc071dacca5d7c9495a6fe7cd8082487ab005308a | Python | 745 | 22 | """Fixtures made with results from generated test data,
in ./tests/data_for_tests/generated/results"""
from collections import defaultdict
from .model import MODELS
from .test_data import GENERATED_RESULTS_DATA_ROOT
GENERATED_LEARNCURVE_RESULTS_ROOT = GENERATED_RESULTS_DATA_ROOT / 'learncurve'
SOURCE_ANNOT_PAIRS = ... |
deae2d6c5afd5abb986ab456dc57ca9144b553bf4b0391205ff7a0cc9425da5f | Python | 745 | 21 | from . import datasets # noqa: F401
from . import metrics # noqa: F401
from .tokenizers import TAPETokenizer # noqa: F401
from .models.modeling_utils import ProteinModel
from .models.modeling_utils import ProteinConfig
import sys
from pathlib import Path
import importlib
import pkgutil
__version__ = '0.5'
# Impo... |
a165d4507956dcbea4ddda49612bfedd6be949c290f94b5e5f119d5255219ea0 | Python | 747 | 28 | from mdt import CompositeModelTemplate
class SSFP_BallStick_r1_ExVivo(CompositeModelTemplate):
name = 'SSFP_BallStick_r1-ExVivo'
model_expression = '''
S0 * ( (Weight(w_ball) * SSFP_Ball) +
(Weight(w_stick0) * SSFP_Stick(SSFP_Stick0)) )
'''
fixes = {'SSFP_Ball.d': 2.0e-9,
... |
5a0919d814c24af09f17a4aa12a3bc36252a176ad2b4a50e70213fa698f549a5 | Python | 748 | 27 | import scanpy as sc, numpy as np, pandas as pd, anndata as ad
from scipy import sparse
panglao = sc.read_h5ad('./data/panglao_10000.h5ad')
data = sc.read_h5ad('./data/your_raw_data.h5ad')
counts = sparse.lil_matrix((data.X.shape[0],panglao.X.shape[1]),dtype=np.float32)
ref = panglao.var_names.tolist()
obj = data.var_n... |
3b68923f97c56819f593361eabedb02d9e151bc10d5b0147987ec7b8de7d21e4 | Python | 749 | 29 | from __future__ import annotations
from abc import ABC
from abc import abstractmethod
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from poetry.core.constraints.version import Version
from poetry.core.packages.dependency import Dependency
from poetry.core.packages.package import Package
class Abst... |
8930310841ab7285d52ef2db59ef4be955ad74b96ad9b391c8d371da789edce5 | Python | 749 | 14 | import sys
f1 = sys.argv[1]
f2 = sys.argv[2]
chromosomes = ["chr1", "chr2", "chr3", "chr4", "chr5", "chr6", "chr7", "chr8", "chr9", "chr10", "chr11", "chr12", "chr13", "chr14", "chr15", "chr16", "chr17", "chr18", "chr19", "chr20", "chr21", "chr22",]
chromosomes_xy = ["chr1", "chr2", "chr3", "chr4", "chr5", "chr6", ... |
e6090fbbb6b7807c48ef88bd0cfcd0f7f7b72f83a4f2a1a29b6fe47aac8e913b | Python | 749 | 25 | import json
import sys
def BndBoxDimensionsEdits(json_file_path):
# load the JSON file
with open(json_file_path, 'r') as file:
data = json.load(file)
# increase the dimensions
data['BrainRegion']['Dimension']['x[mm]'] = 70
data['BrainRegion']['Dimension']['y[mm]'] = 70
data['Br... |
03c2c6d6e9d2249e0c88703050d5986f2f342e54222da3f57216dfd1191420f2 | Python | 750 | 19 | """initialization"""
from voluseg._steps.step0 import define_parameters as step0_define_parameters
from voluseg._steps.step1 import process_volumes as step1_process_volumes
from voluseg._steps.step2 import align_volumes as step2_align_volumes
from voluseg._steps.step3 import mask_volumes as step3_mask_volumes
from vol... |
197d3c0388430942b09106f2b02aa0ded2a0ab995fa4ccabf1b63df351b1e62a | Python | 750 | 19 | from os.path import join
import pandas as pd
from config_path import PROSTATE_DATA_PATH
tmp_file = join(PROSTATE_DATA_PATH, 'raw_data/outputs_su2c_tcga_all_samples_n=980_rsem_results.tsv')
tpm_data = pd.read_csv(tmp_file, sep='\t', index_col=0)
mapping_ids_file = join(PROSTATE_DATA_PATH, 'raw_data/sample_mapping.ts... |
016a37719e29ea64fe3326bc2719d5d2e6a4bded3deff5c49586356a66b77ef4 | Python | 751 | 29 | import logging
from abc import ABC, abstractmethod
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)
class DatasetManager(ABC):
def __init__(self, filepath: str):
"""
Abstract base class for managing datasets.
:param filepath: Path to the dataset file.
"""
... |
89711ddef62d9e65141f8a00ae085356d39748fdd5d17f30d9dff20b7750ae1d | Python | 751 | 28 | from pgmpy.datasets._base import BaseDataset
class CollegePlans(BaseDataset):
_tags = {
"name": "college_plans",
"n_variables": 5,
"n_samples": 10318,
"has_ground_truth": False,
"has_expert_knowledge": False,
"has_missing_data": False,
"has_index_col": False... |
aae29a8f5081f12c90bff320f7c70b06554f86438801eeffa30c846b6c5936b5 | Python | 751 | 29 | from mdt import WeightCompartmentTemplate
__author__ = 'Robbert Harms'
__date__ = '2018-03-23'
__maintainer__ = 'Robbert Harms'
__email__ = 'robbert@xkls.nl'
__licence__ = 'LGPL v3'
class Weight(WeightCompartmentTemplate):
parameters = ('w',)
cl_code = 'return w;'
class ARD_Beta_Weight(Weight):
"""A w... |
5a50442466bd037a7392a35aa22bc2f0f923422a97ef014c2ef77665d9420218 | Python | 754 | 28 | from pgmpy.datasets._base import BaseDataset
class SeoulBike(BaseDataset):
_tags = {
"name": "seoul_bike",
"n_variables": 13,
"n_samples": 8760,
"has_ground_truth": False,
"has_expert_knowledge": False,
"has_missing_data": False,
"has_index_col": False,
... |
faf8774da0164caba2669eb99912ba909c60b21f20bdb471cc0a05a1f3ea34b4 | Python | 754 | 21 | from pytorch_grad_cam.base_cam import BaseCAM
from pytorch_grad_cam.utils.svd_on_activations import get_2d_projection
# Like Eigen CAM: https://arxiv.org/abs/2008.00299
# But multiply the activations x gradients
class EigenGradCAM(BaseCAM):
def __init__(self, model, target_layers,
reshape_trans... |
317c51a160c9cf174477d1b57892d4f5491dd1f50dcc83856dd566ae728efe5e | Python | 755 | 24 | # 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.data.encoders import register_tokenizer
from fairseq.dataclass import FairseqDataclass
@register_tokenizer("nltk", dataclass=Fa... |
43f2b83166cafc28fe12d3dc20abca691a417b3d1b20f79da9801f9ff6ac7483 | Python | 755 | 25 | #! /usr/bin/env python
# System imports
from distutils.core import *
from distutils import sysconfig
# Third-party modules - we depend on numpy for everything
import numpy
# _Series extension module
_peer = Extension("_peer",
["peerPYTHON_wrap.cxx"],
include_dirs = [numpy... |
aa7d8a50638e49e1b84f688ed32de78aa70bf28488052b4e6ae1b801dfb643d1 | Python | 755 | 31 | # -*- coding: utf-8 -*-
# Copyright (C) 2018 Phillip Alday <me@phillipalday.com>
# License: BSD (3-clause)
"""Utility functions not further classified."""
from __future__ import division, print_function
def invert_dict(d):
"""Return an 'inverted' dictionary, swapping keys against values.
Parameters
----... |
54af0ae9ae50d5652e3f6d1efeeee91a7d025085b11b1884ce00092233cac696 | Python | 756 | 22 | def load_mnist(path, kind='train'):
import os
import gzip
import numpy as np
"""Load MNIST data from `path`"""
labels_path = os.path.join(path,
'%s-labels-idx1-ubyte.gz'
% kind)
images_path = os.path.join(path,
... |
d772e7f0b3ced204f318b5628327613c8db09ae5365f5192022463048c66d461 | Python | 756 | 30 | import numpy
import os
import pandas
import numpy.testing
import unittest
from metax.misc import DataFrameStreamer
class TestDataframeStreamer(unittest.TestCase):
def test_dataframe_streamer(self):
root = "tests/_td/gtex_like_eqtl"
kk = os.path.join(root, "data.txt")
kkk = pandas.DataF... |
f4e542e3e2ee53a0881946265b2d3dd00da10533a14443a91af55cc2fd14b475 | Python | 756 | 24 | """tests for vak.config.load module"""
import tomlkit
import vak.config.load
def test__tomlkit_to_pop(a_generated_config_path):
with a_generated_config_path.open('r') as fp:
tomldoc = tomlkit.load(fp)
out = vak.config.load._tomlkit_to_popo(tomldoc)
assert isinstance(out, dict)
assert list(out... |
5ddc29758a4d64aa186d89aa48204ebb57bfaeda2e85307c473a897996c1d95c | Python | 757 | 31 | """
RAG-GNN: Retrieval-Augmented Graph Neural Networks for Biological Network Analysis
A framework for integrating graph neural network representations with
retrieval-augmented generation for biological network modeling.
"""
from .model import RAGGNN
from .gnn import GNNEncoder
from .retrieval import KnowledgeRetriev... |
5f6676e5df82df83f9f6f8a9219648092d00e3109dc07057421231593d27c06f | Python | 758 | 26 | from typing import NamedTuple
class _SCVI_HUB_NT(NamedTuple):
HF_LIBRARY_NAME: str = "scvi-tools"
MAX_HF_UPLOAD_SIZE: int = 5e9 # 5GB
# file names
METADATA_FILE_NAME: str = "_scvi_required_metadata.json"
MODEL_CARD_FILE_NAME: str = "README.md"
# model card defaults
DEFAULT_MISSING_FIELD... |
7e17b15d6803d084f2023d640b2381a04e6f958e5c74717f83560d8889693cbd | Python | 758 | 28 | """
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
# Define the data to extract
rois = 'exampleData/20150429.zip'
images... |
662089c709358acbf8ddfaf448e071c8cdf7cd8401d9a9082c7508d6ca9cd2ae | Python | 760 | 27 | from pgmpy.datasets._base import BaseDataset
class CoverType(BaseDataset):
_tags = {
"name": "cover_type",
"n_variables": 11,
"n_samples": 581012,
"has_ground_truth": False,
"has_expert_knowledge": True,
"has_missing_data": False,
"has_index_col": False,
... |
c044da22a17464fd3496da61622e1ceb02a69389a9a97b9066781a385ced0bb2 | Python | 760 | 21 | # @license
# Copyright 2016 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... |
cf44be02876db16c645ddd1a2e5e36293d09c4ff572fbb5aeb26eecadb52672d | Python | 761 | 29 | # 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
from fairseq import registry
build_tokenizer, register_tokenizer, TOKENIZER_REGISTRY, _ = registry.setup_regist... |
869461b4a616493a27c8aa64d61012762f98cd155146de1393f549b335a60212 | Python | 762 | 23 | from datetime import datetime
from importlib.metadata import version, PackageNotFoundError
__author__ = ("Haibao Tang", "DV Klopfenstein")
__copyright__ = (
f"Copyright (C) 2009-{datetime.now().year}, Haibao Tang, DV Klopfenstein"
)
__email__ = "tanghaibao@gmail.com"
__license__ = "BSD"
__status__ = "Development"
... |
09515fae909cfa16fecaf62bb77df1164ace938b3dd48ec1cf9f3c5cb9af2aed | Python | 763 | 32 | """Generate JSON schemas from Pydantic models in the d3types package.
This module provides functionality to automatically generate JSON schemas for all
Pydantic BaseModel subclasses defined in the d3types module.
Example:
$ python generate_json_schemas.py > d3types.schema.json
The script will print the JSON sche... |
9f9fb12436cb9b5707efe6e3e0d513a5c88f6beb78071a3dce0c66b808a92bc3 | Python | 763 | 33 | import fm
import torch
if __name__=="__main__":
#path= "/path/to/pretrained/model"
model, alphabet = fm.downstream.build_rnafm_resnet(type="ss") #, model_location=path)
batch_converter = alphabet.get_batch_converter()
model.eval() # disables dropout for deterministic results
# Prepare data
... |
e7c1aa00725e21169273d332782f0ae09d3c91e504325206e062343656882ec4 | Python | 763 | 23 | import random
import unittest
from unittest.mock import patch
from pyecharts import options as opts
from pyecharts.charts import HeatMap
from pyecharts.faker import Faker
class TestHeatmapChart(unittest.TestCase):
@patch("pyecharts.render.engine.write_utf8_html_file")
def test_heatmap_base(self, fake_writer)... |
4d7ae7ac963b4ef456b1fe6ff67d5023e2beab9b56885a46bc86e5662059d55a | Python | 764 | 28 | from pgmpy.datasets._base import BaseDataset
class Airfoil(BaseDataset):
_tags = {
"name": "airfoil",
"n_variables": 6,
"n_samples": 1503,
"has_ground_truth": False,
"has_expert_knowledge": True,
"has_missing_data": False,
"has_index_col": False,
"is... |
ed8efb8ef6c7a1553350ae2f311cec7cf393d5ea22f23dc2af2d058dcf649d8e | Python | 764 | 26 | from typing import List
import numpy as np
def div0(a: np.ndarray, b: np.ndarray) -> np.ndarray:
""" ignore / 0, div0( [-1, 0, 1], 0 ) -> [0, 0, 0] """
with np.errstate(divide='ignore', invalid='ignore'):
c = np.true_divide(a, b)
c[~np.isfinite(c)] = 0 # -inf inf NaN
return c
def cap_select(labels: np.ndar... |
ee1290b26f4a9540403eade3a613f80b6fb77dc28f7eaabb36021ed04262392d | Python | 764 | 31 | import numpy as np
import pylab as plt
from skfmm import extension_velocities
N = 150
X, Y = np.meshgrid(np.linspace(-1, 1, N), np.linspace(-1, 1, N))
r = 1.75
dx = 2.0 / (N - 1)
phi = (X) ** 2 + (Y+1.85) ** 2 - r ** 2
speed = X+1.25
d, f_ext = extension_velocities(phi, speed, dx)
plt.subplot(131)
plt.... |
14e28171f0d85e7dc1bd9778188fbd5621deeb381ee47ef1c7e314d4962138e5 | Python | 766 | 22 | import jax.numpy as jnp
from ..geom import distance
from .operators import NuclearForceOperator, one_electron_integral_on_grid
def coulomb_force_nuclei(mol):
diffs = mol.coords - mol.coords[:, None]
dists = distance(mol.coords, mol.coords[:, None], axis=-1, keepdims=False)
charges = mol.charges * mol.cha... |
800e4964a6a1aa6139fadbb76f65727a417e2d2e958024b8adda2f52d10e2cfc | Python | 767 | 22 | """
Open The QCR dashboard in a jupyter notebook.
=============================================
This notebook demonstrate how the PyLossless Quality Control interface can be
integrated in a Jupyter Notebook. This can even be done on a virtualized
platform, like Google Colab! To try it, you can run this notebook from
... |
0b2a042ed2040254b93e06ac6cccfe08ecdee76c94a55fd31d2ddf66080b1fdc | Python | 768 | 21 | import numpy as np
import sklearn.cluster
from scipy.cluster.hierarchy import fcluster, linkage
from scipy.spatial.distance import squareform
def cluster_correlation(corr: np.ndarray, method: str = 'AffinityPropagation', **kwargs) -> np.ndarray:
match method.lower():
case 'affinitypropagation':
clusterer = skle... |
58a0be8c2865fdf1b67399bb0a62baa12a87ec26a984d9f790af683ce7a4fc5f | Python | 768 | 29 | from pgmpy.datasets._base import BaseDataset
class DepressionCoping(BaseDataset):
_tags = {
"name": "depression_coping",
"n_variables": 78,
"n_samples": 127,
"has_ground_truth": False,
"has_expert_knowledge": False,
"has_missing_data": True,
"has_index_col":... |
b895e38882a158e82b5f648486d2eda96cb7a245f8e4629da656fe1c36442a37 | Python | 768 | 26 | """
Fusion module for combining ViT and MaxViT features.
"""
import torch
import torch.nn as nn
class GatedFusion(nn.Module):
"""Adaptive gated fusion for combining two feature vectors."""
def __init__(self, input_dim: int = 1024, dropout: float = 0.3):
super().__init__()
self.gate = nn.Sequ... |
fc4ca5d4e5ce1c263caddccf385032493e4fcb5ffacceaaed376662f3e27f8fd | Python | 769 | 22 | """Bounded preflight: don't start a release build with blocked VTK binaries."""
import subprocess
import sys
def main():
try:
result = subprocess.run(
[sys.executable, "-u", "-c",
"from vtkmodules.qt.QVTKRenderWindowInteractor import QVTKRenderWindowInteractor; "
"fro... |
fd129f5b978a25e74028056a605a5220549e949f8d843f11f09c76188ca61611 | Python | 769 | 24 | """Annotation Extension for relational expressions.
https://link.springer.com/protocol/10.1007/978-1-4939-3743-1_17
"""
__copyright__ = "Copyright (C) 2016-2019, DV Klopfenstein, H Tang. All rights reserved."
__author__ = "DV Klopfenstein"
# pylint: disable=too-few-public-methods
class AnnotationExtension(object... |
d63e0cf7614e21753a586732668e8df8df1c65b8e12ad4876fc980dc335ffabd | Python | 770 | 20 | """Parses config.toml and makes the settings available to the package"""
import tomllib
from importlib import resources
PKGROOT = resources.files("brenda_references")
CONFIG = PKGROOT / "config.toml"
with CONFIG.open(mode="rb") as cf:
config = tomllib.load(cf)
# `config["documents"]` and `config["datasets"]` ar... |
27332624fa2946b88abadd72cb61ee10a2d35ae18dadc432cf8989fe63a60515 | Python | 771 | 29 | import main
def test_main_prefers_qt_dashboard_when_available(monkeypatch):
dashboard_calls = []
monkeypatch.setattr(main, "_is_pyside6_available", lambda: True)
monkeypatch.setattr(
main,
"run_dashboard",
lambda: dashboard_calls.append("qt") or 0,
)
assert main.main([]) ... |
8e0446353ca32e9a45bc5ea493f45a539e92ea69416d0096b167701647b31563 | Python | 772 | 26 | from __future__ import annotations
from typing import TYPE_CHECKING
from typing import ClassVar
from poetry.console.commands.remove import RemoveCommand
from poetry.console.commands.self.self_command import SelfCommand
if TYPE_CHECKING:
from cleo.io.inputs.option import Option
class SelfRemoveCommand(SelfComm... |
ec438ca1e31f1c5fb4f779b96203e11e04a166983d9e95ce6693e3d2408c0465 | Python | 772 | 27 | import os
import time
import torch
import sys
import subprocess
argslist = list(sys.argv)[1:]
log_dir = argslist[-1]
num_gpus = torch.cuda.device_count()
argslist.append('--n_gpus={}'.format(num_gpus))
workers = []
job_id = time.strftime("%Y_%m_%d-%H%M%S")
argslist.append("--group_name=group_{}".format(job_id))
print... |
27b2f870f0fb33a6266fcda52bcf6944d6d7c5bb5995a19f1cab85a407019db2 | Python | 773 | 27 | """
Extract features from simulated tree sequences
"""
import os
import numpy as np
import zarr
import yaml
import tskit
import ts_processors
indices = yaml.safe_load(open(snakemake.input.yaml))["indices"]
input_dir = os.path.dirname(snakemake.input.yaml)
config = snakemake.params.processor_config
class_name = confi... |
36de0a4956d914a62309416822d262788627790782c05471123fd4cfd1277bc2 | Python | 775 | 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.
from .distributed_timeout_wrapper import DistributedTimeoutWrapper
from .fully_sharded_data_parallel import (
fsdp_enable_wrap,
fsdp_w... |
561e6937987c7de75c90a4de3d5104403b72da0a0bbcff14e34d0d5a047382ff | Python | 775 | 22 | from pytorch_grad_cam.base_cam import BaseCAM
from pytorch_grad_cam.utils.svd_on_activations import get_2d_projection
# https://arxiv.org/abs/2008.00299
class EigenCAM(BaseCAM):
def __init__(self, model, target_layers,
reshape_transform=None):
super(EigenCAM, self).__init__(model,
... |
6ccd430105b2da3fec668d501d6af9878a120461336293de9f2aef7fc67b63a1 | Python | 776 | 24 | # Authors: Christian O'Reilly <christian.oreilly@sc.edu>
# License: MIT
#import json
import plotly.graph_objects as go
from dash import dcc
from ..qcannotations import EEGAnnotationList, EEGAnnotation
def test_EEGAnnotationList_serialization():
"""JSON serialization for EEGAnnotationList fails. Test adding to d... |
12d7c1e5a422256d91a1d66e02241fab13f830dcfd8cbc628138c054737504f3 | Python | 777 | 18 | """Shared analysis code for the cichlid vs zebrafish optomotor response (OMR) study.
Modules:
- `cichlid_omr.io`: file discovery, filename parsing, CSV loading
- `cichlid_omr.signal`: interpolation, peak detection, smoothing, timeline merging
- `cichlid_omr.plotting`: shared matplotlib figure style
- `cichlid_omr.fig... |
e888e9ff58bfe661ba3cc6c2765c7f5d7b98c598de8f12731c58df6c951d10a5 | Python | 777 | 18 | import unittest
from mask_sequence import canonical_mask_records, export_mapping_preview
class MaskSequenceContractTests(unittest.TestCase):
def test_512_slice_display_numbers_map_directly_to_png_numbers(self):
records = canonical_mask_records(f"{index + 1:04d}" for index in range(512))
self.asse... |
8b0db9500298839f4abffc5d8c7914d0f5ee6bcf5c99802dad5dd10faf534239 | Python | 778 | 19 | # python3 setup_cmmcost_omp_abel.py build_ext --inplace
# export OMP_NUM_THREADS=16
from distutils.core import setup
from Cython.Build import cythonize
from distutils.extension import Extension
import numpy
srcfiles = ["cmmcost_omp.pyx", "_cmmcost_omp.c"]
includedirs = ["/cluster/software/VERSIONS/gsl-2.2/include", nu... |
7c0ce484e1babee053d9a102c1d4bd8b4b69dae6e52242b284a6c49b1e4be77a | Python | 779 | 22 | import dadi
import numpy as np
from dadi_simulators import *
import os
import torch
datadir = snakemake.params.datadir
posteriordir = snakemake.params.posteriordir
n_train = snakemake.params.n_train
sample_idx = snakemake.params.sample_idx
simulator = MODEL_LIST[snakemake.params.demog_model](snakemake)
samples = np.... |
b20470209d6869570a473fc29e63e05a9f95c98b9dec5f505675256cfb0167d9 | Python | 780 | 25 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from tractseg.data import dataset_specific_utils
from tractseg.experiments.tract_seg import Config as TractSegConfig
class Config(TractSegConfig):
EXP_NAME = os.path.basename(__file__).split(".")[0]
DATASET = "HCP_all"
DATASET_FOLDER = "HCP_preproc_... |
33700fb27819a946b61ca2bf02465ce162a8e68620d7b24758ca19abd98ed405 | Python | 781 | 26 | import torch
import torch.nn as nn
import random
import warnings
random.seed(1234)
warnings.filterwarnings("ignore")
class PoswiseFeedForwardNet(nn.Module):
def __init__(self, device, d_model, d_ff):
super(PoswiseFeedForwardNet, self).__init__()
self.d_model = d_model
self.d_ff = d_ff
... |
5de63da0abc439b3a8bb92ed4de4f797fd8c9c3f6d89dd38061addaae6987509 | Python | 786 | 31 | # 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 numpy as np
import torch
from . import BaseWrapperDataset
class NumelDataset(BaseWrapperDataset):
def __init__(self, dataset, re... |
391939efa9550c8bb6dc7fca6568fe9b4fa731c7cfbfd0e3e21f6b814af03a21 | Python | 787 | 25 | import numpy as np
from paper2.figures2 import plot_mean_spectra2, plot_cv_box2, plot_parity
from paper2.loaders import load_oil
def test_mean_spectra_writes_png(tmp_path):
ds = load_oil()
out = tmp_path / "spec.png"
plot_mean_spectra2(ds, out)
assert out.exists() and out.stat().st_size > 0
def test... |
a90e3a1b611cb96211b7aecf8686b9f25cd3382d0f98cbef82f25184e81c8c42 | Python | 787 | 25 | import dadi
import numpy as np
import os
from dadi_simulators import *
datadir = snakemake.params.datadir
posteriordir = snakemake.params.posteriordir
n_train = snakemake.params.n_train
# compare observed sfs (data) against sfs simulated with MAP parameters
# load data
data = np.load(os.path.join(datadir, "fs_star.n... |
2303624d03735e3f19a38e704be227636282a95c29939e0ea1b117454b15e856 | Python | 788 | 23 | from __future__ import annotations
import re
from poetry.console.logging.formatters.formatter import Formatter
class BuilderLogFormatter(Formatter):
def format(self, msg: str) -> str:
if msg.startswith("Building "):
msg = re.sub("Building (.+)", " - Building <info>\\1</info>", msg)
... |
e6f18af3387b1d721744a59a35bb0b7fd97fdfe9e28c17dddeac1563811dd4ac | Python | 788 | 33 | import torch
class CrossEntropyLoss(torch.nn.CrossEntropyLoss):
"""Wrapper around :class:`torch.nn.CrossEntropyLoss`
Converts the argument ``weight`` to a :class:`torch.Tensor`
if it is a :class:`list`.
"""
def __init__(
self,
weight=None,
size_average=None,
ignor... |
f5404e4cf9f13b2b07c21a459a846ae755507377d6c6ae9793b71a9a28af79bc | Python | 788 | 30 | from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from poetry.core.packages.dependency import Dependency
from poetry.core.packages.package import Package
from poetry.mixology.failure import SolveFailureError
class SolverProblemError(Exception):
def __init__(self... |
9a123f8e9f3d96c348070998e3da171019edf6031c9b3eb6e86ce1c52072d866 | Python | 790 | 22 | import pytest
import vak.config.validators
def test_are_tables_valid(invalid_table_config_path):
"""test that invalid table name raises a ValueError"""
config_dict = vak.config.load._load_toml_from_path(invalid_table_config_path)
with pytest.raises(ValueError):
vak.config.validators.are_tables_va... |
6eb390711a2dfc1849571f66b4a446dda97a19c07390fffa10d32b041fbc52d1 | Python | 791 | 20 | """Bayesian Optimization module for D-peptide sequence optimization (Tier 2).
Provides Evolutionary BO and MCMC explorers with GP surrogate models,
supporting one-hot, physicochemical, and Boltz2 sequence embeddings.
"""
from .encoders import OneHotEncoder, PhysicochemicalEncoder, Boltz2Encoder, AAS
from .models impor... |
d64a3040741793b460cfbb709b76e60bbffce00c96406e7e4150c9a553f01c72 | Python | 791 | 29 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from tractseg.data import dataset_specific_utils
from tractseg.experiments.base_legacy.dm_reg_legacy import Config as DmRegConfig
class Config(DmRegConfig):
EXP_NAME = os.path.basename(__file__).split(".")[0]
DATASET_FOLDER = "HCP_preproc_all"
NR_O... |
6e948b239b5948c70cb44d1887597db67fbdf8185675fafa902f2f8a71acece5 | Python | 792 | 27 | # -*- coding: utf-8 -*-
"""
@Time:Created on 2019/9/23 15:24
@author: LiFan Chen
@Filename: analysis.py
@Software: PyCharm
"""
file_path = "dataset_kiba/kiba_train.txt"
with open(file_path,"r") as f:
data_list = f.read().strip().split('\n')
P = 0
N = 0
with open("dataset_kiba/train_c.txt","w") as f:
for element... |
9aac387db59f21895c9cbfa8ad69ddb31ce8e4dc898b6964f8e3c520cff9f605 | Python | 792 | 24 | from mdt import CompartmentTemplate
from mdt.lib.post_processing import DTIMeasures
__author__ = 'Robbert Harms'
__date__ = "2015-06-21"
__maintainer__ = "Robbert Harms"
__email__ = "robbert@xkls.nl"
class Tensor(CompartmentTemplate):
parameters = ('g', 'b', 'd', 'dperp0', 'dperp1', 'theta', 'phi', 'psi')
d... |
ce33be65c79535ff20cc795cdf4a2eb1a158c4cd616f46ff80e1f7f66a71cd26 | Python | 792 | 23 | from .base import (load_conte69, load_sc, load_fc, load_fsa,
load_fsa5, load_fsa6, load_subcortical, structural_covariance,
fetch_ahba, risk_genes, load_example_data,
load_summary_stats, load_fc_as_one, load_sc_as_one,
nfaces, getaffine, load_m... |
daa6cbf556f05c4e2c9ca2ddff57512d70c15e2293219fa1ef6dcc744a222d40 | Python | 792 | 29 | __version__ = "0.2.5"
import logging
import sys
logger = logging.getLogger("scGPT")
# check if logger has been initialized
if not logger.hasHandlers() or len(logger.handlers) == 0:
logger.propagate = False
logger.setLevel(logging.INFO)
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(loggin... |
691b0dada76adb4590e0affd9b71e6818fdac7fd3b2a853e0ac86d1e56cfe16c | Python | 793 | 23 | #!/usr/bin/env python3
# merge 5utr info into the main protein classification table
#%%
import pandas as pd
import argparse
import os
parser = argparse.ArgumentParser()
parser.add_argument('--utr_info',action='store',dest='utr_info')
parser.add_argument('--sqanti_protein_classification',action='store',dest='sqanti_p... |
6ca01446864824920170bfea3149940ab3ab5414894ab40b7a5809de71c3b2da | Python | 793 | 33 | from pgmpy.datasets._base import BaseDataset
class BlueDriver(BaseDataset):
"""
References
----------
- :footcite:t:`uci_adult`
"""
_tags = {
"name": "blue_driver",
"n_variables": 10,
"n_samples": 1381,
"has_ground_truth": False,
"has_expert_knowledge":... |
b6b11a64b672f27f0c19dbc69bc83fd073c5269a5bd8949b06b2f40fac301a89 | Python | 793 | 16 | from typing import List, Tuple
import numpy as np
from sklearn.model_selection import GroupShuffleSplit, StratifiedGroupKFold
def group_holdout_split(groups, test_size=0.30, seed=42) -> Tuple[np.ndarray, np.ndarray]:
"""Train/test indices with NO shared group (isim) between sets."""
gss = GroupShuffleSplit(n_... |
d19d6e16a540cff82c345318d9e2a4be33ec99c303d8e25933f7172d2640245d | Python | 793 | 28 | from PIL import Image
import phate
import cv2
import numpy as np
import joblib
from msi_visual.utils import normalize
class PHATE3D:
def __init__(self, start_bin=0, end_bin=None):
self._trained = False
self.start_bin = start_bin
self.end_bin = end_bin
def __repr__(self):... |
fec672ef6956967423c665480bf53954f569ba5e7db9683e0b87a7f899cddb02 | Python | 793 | 27 | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
NUM_ATOMS_DISTRIBUTIONS = {
"ALEX_MP_20": {
1: 0.0002303828963737732,
2: 0.002804088967292211,
3: 0.019342289742695216,
4: 0.1636343889258233,
5: 0.04668051158167732,
6: 0.07808005476530565,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.