sha256 stringlengths 64 64 | language stringclasses 27
values | size int32 1 491k | lines int32 1 21.8k | content stringlengths 1 200k |
|---|---|---|---|---|
a6b030c0e8883243b9d75b90eef725b7cc282efd263ed7583183667329ff23a9 | Python | 2,049 | 72 | import os
import json
from copy import deepcopy
from dataclasses import dataclass
@dataclass
class BaseConfig:
def clone(self):
return deepcopy(self)
def inherit(self, another):
"""inherit common keys from a given config"""
common_keys = set(self.__dict__.keys()) & set(another.__dict_... |
b656a6372521a5ad1feaefc893d26a79d9c168216481ebc3d9f676a5d6a25863 | Python | 2,049 | 63 | import unittest
import numpy as np
import numpy.testing as npt
from skbase.utils.dependencies import _safe_import
from pgmpy import config
from pgmpy.utils import optimize, pinverse
torch = _safe_import("torch")
class TestOptimize(unittest.TestCase):
"""
self = TestOptimize()
self.setUp()
"""
... |
da0684f219f9c610a5840532f54bf91762c4c272dcc69903de51aceb3c399132 | Python | 2,049 | 49 | #!/usr/bin/env python
import polars as pl
import argparse
def get_expression(read_stat_path, id_to_sample_path):
print("Getting mapping from PB IDs to sample names...")
id_to_sample = pl.read_csv(id_to_sample_path, separator = "\t", has_header = False, new_columns = ["id", "sample"])\
.with_colum... |
b4a564f08cfbe6650568ba3a4490aab8706ec01c1c4ea7c98db407a084a552c8 | Python | 2,050 | 53 | from dipy.io.streamline import load_trk
import os
import sys
import numpy as np
import nibabel as nib
import scipy.ndimage.morphology
from dipy.tracking import utils
from dipy.tracking.streamlinespeed import length
###################################################################################################... |
75f383c8f7d9cb6bc1ac391602ee2cc1093300be3e188480033309b5e5bc43d9 | Python | 2,054 | 49 | #!/usr/bin/env python
import polars as pl
import argparse
def get_expression(read_stat_path, id_to_sample_path):
print("Getting mapping from PB IDs to sample names...")
id_to_sample = pl.read_csv(id_to_sample_path, separator = "\t", has_header = False, new_columns = ["id", "sample"])\
.with_colum... |
91174fc9cd86c733cc7be26d499e90d179db3fe6024705d3a6c2ee44cecf6997 | Python | 2,054 | 54 | #
# Copyright 2017-2023 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with
# Sandia Corporation, the U.S. Government retains certain rights in this software.
#
# See LICENSE for full license details
#
from ..idevice import EmptyDevice
from ..generic_device import NormalError
from simulat... |
f2fb4ae682029f95feab85625026fef43628143a700b02ddf20cb733b7876394 | Python | 2,054 | 64 | import os
import numpy as np
import pytest
from pgmpy.ci_tests import PearsonrEquivalence
from pgmpy.factors.continuous import LinearGaussianCPD
from pgmpy.models import LinearGaussianBayesianNetwork
@pytest.fixture
def pearson_equivalence_data():
np.random.seed(42)
model_dep = LinearGaussianBayesianNetwor... |
5176591eb3f7c2603d2f14e718054dac2a121e76cd91e98817aaf3a73ecb7079 | Python | 2,055 | 56 | import os
import yaml
import traceback
from pydantic import BaseModel, ValidationError
from simulation_encoder.dataclass.param_sets import DatasetParams
from simulation_encoder.dataclass.config_schemas import (
StudyConfig,
HyperparameterConfig,
ModelArchitectureConfig,
)
def load_yaml(yaml_file: str, co... |
bb1ae6a12b0f7ac642dbf90558a7dec89f90bbfb27e011c34f95ef8d423e7294 | Python | 2,055 | 55 | from transformers import AutoTokenizer, AutoModelForCausalLM
from peft import PeftModel
from tqdm import tqdm
import argparse
import os
import torch
parser = argparse.ArgumentParser()
parser.add_argument("--txt", type=str)
parser.add_argument("--dst", type=str)
parser.add_argument("--gpu", type=int, default=1)
args = ... |
9a60f22f09ae5523d1efa1b09267a6338abf51f0652052154b19fb2f6293b41c | Python | 2,056 | 66 | import pytest
import vak.models
from .conftest import MockModel, MockModelFamily, MockEncoderDecoderModel
from .test_definition import TweetyNetDefinition as TweetyNet
from .test_definition import (
MissingClassVarModelDefinition,
ExtraClassVarModelDefinition,
InvalidNetworkTypeModelDefinition,
Inval... |
35bb8e50614902ad385e467fba4e251c7c5203fbd34398c1974a416c4ddc72d8 | Python | 2,057 | 61 | # 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"""
import logging
from hydra.core.config_store import ConfigStore
from fairseq.dataclass.configs import FairseqConfig
from ... |
99dc2ea86fc755548bb8d8a175052dbe2b1682e1d82827f3e9dacacc6fac5769 | Python | 2,058 | 104 | import os
import re
import subprocess
def available_cpu_count():
""" Number of available virtual or physical CPUs on this system, i.e.
user/real as output by time(1) when called with an optimally scaling
userspace-only program"""
# cpuset
# cpuset may restrict the number of *available* processors
try:
m = re... |
db4db56097e2182efd4a7d7bcc267956b213ce508189dff549042d6ab544788d | Python | 2,058 | 62 | #!/usr/bin/env python
# @license
# Copyright 2017 Google Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... |
092bc8c7a69fd4b9785d8d8b0727cc793948b37afd5292fa4823fcad9cd7ef3f | Python | 2,059 | 53 | import pandas as pd
import matplotlib.pyplot as plt
def plot_logs(train_log_path, val_log_path, log_interval, out_dir):
# Load training and validation logs
train_df = pd.read_csv(train_log_path)
val_df = pd.read_csv(val_log_path)
y_min = min(train_df['loss'].min(), val_df['loss'].min())
y_max = ma... |
9819f9fbe1a2a3956af9d2c4f7c52337f4d084267ea9ca2664253433e094db6e | Python | 2,059 | 61 |
from msi_visual import nmf_segmentation
import glob
import argparse
import numpy as np
from argparse import Namespace
from pathlib import Path
import joblib
import tqdm
import os
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument('--Percentile Ratioefix', type=str, default='',... |
9f67426e74e885b09c83649f71b8271819b7111d8581e72aad152483c8d64bb0 | Python | 2,059 | 69 | import os
from os.path import join, exists
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from config_path import PROSTATE_DATA_PATH, PLOTS_PATH
# base_dir = '../../data/prostate/input'
base_dir = join(PROSTATE_DATA_PATH, 'raw_data')
# filename = 'final/P1013_Clinical_Annotations_MAF.tx... |
5b53158a30d2e391f4b21d8ff3ab7612eca43657a8f6b925a742191e30f48ab8 | Python | 2,063 | 68 | """
Novae model training with Weight & Biases monitoring
This is **not** the actual Novae source code. Instead, see the `novae` directory
"""
# isort: skip_file
# else segmentation fault on our-HPC-specific env
import pyarrow # noqa: F401
import argparse
import novae
from novae._constants import Nums
from novae.dat... |
b951a18ed2db33434af967ee651a207e40680f1a7abad046257e4a1fc3bafa90 | Python | 2,064 | 61 | #!/usr/bin/env python
# PYTHON_ARGCOMPLETE_OK
"""Generate the bval and bvec file from a protocol file."""
import argparse
import os
import mdt
from argcomplete.completers import FilesCompleter
import textwrap
import mdt.protocols
from mdt.lib.shell_utils import BasicShellApplication
from mdt.protocols import write_bvec... |
da286ad0dfe99119df7182ccb418af0c4f681d9a11bc118e65844346b04cb391 | Python | 2,065 | 40 | import matplotlib.pyplot as plt
import numpy as np
plt.style.use(['science','nature'])
x_ax = np.load('new_inf_comp_x.npy')
y_base = np.load('new_inf_baseline_y.npy').reshape(-1,1)
y_sot = np.load('new_inf_sotmram_y.npy')
y_sotnorm = y_sot/y_base
y_rram = np.load('new_inf_rram_y.npy')
y_rramnorm = y_rram/y_base
y_ecr... |
82adae4519bf5d49078539a4c03b9b3b2f8f9af6930287a3cbe3af07aed73e8e | Python | 2,066 | 40 | #!/usr/bin/env python3
"""Merge the two harmonization tracks (RNA-seq v3 + microarray v2) into one symbol x sample
matrix on gene symbols, ready for per-dataset normalisation + ComBat (downstream)."""
import os, glob
import pandas as pd, numpy as np
ED="__MS_GEO_ROOT__/Expression_Data"; H=f"{ED}/harmonized_v2"
mats=so... |
14735b38494d32f23f5e6fc3157353046c1a74a16a707875a1cd0f027273542e | Python | 2,067 | 66 | import pandas as pd
from .power_divergence import PowerDivergence
class ChiSquare(PowerDivergence):
"""
Pearson chi-square test for conditional independence on discrete data.
This class is a thin specialization of :class:`PowerDivergence` with ``lambda_="pearson"``.
For the contingency-table constru... |
7cb3d97476ca0d470a011117400c877091ae5d08ddea93bbe2fe10110c48e120 | Python | 2,067 | 57 | import sys
import torch.nn as nn
from collections import OrderedDict
_internal_attrs = {'_backend', '_parameters', '_buffers', '_backward_hooks', '_forward_hooks', '_forward_pre_hooks', '_modules'}
class Scope(object):
def __init__(self):
self._modules = OrderedDict()
def _make_functional(m... |
c95f19792b97e23629806229dc41c99d817dea6b48f8b27ce8daf875964d4c19 | Python | 2,067 | 61 |
from msi_visual import kmeans_segmentation
import glob
import argparse
import numpy as np
from argparse import Namespace
from pathlib import Path
import joblib
import tqdm
import os
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument('--Percentile Ratioefix', type=str, default=... |
d9ba3683ce76efc2b667a1f20197870f5f27a0c64e91e29cde8281a443c6e149 | Python | 2,068 | 78 | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
from typing import List
logger = logging.getLogger(__name__)
def uniform(dataset_sizes: List[int]):
return [1.0] * len(... |
0623976295584e0d1a6ae1257956da4bfcf00cc720fd13b3c156b84ef17a2a8f | Python | 2,070 | 80 | from typing import Any, Dict, Generic, NamedTuple, Protocol, Tuple, TypeVar
import jax
from ..types import MolecularConfiguration, RandomKey, Stats, WavefunctionParams
B = TypeVar("B", covariant=True)
_B = TypeVar("_B", contravariant=True)
O = TypeVar("O")
P = TypeVar("P")
class DensityModel(Generic[P], Protocol):... |
74b2a9957667d60699af9b29184584e21beaa29ce5d4e23f2a3e069d08a0344b | Python | 2,071 | 63 | # @license
# Copyright 2017 Google Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... |
a7e10b6f7ae31ade0d4aadcf8663c86b11228f17f6b1c33a423c3afeed2ebb4b | Python | 2,071 | 57 | # Copyright Howto100m authors.
# Copyright (c) Facebook, Inc. All Rights Reserved
import torch as th
class Normalize(object):
def __init__(self, mean, std):
self.mean = th.FloatTensor(mean).view(1, 3, 1, 1)
self.std = th.FloatTensor(std).view(1, 3, 1, 1)
def __call__(self, tensor):
t... |
a7ecfac1c850291a444bab49bb3e391ecc3915225c41f95ac4cadfbb78088afa | Python | 2,072 | 65 | #!/usr/bin/env python3
# -*- encoding: utf8 -*-
import argparse
import itertools
import os
import re
import sys
from pathlib import Path
import math
import whisper
from tqdm import tqdm
parser = argparse.ArgumentParser()
parser.add_argument("--wavs", type=str)
parser.add_argument("--dst", type=str)
parser.add_argum... |
963c06ca333f7630823220086d20aed2a3fe32bc7734ed439a8ff37b0d502e96 | Python | 2,073 | 63 | import pandas as pd
from .power_divergence import PowerDivergence
class ModifiedLogLikelihood(PowerDivergence):
"""
Modified log-likelihood ratio test for conditional independence on discrete data.
This class is a thin specialization of :class:`PowerDivergence` with
``lambda_="mod-log-likelihood"``.... |
8b773d574e7cb751979d2443059d43a8ea22b6765c01fbba6633d9c212e919fe | Python | 2,075 | 66 | """Parametric UMAP model, as described in [1]_, with a convolutional network as the encoder.
Code adapted from implementation by @elyxlz
https://github.com/elyxlz/umap_pytorch
with changes made by Tim Sainburg:
https://github.com/lmcinnes/umap/issues/580#issuecomment-1368649550.
"""
from __future__ import annotations... |
f963c2ad8571698d72d01619d0c64d2d588cc917c0615f815d3222b46b0b93bf | Python | 2,075 | 54 | """Value-constrained aliases for the ranges a bare `int` or `float` hides.
Each alias is an `Annotated` type whose metadata beartype checks at call
time and every other reader ignores, so a signature states its range where
the parameter is declared. beartype is optional at runtime, so an alias is a
contract the claw e... |
6035cb9f45b502d96f1ab6b13a260c1254ebbe59b9b209b397eaca20002bde2c | Python | 2,076 | 59 | import torch
import numpy as np
import pickle
def load_pickle_file(file):
"""
input: pickle file
return:list of feature, [(),(),().....()], in every tuple contain five feature:
pdb_chain: PDB ID and Chain ID for example :4U3M_A
pairwise_seq_feat: one-hot encoding of sequence, shape:[seq_len,seq_le... |
07f7319a2a2c94b174dcdf700b9d0b639bf767e0cc33e50cee546d993aa8012a | Python | 2,077 | 72 | import argparse
from typing import Tuple
def get_next_version(release_type) -> Tuple[Tuple[int, int, int], str, str]:
current_ver = find_version("fairseq/version.txt")
version_list = [int(x) for x in current_ver.strip("'").split(".")]
major, minor, patch = version_list[0], version_list[1], version_list[2]... |
2c0a1c455bf7c49e93f75243c9e4494340b66d74aa1e8ac80a6900b877d111f7 | Python | 2,077 | 63 | import uuid
from jinja2 import Environment
from prettytable import PrettyTable
from ..charts.mixins import ChartMixin
from ..commons.utils import OrderedSet
from ..globals import CurrentConfig
from ..options import ComponentTitleOpts
from ..render import engine
from ..types import Optional, Sequence, Union
class Ta... |
671fc80cebe807eebdf2ef105879457881c69cae0ce5cfd01df37a5bd781037f | Python | 2,077 | 59 | import torch
import torch.nn as nn
import warnings
warnings.filterwarnings('ignore')
class Model_3DCNN(nn.Module):
# num_filters=[64,128,256] or [96,128,128]
def __init__(self, feat_dim=24, output_dim=1, num_filters=[64,128,256]):
super(Model_3DCNN, self).__init__()
self.feat_dim = feat_dim
... |
556095e4b55420417704d15ef9c92e4e2a2eabda4527fc8281b2aa9df818d624 | Python | 2,078 | 67 | """Helper function that gets instances of classes representing datasets built into :mod:`vak`."""
from __future__ import annotations
from typing import TYPE_CHECKING, Literal, Mapping
from .. import common
Dataset = Mapping
if TYPE_CHECKING:
from ..transforms import FramesStandardizer
def get(
dataset_co... |
88f960dfa80f5f300542b269f4f84c1385c7065549148ebb8813ed4d69863a0c | Python | 2,078 | 70 | import pandas as pd
import pytest
import vak
@pytest.mark.parametrize(
'config_type, model_name, audio_format, spect_format, annot_format, input_type',
[
('train', 'TweetyNet', 'cbin', None, 'notmat', 'spect'),
('predict', 'TweetyNet', 'cbin', None, 'notmat', 'spect'),
('eval', 'Tweet... |
8d14b4fdd8e8905d5f4314bcd5dae0ec11a807f815327518af900a8ab4008c94 | Python | 2,078 | 69 | import time
from mne.utils import logger
from functools import wraps
CONF_MAP = {"run_staging_script": "staging_script", "find_breaks": "find_breaks"}
def _is_step_run(func, instance):
"""Check if step was run."""
if func.__name__ in ["run_staging_script", "find_breaks"]:
step = CONF_MAP[func.__name... |
510dcf5571d2dcb84dd9721f7348c72ee8c0e074f07f4e6a9af2cc979350bca8 | Python | 2,079 | 42 | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. 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 cop... |
f83d9f82e8f2af9afdee473bc7ed4d1a9300dd0efe05756e49fcb13986da439d | Python | 2,079 | 44 | """
Cell sampling preprocessing based on CytoSPACE.
Installation:
CytoSPACE via https://github.com/digitalcytometry/cytospace
"""
import cytospace
import numpy as np
import pandas as pd
def cell_sampling(adata_sc, adata_st):
scRNA_data = pd.DataFrame(adata_sc.raw.X.toarray(),index=adata_sc.obs_names,columns=... |
317ffb22600978a7b5668c1ab45bfb3e88da45144c6f0624379b943aff089933 | Python | 2,080 | 68 | import logging
import numpy as np
from scvi.data import AnnDataManager
from scvi.data._constants import _SETUP_ARGS_KEY
from scvi.external.methylvi._constants import METHYLVI_REGISTRY_KEYS
logger = logging.getLogger(__name__)
def scmc_raw_counts_properties(
adata_manager: AnnDataManager,
idx1: list[int] | ... |
386a342b23ae347d9528cc9e690ed24b828829d7ded5aa8cb8b7b29137796975 | Python | 2,080 | 43 | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. 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 cop... |
5640e7f39070047936724e1e3f47e5398a41cb002f4dedceca7b4d0c9554b1d7 | Python | 2,080 | 77 | import numpy as np
from utils.measures import compute_di_from_log_prob_api
def generate_coupled_gaussian(N=20000, M=3, a=0.8, sigma=0.5, seed=0):
"""Generates a simple coupled Gaussian process with known DI."""
rng = np.random.default_rng(seed)
# Need M history points plus 1 future target
x = rng.norm... |
9eb2d979548987343da75f46ff60d4150be83875142db24d88dd64086ecce06c | Python | 2,080 | 50 | from batchgenerators.utilities.file_and_folder_operations import *
import shutil
from nnunetv2.dataset_conversion.generate_dataset_json import generate_dataset_json
from nnunetv2.paths import nnUNet_raw
def convert_kits2023(kits_base_dir: str, nnunet_dataset_id: int = 220):
task_name = "KiTS2023"
foldername ... |
47cc46b1e6d1199d12515b9e00cf0a064a8bc3bd9634a365870c3cee7f7cb553 | Python | 2,083 | 43 | #!/usr/bin/env python3
"""Acha as copias por simetria entre as 1784 estruturas do conjunto de perovskitas.
As celulas mistas foram geradas substituindo sitios da supercelula 2x2x2, e padroes
diferentes de substituicao podem dar a MESMA estrutura (uma substituicao unica, por
exemplo, e equivalente por translacao qualqu... |
087ee5109fae3b7b793369eb3cf92990791439a647557b291b05a1278de01088 | Python | 2,085 | 74 | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import unittest
import torch
from torch import nn
from fairseq.distributed import ModuleProxyWrapper
from .utils import objects_are_equal
... |
102a72760170419659e7be67b64f923308905f6abd7e42ef383dba28ce665d1a | Python | 2,085 | 61 | import unittest
from unittest.mock import patch
from pyecharts import options as opts
from pyecharts.charts import Sunburst
class TestSunburstChart(unittest.TestCase):
@patch("pyecharts.render.engine.write_utf8_html_file")
def test_sunburst_base(self, fake_writer):
data = [
{
... |
920d12334701b76c8059a699d95cbccb09ddde7b44e83070663ff9e97928e04e | Python | 2,085 | 50 | from batchgenerators.utilities.file_and_folder_operations import *
import shutil
from nnunetv2.dataset_conversion.generate_dataset_json import generate_dataset_json
from nnunetv2.paths import nnUNet_raw
def convert_kits2023(kits_base_dir: str, nnunet_dataset_id: int = 220):
task_name = "KiTS2023"
foldername ... |
32869edd189b46c5bee0f4cd8a34b9e4597312b4cec349ef59afb4b82ff5d6c0 | Python | 2,086 | 71 | #!/usr/bin/env python
# ENCODE DCC TAGALIGN pooler wrapper
# Author: Jin Lee (leepc12@gmail.com)
import sys
import os
import argparse
from encode_lib_common import (
log, ls_l, make_hard_link, mkdir_p, run_shell_cmd, strip_ext_ta)
def parse_arguments():
parser = argparse.ArgumentParser(prog='ENCODE DCC TAGA... |
6bfd36d0a610cdfa6c578c7a4a049c29cdd8e86ba7a04358a128e186f0d3e946 | Python | 2,086 | 66 | # Authors: Christian O'Reilly <christian.oreilly@sc.edu>
# Scott Huberty <seh33@uw.edu>
# Tyler Collins <collins.tyler.k@gmail.com>
#
# License: MIT
import sys
from pathlib import Path
import yaml
# TODO: Add parameters and references for below functions.
# TODO: Add magic methods and constructors ... |
97d9c8402005cc9619ebebe98f856acc59ccc31c9de236cf8c785749bd1376c4 | Python | 2,086 | 53 | import os
from os.path import join
import numpy as np
import yaml
from data.data_access import Data
from model import model_factory
class DataModelLoader():
def __init__(self, params_file):
self.dir_path = os.path.dirname(os.path.realpath(params_file))
model_parmas, data_parmas = self.load_parmas(... |
152ef825fbb800925f341deb4f6033d33a7ccdd896cbe4be6f33ed6fa3c63399 | Python | 2,088 | 73 | import os
import copy
import numpy as np
from utils.mpr import MultipleProcessRunnerSimplifier
# efficiently read large file by using a pointer
class FileReader:
@classmethod
# build a pointer for file
def build_pointer(cls, file_path, save_path):
with open(file_path, 'r') as r:
loc =... |
58658ba184f21e8bf2f9e9611bdf159d15d361b3ba74b60531e41b8e6c6d9d8b | Python | 2,088 | 65 | """Remember which signal columns a user ticked for a given set of columns.
Dual-signal recordings are usually processed in batches of files that share
the same column layout (e.g. ``dFoF_465`` + ``dFoF_405``). Rather than make
the user re-tick the same columns for every file, the selection is keyed by
the *set* of ava... |
2b2b395c88126454f71c4d6406278658d32e41f82fed337b5a5eb5ed1aaf06c0 | Python | 2,089 | 68 | from __future__ import annotations
import pytest
from src.features.behaviour_alignment.io.behaviour_file_pipeline import (
BehaviourFilePipeline,
)
from src.gui.framework.messages_and_errors import (
describe_exception,
format_action_error,
)
from src.processing.image_export import build_image_export_requ... |
3651f24d43b23f7c6c5556ae88bca171debd44e26df8fbb8179744941a8b846a | Python | 2,091 | 57 | """Controller for behaviour CSV column-name settings and persistence."""
from __future__ import annotations
import json
from pathlib import Path
from src.persistence.app_paths import config_file_path
class BehaviourColumnMappingStore:
"""Owns column-name settings persistence and app-state sync."""
@static... |
6f819827f66a29ea03e6eba4922b4697968101fb019abf83ca44ae79631cc8fc | Python | 2,092 | 75 | import os
import numpy as np
import pandas as pd
import pytest
MULTIVARIATE_FIXTURE_SEED = 42
skip_gh_actions = pytest.mark.skipif(
os.getenv("GITHUB_ACTIONS") == "true",
reason="Skipping residual tests on GitHub Actions.",
)
def _simulate_data(dependent: bool, z2_categorical: bool, seed: int = MULTIVARIAT... |
0463defa4359087197d9d7dfc23a78670929c567f666c168acb9d8d2f901a30f | Python | 2,093 | 55 | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
from fairseq.data.audio.frm_text_to_speech_dataset import FrmTextToSpeechDatasetCreator
from fairseq.tasks import register_tas... |
0f8c9b51b9ce950f65100805fd49bf07f8a4527b7f870a59f9fa25fe482bf27a | Python | 2,093 | 66 | from __future__ import annotations
import shlex
from typing import TYPE_CHECKING
import shellingham
from poetry.console.commands.env_command import EnvCommand
from poetry.utils._compat import WINDOWS
if TYPE_CHECKING:
from pathlib import Path
from poetry.utils.env import Env
class ShellNotSupportedErro... |
6a45c6f905b7076c219155581fb1e54f605d6343f8a4c2887eec6f1ea897112a | Python | 2,093 | 52 | import papermill as pm
import os
import shutil
print(os.getcwd())
censor_region = 'above'
output_dir = 'OUTPUTS/notebooks'
os.makedirs(output_dir, exist_ok=True)
for censor_split in [0.1, 0.5, 0.9]:
print(f'Running GCN notebooks for split {censor_split}')
pm.execute_notebook(input_path='omission_gcn.ipynb',
... |
75c32caa8b426ff6e80596c2f642cea2c482f2487a2a7b9d075be323a7745cb2 | Python | 2,093 | 62 | # 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 itertools as it
from typing import Any, Dict, List
import torch
from fairseq.data.dictionary import Dictionary
from fairseq.models.fai... |
4e6817500622cdcfc955e5d22e22f35e6bad18aac2b07d9c49d0c05338d47bb4 | Python | 2,094 | 53 | """
MoE implementation adapted from https://gist.github.com/ruvnet/0928768dd1e4af8816e31dde0a0205d5
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
# Define the Expert class
class Expert(nn.Module):
def __init__(self, input_dim, hidden_dim, output_dim):
super(Expert, self).__init__... |
bf5f841dd722faefd4349489ce0b14d3efe660a908f3a23a8e693ff0e18a2b7c | Python | 2,094 | 72 | import json
import os
import sys
import argparse
import random
import numpy as np
import tensorflow as tf
from tensorflow.keras.models import load_model
import transistor_extract as TE
from pathlib import Path
dir_path = os.path.dirname(os.path.abspath(sys.argv[0]))
repo_root = Path(__file__).resolve().parents[2]
pr... |
01e5710dcc15073760540686198c3fe8149b8562f300854c342a8f9b160b262d | Python | 2,095 | 87 | # Copyright (c) Facebook, Inc. All Rights Reserved
import torch
from torch import nn
class Loss(object):
def __call__(self, *args, **kwargs):
raise NotImplementedError
# Dummy Loss for testing.
class DummyLoss(Loss):
def __init__(self):
self.loss = nn.CrossEntropyLoss()
def __call__(s... |
9bdba1bf061f68a71820dfe5d4ab17b34efa8a4ccceafa87e2b011006b5904f8 | Python | 2,095 | 60 | ###20210924原始数据记录的过程取消2×2bining模式
from PyQt5.QtWidgets import QDialog,QMessageBox
import pco
import cv2 as cv
import numpy as np
import os
import time
def set_roi():
# app=QApplication(sys.argv)
dialog = QDialog()
# 打开相机记录单个图片
with pco.Camera() as cam_panda:
cam_panda.configuration... |
f8fa5ad40cac1592b2c2c6d7d024d7018c9eb759b4d38f573ec73b291ecd30be | Python | 2,096 | 58 | import unittest
import sys
import shutil
import os
import gzip
import re
if "DEBUG" in sys.argv:
sys.path.insert(0, "..")
sys.path.insert(0, "../../")
sys.path.insert(0, ".")
sys.argv.remove("DEBUG")
import metax.PrediXcanFormatUtilities as PrediXcanFormatUtilities
import metax.WeightDBUtilities as We... |
0141c2cb27526f8aadc8f59c8d0db7e0ef0936101936db1c7279a00b10572d8c | Python | 2,097 | 66 | """Create Fourier-scrambled versions of some images in the selected stimuli directory."""
import cv2 # type: ignore
import numpy as np
def fft_phase_scrambling_channel(
channel: np.ndarray,
random_seed: int = 42,
) -> np.ndarray:
"""Apply FFT phase scrambling to one channel of an image.
:param chan... |
b02895cfb4ccedf2bb86134195eb434619475720fb0023c493468d35b158c2da | Python | 2,097 | 56 | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
from functools import partial
from typing import Dict, Literal, Optional
from mattergen.diffusion.losses import SummedFieldLoss, denoising_score_matching
from mattergen.diffusion.model_target import ModelTarget
from mattergen.diffusion.training.... |
04a76e23f59a95865c21a081b83fd1f24bc79053c721e9495fd48e8319070026 | Python | 2,098 | 56 | '''
EffNet: AN EFFICIENT STRUCTURE FOR CONVOLUTIONAL NEURAL NETWORKS
Implementation in Pytorch of Effnet.
https://arxiv.org/abs/1801.06434
'''
import torch.nn as nn
class Flatten(nn.Module):
def forward(self, x):
x = x.view(x.size()[0], -1)
return x
class EffNet(nn.Module):
def __init__(... |
4de6b5c81c7c8e68a27a94125c048e1d7ea4ee0ffa2c648fb718312756033a28 | Python | 2,098 | 59 | # coding=utf-8
# Copyright 2018 The T5 authors and HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless require... |
272ae3a09e74207dd9acb463b90aa59e22246d32e5e115219cb9ffc92de46edf | Python | 2,099 | 40 | from typing import Union, Tuple, List
from batchgenerators.transforms.abstract_transforms import AbstractTransform
from nnunetv2.training.nnUNetTrainer.nnUNetTrainer import nnUNetTrainer
import numpy as np
class nnUNetTrainerNoDA(nnUNetTrainer):
@staticmethod
def get_training_transforms(patch_size: Union[np... |
9c4c5cdb2eea7ba2235c3e0a04e7692efad019db1be55821ba6f5cfc45f46b21 | Python | 2,099 | 68 | import pandas as pd
from .power_divergence import PowerDivergence
class GSq(PowerDivergence):
"""
G-squared test for conditional independence on discrete data.
This class is a thin specialization of :class:`PowerDivergence` with
``lambda_="log-likelihood"``. For the contingency-table construction, c... |
dce1ca3e390dc033fc3431d360b017685b50b5c3d95b1e9e55cb431748c33afa | Python | 2,099 | 73 | # 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"""
import functools
import importlib
dependencies = [
"dataclasses",
"hydra",
"numpy",
"omegaconf",
"... |
25086585ea4da4d6574123141b91682b3c1949785273405149dfcf54a80115fb | Python | 2,100 | 52 | import polars as pl
from src.utils import read_gtf
from genome_kit import Interval
transdecoder = pl.read_csv("full_nt.fasta.transdecoder.gff3", separator = "\t", new_columns=["seqid", "source", "type", "start", "end", "score", "strand", "phase", "attributes"])\
.drop_nulls()\
.filter(pl.col("type") == "CDS")\... |
35c19035cfc8f2353b4a5582a980f138128a89596e05514efb371d8617f7afed | Python | 2,100 | 61 | # coding=utf-8
# Copyright 2018 The T5 authors and HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless require... |
80c3215d2e613a7058d09bf9e043d466a5adbd793fa52759fd74a89a1298618b | Python | 2,101 | 74 | """Cluster-based permutation statistics for NIRS channel-level simulations."""
import numpy as np
import mne
def ftest_rel_no_p_custom(*args):
"""
Compute a paired-samples t-statistic and convert it to F.
"""
condition1, condition2 = args[0], args[1]
diff = condition1 - condition2
var = np.va... |
0a0b56fd479f4e20727d9bfb8b9951b75b98f8079e1b1278e7f0f5aa3f41f266 | Python | 2,102 | 95 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2016-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
from __future__ import absolute_import
from __future__ import division
from... |
1852ec97eec95469e1e8de0241ca07ed61cbb28613fe34e8e48d90a6b90d205e | Python | 2,102 | 50 | #!/usr/bin/env python
"""Small SERIAL demo — neural pattern similarity on 5 representative parcels.
Runs single-condition (R4) and triple / across-condition (R5) pattern similarity
on five parcels drawn from the significant regions in Supplementary Tables S3-S6
(bilateral auditory STG, middle temporal gyrus, and precu... |
232d2bf8a889e11ad04c324db118246356700646b5bf6c4c153bdbb6e6abf143 | Python | 2,102 | 59 | import os
import pandas as pd
from BLRun.runner import Runner
class GRNBoost2Runner(Runner):
"""Concrete runner for the GRNBoost2 GRN inference algorithm."""
def generateInputs(self):
'''
Function to generate desired inputs for GRNBoost2.
If the folder/files under self.input_dir exis... |
5d5b7e308d30e3d6de52b22a69a311028ee8828a9c14942d6b5726e2167d239a | Python | 2,102 | 79 | import cv2
from PIL import Image, ImageDraw
import numpy as np
def drawline(draw, pt1, pt2, color, thickness=1, style='dotted', gap=15):
dist = ((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2) ** .5
pts = []
for i in np.arange(0, dist, gap):
r = i / dist
x = int((pt1[0] * (1 - r... |
98511db7b71331325e7a49925dd5b93db52d877d46d78b6fd7666dd3351eb2d4 | Python | 2,103 | 61 | """Embedding layers shared by GPN-SS and GPN-MSA."""
from typing import Protocol
import torch.nn as nn
import torch.nn.functional as F
from jaxtyping import Float, Int, Num
from torch import Tensor
class AuxEmbeddingConfig(Protocol):
"""Configuration fields consumed by :class:`OneHotAuxEmbedding`."""
vocab... |
b8b19cdcefae83bc921bca6d9697197f73ea39559c85e5d28f829a1e7160e0f0 | Python | 2,104 | 59 | import numpy as np
import pytest
from st_risk.risk.score import combine_risk_features, enumerate_weight_schemes, grouped_zscore, weight_scheme_name
def test_combine_risk_features_returns_unit_interval_scores():
features = {
"phi_local": np.array([0.0, 1.0, 2.0]),
"phi_uncertainty": np.array([0.0,... |
25a6668533af7e6ad77ea0f3fc5c8445e3e9989185e4351497f54b8c6c3fe0f6 | Python | 2,105 | 73 | import argparse
from pathlib import Path
import anndata
import pandas as pd
from scipy.sparse import csr_matrix
def convert_to_h5ad(dataset_dir: Path):
print(f"Reading {dataset_dir}")
res_path = dataset_dir / "adata.h5ad"
if res_path.exists():
print(f"File {res_path} already existing.")
... |
8294f68b3a95f6d77bf0a4060aba1d5cb05e9f10967be9f5d66555f0211857ad | Python | 2,105 | 69 | import vcf
import logging
import pandas
import numpy
def int_treatment(x, allele_index):
try:
d_ = (int(x) == allele_index + 1)
except:
d_ = 0
return d_
def float_treatment(x):
try:
d_ = float(x)
except:
d_ =0
return d_
def vcf_file_geno_lines(path, mode="genot... |
6897876ae64366728a6cceed014f9a6784b207c92658945ae7097cecd20e51c9 | Python | 2,106 | 69 | import os
import tempfile
import re
import argparse
from tqdm import tqdm
parser = argparse.ArgumentParser()
parser.add_argument("--txt", type=str)
parser.add_argument("--lid", type=str)
parser.add_argument("--dst", type=str)
parser.add_argument("--model", type=str)
args = parser.parse_args()
UROMAN_PL = args.model +... |
a24924da5eba03aa416b2bb9527d9ed34f2cba07657590bb9f163de96d3e3865 | Python | 2,106 | 67 | #!/usr/bin/env python3
"""Validate docs/examples README copies match transformed examples/ READMEs."""
from __future__ import annotations
import argparse
import difflib
import sys
from pathlib import Path
REPO = Path(__file__).resolve().parents[1]
SCRIPTS = REPO / 'scripts'
if str(SCRIPTS) not in sys.path:
sys.p... |
dde406d0b2d08f728362404e0a785066fa2ed12fd06704e3773f0c259263690c | Python | 2,109 | 69 | import pytest
import torchvision
import torch
import cv2
import psutil
from pytorch_grad_cam import GradCAM, \
ScoreCAM, \
GradCAMPlusPlus, \
AblationCAM, \
XGradCAM, \
EigenCAM, \
EigenGradCAM, \
LayerCAM, \
FullGrad, \
ShapleyCAM
from pytorch_grad_cam.utils.image import show_cam_on... |
f3c63c2e40ecae4db9a95fc2326267b50e7b4046bbe3c8728d2959f6ce7e84ec | Python | 2,109 | 72 | # @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... |
0f740c236aa2dc4e29833014698c31838b445ef2bcb6e97ec188a9912fbb47cf | Python | 2,111 | 49 | import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
metadatapath = "..\\data\\meta_data.csv"
metadata = pd.read_csv(metadatapath)
valid_groups = [1,2,3,4,5,6,7,8,10,11,12,15,17] # Groups for which a sRC was observed
### Pie/bar chart for showing RC sizes
sizes = [np.sum(metad... |
e89beebedf3c4107b9f99e2f928b9ab950f867320b89e5bf9cf9f793c03e2bd9 | Python | 2,111 | 60 | import haiku as hk
import jax
from ...types import Nuclei
from ..nn.masked.basic import Constructor, PsiformerDense, no_upscale_ln
from ..nn.masked.features import featurize_real_space_vector
from ..nn.masked.message_passing import MaskedMPNNBlock
class NucleiGNN(hk.Module):
def __init__(
self,
f... |
ad0f29e051548c7b4b60d83cff1255b8f4f5e7105e4c0d9d370854c1e5193011 | Python | 2,112 | 53 | import numpy as np
from sklearn.feature_selection import mutual_info_regression
from sklearn.cross_decomposition import PLSRegression
class MIFeatureSelector:
"""Select top-k wavenumbers by mutual information with a single target. Fit on TRAIN only.
Retained for interpretability / wavenumber-importance analys... |
cef51d5cbd1b8ae664dc358188a912142c05a24f2bf7ad68d4eb8183b5d42e94 | Python | 2,113 | 42 | from copy import deepcopy
from batchgenerators.utilities.file_and_folder_operations import *
from nnunetv2.paths import nnUNet_preprocessed
from nnunetv2.utilities.dataset_name_id_conversion import maybe_convert_to_dataset_name
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
... |
7c7a7fcb7d30f3741ccb24ce10473a55934c71543570837fddebce7fe40e16a1 | Python | 2,115 | 82 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from glob import glob
from vlpp.utils import save_json
from vlpp.qamosaic import Mosaic
def main():
# Usefull directories
os.mkdir("data")
# Informations
participant_id = "${sub.sub}"
# Images Path
try: anat = glob("${sub.anat}")[0]
... |
6e68fdabe1d7b57d0d07a150d46535f6aa35a0bb27f7ef3ffde00cbe1daa399c | Python | 2,117 | 61 | """Controller for behaviour-file selection and parsing entrypoint."""
from __future__ import annotations
from collections.abc import Callable
from src.features.behaviour_alignment.services.reset_helpers import (
clear_common_selections,
clear_photometry_app_specific_selections,
)
from src.gui.framework.file_... |
dda355ad9540d8bca99eb935c5ab2251e1ff3e626d1f0d2f48d2cc13b53c1b21 | Python | 2,122 | 75 | """ featgen.py
Node feature generators.
https://github.com/RexYing/gnn-model-explainer
"""
import networkx as nx
import numpy as np
import random
import abc
class FeatureGen(metaclass=abc.ABCMeta):
"""Feature Generator base class."""
@abc.abstractmethod
def gen_node_features(self, G):
pass
cl... |
d2b74634bb2f6e10716e1516e94ec7e6633f75fb0e39e9eff4909efd3809c383 | Python | 2,123 | 61 | """
Functions for graph construction
"""
import numpy as np
import warnings
import scanpy as sc
import scipy.sparse as sp
import igraph as ig
import leidenalg
import pynndescent
from . import _utils as utils
def get_nearest_neighbors(
query_arr,
target_arr,
svd_components=None,
rand... |
2b3da6809f5a0a84bfa51a8a8492d94c1b30577b2f34c1c3a5a82ca47c33bd3f | Python | 2,126 | 54 | """
============================================================================
fig03or_perfusion_channel_split_merge__imagej_macro_6dc029b9.py — Fig 3r perfusion
============================================================================
What this script does: Jython for ImageJ: 3-channel deinterleave/merge. One ca... |
6978775146b892e9090299dd769e1e162b6277f4fd2245c1bb6ddb0a6ccbd097 | Python | 2,129 | 43 | # Source code:
# https://github.com/zbmed-semtec/doc2vec-doc-relevance-training/blob/main/code/train_model/train.py
# This file includes the modifications to the source codes according to this project!
import time
import logging
import utilities as utilities
import gensim
def run(best_params, args):
# 1) Lo... |
02921e784af1a5f03ea65b5adfcd920982210b7fbef9e3667ba3d0a3dd89a0e1 | Python | 2,130 | 74 | # @license
# Copyright 2023 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... |
daeb22b1f6b5949091f574bc8d86ef3ee179c4d7747dc793ad877d6c79980ca7 | Python | 2,132 | 73 | class Keys:
# obs keys
LEAVES: str = "novae_leaves"
DOMAINS_PREFIX: str = "novae_domains_"
IS_VALID_OBS: str = "neighborhood_valid"
SLIDE_ID: str = "novae_sid"
# obsm keys
REPR: str = "novae_latent"
REPR_CORRECTED: str = "novae_latent_corrected"
HISTO_EMBEDDINGS: str = "histo_embedd... |
49770b63750e72aeb41170deeb8623323794246d7d87e16b50bcf9f533bd943c | Python | 2,136 | 77 | #!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.11"
# dependencies = [
# "tensorstore",
# ]
# ///
import os
import pathlib
import shutil
import tensorstore as ts
SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__))
def write_ocdbt_files(name, config):
print(name)
files_dir = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.