sha256
stringlengths
64
64
language
stringclasses
27 values
size
int32
1
491k
lines
int32
1
21.8k
content
stringlengths
1
200k
733325a0b479550dcfc388267882772be456f54a44a37d80e8e773753dc05959
Python
2,497
91
import GeoJax as gj import numpy as np def generate_anisotropic_unit_vectors(n, scale=(1.0, 1.0, 1.0), orient_axis=None): """ Generate anisotropic unit vectors on a sphere, optionally oriented to a hemisphere. Parameters ---------- n : int Number of vectors. scale : tuple of 3 fl...
83d0bfad5a500059034355fdf729df39fa91d2089d1c835ee719ac87461ed2a3
Python
2,498
80
# Copyright 2023 BioMap (Beijing) Intelligence Technology Limited import torch import torch.nn as nn from .performer import Gene2VecPositionalEmbedding, RandomPositionalEmbedding from torch.nn import functional as F class pytorchTransformerLM_mse(nn.Module): def __init__(self, num_tokens, ...
fbfb25ae067e8e86cdfdad150f3c7ecfd94c9f3c7c2b2a93ce62b3524bfe5077
Python
2,500
69
"""test loss functions""" import torch from torch.autograd import gradcheck from torch.testing import assert_close import vak.nn.loss def tensor_to_gradcheck_var(tensor, dtype=torch.float64, requires_grad=True): """Converts the input tensor to a valid variable to check the gradient. `gradcheck` needs 64-bit ...
07cd0d6f460fcee1857d7011eb5024458ece1742828b4cf8f27f6c9541465b57
Python
2,501
69
# Copyright 2021 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agr...
83460e1cafbf4b783aadbbd970687efb3c6e47f7ef80f80b299ec08093fbf570
Python
2,501
54
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'UI/AddWindow.ui' # # Created by: PyQt5 UI code generator 5.9.2 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow: QtWidgets.QM...
ff425a3c2bd076bb7f64c8496839748fa24f0ed8b4afc3e73af31d5a9a5bdf4a
Python
2,501
81
"""tests for vak.cli.train module""" from unittest import mock import pytest import vak.config import vak.common.constants import vak.common.paths import vak.cli.train from . import cli_asserts @pytest.mark.parametrize( "model_name, audio_format, spect_format, annot_format", [ ("TweetyNet", "cbin",...
b37740e9f0c0f96d70661975287b4c3da07def3b4268bfbd4bf0b76d50692534
Python
2,502
98
import numpy as np # Colours and types Types = np.array(["T4", "T5"]) Type_colours = np.array(["#17becf", "#ff7f0e"]) Subtypes = np.array(["T4a", "T4b", "T4c", "T4d", "T5a", "T5b", "T5c", "T5d"]) Subtype_colours = np.array( [ "#1f77b4", "#9edae5", "#98df8a", "#bcbd22", "#d6...
9cd6fe334f297c735b75ba31a5629e82a1b97f6f3459570c89bd2135fcba816c
Python
2,505
65
# coding=utf-8 # Copyright 2018 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
eafcf1233029875f4bdce813e904d1644b4a576a749fc1059a0da6bafb419d05
Python
2,505
83
import torch import torch.utils.data as Data import torchvision from lib.network import Network from torch import nn import time # def calc_acc(x, y): # x = torch.max(x, dim=-1)[1] # accuracy = sum(x == y) / x.size(0) # return accuracy train_data = torchvision.datasets.MNIST(root='./mnist', train=True, ...
3492038eaa161aefb9137c8fffc9312538701c7c35193e7d399aa728cc965f12
Python
2,507
79
#!/usr/bin/env python # -*- coding: utf-8 -*- """Objects to classify nuclei""" from typing import Optional, Tuple import numpy as np import pandas as pd from shapely.geometry import Point from shapely.geometry.polygon import Polygon class PolygonClassifier(object): """Classifies data""" def __init__(self)...
91de7d47e39ccbb594eca23eef193f7bb732c3ed14df7c4369c4d60e0133c512
Python
2,507
67
# coding=utf-8 # Copyright 2018 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
30bb75353547a990c14de27d470643205d730e585771fdaf87f271702b214363
Python
2,508
74
''' Provides a general testing class which inherits from unittest.TestCase and also provides the numpy testing functions. ''' import contextlib import unittest import os.path from inspect import getsourcefile import numpy as np from numpy.testing import (assert_almost_equal, assert_array_eq...
89b74df9c3cd67a553753b0332307add345e82b69b5a939a1a72f9e3dbddb170
Python
2,509
72
#!/usr/bin/env python # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import argparse import fileinput from tqdm import tqdm def main(): parser = argparse.ArgumentParser( desc...
b8edd9b82e3316b5c4ff9e17f71cfd486d37a6de8f3a0d901b7a16952893a15f
Python
2,511
80
# Copyright (C) 2025 ETH Zurich, Moritz Thürlemann, and other AMP contributors """basic scatter_sum operations from torch_scatter from https://github.com/mir-group/pytorch_runstats/blob/main/torch_runstats/scatter_sum.py Using code from https://github.com/rusty1s/pytorch_scatter, but cut down to avoid a dependency. Py...
b0fde5882929907086fb237b60219e09f3e46f7c715a1def2500dcb51833b497
Python
2,512
89
import os import csv import random BASE_DIR = os.path.dirname(os.path.abspath(__file__)) CSV_FILE = os.path.join(BASE_DIR, "tm_score_results.csv") OUTPUT_DIR = os.path.join(BASE_DIR, "processed_data", "splits", "similarity_experiments") TOTAL_SAMPLES = 2600 def create_similarity_splits(): if not os.path.exists(...
df4d717da4a6866bf8e1e14bea6a520e39ebb0dc6b78d5fa4e1dc81fd29fb2f9
Python
2,513
87
#!/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. """ Data pre-processing: build vocabularies and binarize training data. """ import argparse import glob import os impor...
ec5564b1e3209f66889b83aeec45c7a0a79c0c973b79cd39b68adec78299a13a
Python
2,513
64
import torch from nnunetv2.training.nnUNetTrainer.variants.benchmarking.nnUNetTrainerBenchmark_5epochs import ( nnUNetTrainerBenchmark_5epochs, ) from nnunetv2.utilities.label_handling.label_handling import determine_num_input_channels class nnUNetTrainerBenchmark_5epochs_noDataLoading(nnUNetTrainerBenchmark_5ep...
ac18cb14c8a92765f4e915119978186f683045701ab5c97e34eefb892ad785ba
Python
2,514
79
""" Text Processing for NeuroVFM-LLM This module provides utilities for text processing including: - Text processing for visual instruction tuning - Task classes for visual instruction tuning objectives """ from typing import Dict, List import torch import random import json import logging def process_text( con...
2515bf687882c7501dc94e57f36c9727a43e827a2511543c5345ede2d4d639d5
Python
2,515
84
import os import subprocess from datetime import datetime from threading import Thread, Event from configs import SYNC_INTERVAL, LOGGER, LOG_PATH, ROOT_DIR, SYNC_TIMEOUT, RESULT_PATH, SYNC_SCRIPT_PATH def now_int(): epoch = datetime.utcfromtimestamp(0) return int((datetime.now() - epoch).total_seconds()) c...
703553f47f2d3126e94b6ddbde58907e861742e7cea6f419c4c1e2e6ca1129f1
Python
2,515
73
import json import numpy as np epsval = np.finfo(float).eps minval = np.finfo(float).min maxval = np.finfo(float).max def _log_bounded(x): # transforms, roughtly speaking, [0.00001, 100000] to [-10, 10] if not np.isfinite(x): return x if x<epsval: x=epsval if x>maxval: x=maxval y = np.log(x) retur...
cc2c65851fa9cde1cdea0b7280a3007ff9f5d2e0a96bb8ded300dccf5e5540d9
Python
2,515
87
import os import tempfile import re import librosa import torch import json import numpy as np import argparse from tqdm import tqdm import math from transformers import Wav2Vec2ForCTC, AutoProcessor from lib import falign_ext parser = argparse.ArgumentParser() parser.add_argument("--uroman_txt", type=str) parser.ad...
dedff9465469c50f3f3e045c35fa54db38df28b955560777f0c8ca875fbd4910
Python
2,515
78
"""Simple test/demonstration program of pileup counting.""" import argparse import logging from timeit import default_timer as now import numpy as np import medaka.common import medaka.features def main(): """Entry point for pileup counting program.""" logging.basicConfig( format='[%(asctime)s - %(n...
9ad231f36e253599c2a52da3541c52ead4b49f75b027890e60c67ca08317cd91
Python
2,517
69
from argparse import ArgumentParser from pathlib import Path import nibabel as nib import numpy as np import pandas as pd def parse_args(): parser = ArgumentParser() parser.add_argument("metadata", type=Path) parser.add_argument("mask", type=Path) parser.add_argument("image_dir", type=Path) parse...
728de7596ee8bb3a5c038b7394b29eb6b8c7bd6226b80733efdf238d2d8c2204
Python
2,518
77
from ... import options as opts from ... import types from ...charts.basic_charts.geo import GeoChartBase from ...commons.utils import OrderedSet, JsCode from ...exceptions import NonexistentCoordinatesException from ...globals import ChartType GMAP_API = "https://maps.googleapis.com/maps/api/js?key={}" class GMap(G...
fbf2753d78521f702943c389d547804d0013a804d6ee008b2188cf77a0bf81ed
Python
2,518
93
import GeoJax as gj import numpy as np import pandas as pd def generate_anisotropic_unit_vectors(n, scale=(1.0, 1.0, 1.0), orient_axis=None): """ Generate anisotropic unit vectors on a sphere, optionally oriented to a hemisphere. Parameters ---------- n : int Number of vectors. ...
1028403eb4437871407d260a901efd884666c5d0004a4b730669a50c0ad54b79
Python
2,519
82
import torch import torch.nn.functional as F import numpy as np from scipy import interpolate class InputPadder: """ Pads images such that dimensions are divisible by 8 """ def __init__(self, dims, mode='sintel'): self.ht, self.wd = dims[-2:] pad_ht = (((self.ht // 8) + 1) * 8 - self.ht) % 8 ...
f0940a9bc1d43ab885136255fd34d99549238e446e969987f038eae2ff49bc4b
Python
2,519
68
import torch.nn as nn import torch class SKConv(nn.Module): def __init__(self, features, WH, M, G, r, stride=1, L=32): """ Constructor Args: features: input channel dimensionality. WH: input spatial dimensionality, used for GAP kernel size. M: the number of branc...
4d193615578d1c425e5b7d2356d304942e12771afb0fcdefde3d431c9202d2fd
Python
2,521
65
"""tests for vak.config.spect_params module""" import pytest import vak.config.spect_params from .attr_helpers import simple_attr # approaching to testing validators adopted from # https://github.com/python-attrs/attrs/blob/a025629e36440dcc27aee0ee5b04d6523bcc9931/tests/test_validators.py#L338 def test_freq_cutoffs...
7cbc505db554fbf9c710752f794789de078c7faa44d73966bfdb17f14efbf2ee
Python
2,522
114
# -*- coding: utf-8 -*- import os import json import shlex import shutil import subprocess from jinja2 import Environment, FileSystemLoader PKG_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TPL_PATH = os.path.join(PKG_PATH, "templates") def load_json(filename): with open(filename, 'r') as...
accab0e5b02e07a7663ce5385e9bed5ceb036778964ccf330554f83c10079870
Python
2,522
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 torch import torch.nn as nn # Different encodings for the atom distance embeddings class GaussianSmearing(torch.nn.Module): def ...
f40768f8d9d1e6ffc070a72c871a62e9016bf4f9af2018284a62fd8efb04b254
Python
2,522
75
#!/usr/bin/env python # -*- coding: utf-8 -*- """Compares automated vs. manual cell counts""" import os from glob import glob from typing import Generator import pandas as pd import matplotlib matplotlib.use("Qt5Agg") from tqdm import tqdm # noqa E402 from utils import Image # noqa E402 from utils.data_pickling ...
047ea6a6dbe91e3906997a0163e46b4e966e91e4984754ea359e5a48172d8b9b
Python
2,525
59
"""Comparison of pattern-similarity z-maps to Neurosynth meta-analytic maps (R6, Fig 5). Ports `paper_revision_analyses/pattern_sim_to_neurosynth_smooth25mm.py`. The per-parcel neurosynth averaging, Pearson correlation, negative-zeroing, and within-map BH-FDR are unchanged. The pattern-similarity z-values now come fro...
5f0778055012ef659d36a289dadd0391e6b4cdedbb2b7ac35c35486a233cd3ae
Python
2,525
71
import pytest import torch import scvi.module._vae as vae_module from scvi import REGISTRY_KEYS from scvi.module import VAE @pytest.mark.parametrize("n_samples", [1, 2, 3]) @pytest.mark.parametrize("gene_likelihood", ["zinb", "nb", "poisson"]) @pytest.mark.parametrize("n_input", [100]) @pytest.mark.parametrize("batc...
6b15427d2c2f3bc2ee2919f3765cb58a23ffe3a68c42be715811a45edb1e9107
Python
2,525
85
#!/usr/bin/env python """Extract protein PDB files required for the US-align similarity analysis. Raw PDBbind structures are not included in this repository. By default, the script reads the published split lists and a local PDBbind v2020.R1 directory. """ from __future__ import annotations import argparse import shu...
75e05526e3781a380fbd89411357fe455fde8bca76d9707463fee2a1b6f9632d
Python
2,526
83
import pytest from pgmpy.base import DAG @pytest.fixture def cg(): edges = [("U", "X"), ("X", "M"), ("M", "Y"), ("U", "Y")] roles = {"exposures": "X", "outcomes": "Y"} return DAG(ebunch=edges, roles=roles) @pytest.fixture def cg2(): cg2 = DAG( ebunch=[("U", "X"), ("X", "M"), ("M", "Y"), ("U...
962184667f28eb669031422a4aa47a061ef8a040a2da6bc58b1716b6b1b8ab50
Python
2,526
75
import pandas as pd import pytest from sklearn.metrics import accuracy_score, f1_score from pgmpy.base import DAG from pgmpy.example_models import load_model from pgmpy.metrics import CorrelationScore @pytest.fixture def model_and_data(): alarm_model = load_model("bnlearn/alarm") alarm_data = alarm_model.sim...
f015e6b313a90de0bc714e24b309cc6e59465af0e1943bcc528b2a34d389db5b
Python
2,528
71
import unittest from unittest.mock import patch from pyecharts import options as opts from pyecharts.charts import Sankey class TestSankeyChart(unittest.TestCase): @patch("pyecharts.render.engine.write_utf8_html_file") def test_sankey_base(self, fake_writer): nodes = [{"name": "category1"}, {"name": ...
4bd5f1af75f642c97f5cb4b4721609c83d69ee9c5417003f9f8fb698e821b0ba
Python
2,530
81
#!/usr/bin/env python # ENCODE DCC Count signal track generation # Author: Jin Lee (leepc12@gmail.com) import sys import os import argparse from encode_common import * def parse_arguments(): parser = argparse.ArgumentParser(prog='ENCODE DCC Count signal track generation', ...
f1dec248378c61d06d49645254416d89b270a478cfcdbcf33854123932240318
Python
2,531
83
import torch import torch.utils.data as Data import torchvision from lib.network import Network from torch.autograd import Variable from torch import nn import time def calc_acc(x, y): x = torch.max(x, dim=-1)[1] accuracy = sum(x == y) / x.size(0) return accuracy train_data = torchvision.datasets.MNIST(...
94d22d58aad248c9526a4c9ff1d1bbad02f7336b47a926ee11a009765168d3fd
Python
2,532
59
''' Logic to generate inflammation profiles for prescribed min/max induction days ''' import numpy as np import pickle np.random.seed(0) def induction_linear(max_years, year_s, upper_prop, min_length_induction, max_length_induction): # Make linear propensity function prop_induction = np.zeros(max_years * 12) ...
6a722d94d092e90a1cfcabc1517f31c1ee37072528f0fc9a02868be279baa000
Python
2,534
73
"""Resolving a tagged mention to the BRENDA entities it could name. Deliberately not part of the model: it holds no learned parameters, so it can be swapped without touching a checkpoint. The answer is a *set*, since a surface form is not owned by one entity, and the empty set is an answer — a NIL mention — rather tha...
ee08476d4ed28abe43c7f2f2323ebaedc6f002c868d57ad671947ca8d4ff52f3
Python
2,534
59
from typing import Tuple, List import loompy import numpy as np from sklearn.decomposition import IncrementalPCA import logging from harmony import harmonize import pandas as pd class IncrementalResidualsPCA(): """ Project a dataset into a reduced feature space using PCA on Pearson residuals. See https://www.biorx...
a470dc16c6169fbcf390a9bde4f73d4ebc12907df4699e7d5a7921cae8b139d3
Python
2,537
93
import GeoJax as gj import numpy as np import pandas as pd df_point = pd.read_ def generate_anisotropic_unit_vectors(n, scale=(1.0, 1.0, 1.0), orient_axis=None): """ Generate anisotropic unit vectors on a sphere, optionally oriented to a hemisphere. Parameters ---------- n : int Numb...
f1a7767103694ccc4195c4bc798fadc4f72732f63414feabefb8e43e384b2ca9
Python
2,537
84
import h5py as h5 import numpy as np class Epoch(): """ Represents a data epoch with a start time (in seconds), an end time (in seconds), and a name Optionally includes a start_index and an end_index """ def __init__(self, name, start_time, end_time): """ name : str ...
fea958e181d775d2ff6d32fd5221e06ac46f010fa1f30dad11fe6e02cca36c22
Python
2,539
80
from src.utils import read_gtf, read_SJ, gtf_to_SJ import polars as pl from pathlib import Path import os SR_SJ = ( pl.concat([read_SJ(file) for file in Path('export/STAR_results').rglob('*_SJ.out.tab')], how='vertical') .unique(['chrom', 'start', 'end', 'strand', 'motif']) .select(['chrom', 'start', 'end'...
a7f434989dba76f926660e99c3c6e321cec11b5351cafb1213c905b4d7bfac01
Python
2,540
76
import shlex import os import sys from argparse import ArgumentParser, SUPPRESS from collections import defaultdict from sys import exit, stderr from subprocess import check_output, PIPE, Popen from subprocess import PIPE def subprocess_popen(args, stdin=None, stdout=PIPE, stderr=stderr, bufsize=8388608): ...
e78ab2577abd8b60e1e2a6851b2cf3b69c7578257593ae0df0ec973dc6780491
Python
2,543
116
"""Definitions of the protocol parameters. The type of these parameters signifies that the data for this parameter should come from the protocol file or from the protocol maps. These parameters are never optimized and are always set to the given input data. """ from mdt import ProtocolParameterTemplate __author__ = '...
8be7bf37c500c9e318bb881339ca65eed49df26d3b718714be40604328dc4d3e
Python
2,544
54
import itertools aa_set = {"A", "C", "D", "E", "F", "G", "H", "I", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "V", "W", "Y"} aa_list = ["A", "C", "D", "E", "F", "G", "H", "I", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "V", "W", "Y"] foldseek_seq_vocab = "ACDEFGHIKLMNPQRSTVWY#" foldseek_struc_vocab = "pynwrqhgdl...
6bb0edf69ed1286dd65626fbab8646a37e3eb4c1023b941b39cfce6693e8c8ee
Python
2,545
93
import GeoJax as gj import numpy as np import pandas as pd df_point = pd.read_pickle() def generate_anisotropic_unit_vectors(n, scale=(1.0, 1.0, 1.0), orient_axis=None): """ Generate anisotropic unit vectors on a sphere, optionally oriented to a hemisphere. Parameters ---------- n : int ...
c744672f0f3bf108e42909e3f6880525419a0d6cef396c8b9f15410075889439
Python
2,546
74
from __future__ import annotations import functools from dataclasses import dataclass from html.parser import HTMLParser from typing import TYPE_CHECKING if TYPE_CHECKING: from collections.abc import Callable # The following code was originally written for PDM project # https://github.com/pdm-project/pdm/blob...
bfcb5269154fcb2b65b02d36b718c89f99c720b42ee7ee93ed99b41f1f05589d
Python
2,547
71
# 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 import torch.nn as nn import torch.nn.functional as F class PQLinear(nn.Module): """ Quantized counterpart of nn.Linear...
72b0cbb4cfd39cc818482d93882e91c1c6e17533fab9d80f43ece74fd28708d3
Python
2,548
77
# -*- coding: utf-8 -*- """ Created on Thu Feb 6 20:52:03 2025 @author: hanna """ import numpy as np import pandas as pd def get_trial_inds(df, blockType, mode, n_sets): """ Finds the putative trials (and their lengths) within a block for use in analysis. Ensures that the number of sets of 8 tria...
84900a63f2ac6f2abda388248a2752e06eb90924af991c3656b9b1f1dcf31021
Python
2,548
75
import polars as pl from src.utils import read_gtf # Define functions def remove_peptide_with_conflicted_mapping(peptide_mapping: pl.DataFrame) -> pl.DataFrame: """Remove peptides that map to transcripts that include known and novel transcripts.""" peptide_to_remove = peptide_mapping\ .group_by("peptid...
13e0908992eec03c62b32d1b882a97985f70993cce809173ce04486216d5a339
Python
2,549
73
from typing import Protocol import jax import jax.numpy as jnp import jax_dataclasses as jdc from ..data import Batch from ..types import MolecularConfiguration, RandomKey class Augmentation(Protocol): def __call__(self, rng: RandomKey, pytree: Batch) -> Batch: raise NotImplementedError class Rotation...
b87a59171e26120ccb17fb194c38c654cf91246bb4634e02c936c4483eb96f95
Python
2,549
74
import shlex import os import sys from argparse import ArgumentParser, SUPPRESS from collections import defaultdict from sys import exit, stderr from subprocess import check_output, PIPE, Popen from subprocess import PIPE # 为phase筛选snp def subprocess_popen(args, stdin=None, stdout=PIPE, stderr=stderr, bufs...
184d86fa9e1a65ab4692aa9e970c0e96daa0d6421c65003e222b7548d0579573
Python
2,551
86
#!/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. """ Split a large file into a train and valid set while respecting document boundaries. Documents should be separated by...
62ea0cb728eabd66d721e6e42e083157ab1c7ab5cde50a950138de9a7c83cf08
Python
2,552
78
import torch import torch.nn as nn #import torch.nn.functional as F #from .activate import * from .deformable_conv import DeformableConv2d norm_name = {"bn": nn.BatchNorm2d} activate_name = { "relu": nn.ReLU, "leaky": nn.LeakyReLU} # "mish": Mish} class Convolutional(nn.Module): def __in...
3ef9096cd3de12d22c1d5e96b4d01020889a403e46568dc18cfa1a1185e2b39c
Python
2,553
47
import time import numpy as np from kanfood.split import stratified_group_kfold from kanfood.preprocess import Preprocessor from kanfood.features import PLSFeatures from kanfood.models import build_model, front_end_components from kanfood.metrics import regression_metrics, classification_from_tahini, classification_met...
5690b6b8169eba968d29c1e2cc9ee4fcef74fced4a1ca3bcc2fb9e5dd1720327
Python
2,553
90
"""Compatibility facade for behaviour parsing and signal extraction. New code may import the focused input-parsing and window-extraction modules directly. Existing imports from this historical module remain supported. """ from __future__ import annotations import re from pathlib import Path import numpy as np impo...
709bf4a20882140979beb87f8c73643df995b349ceab7f703b0d0f0c4acbd3e3
Python
2,554
63
import gzip class LiftRsNumbers: def _read_rs_history(self, histFile): RS_HISTORY = set() # store rs print("Reading '{}' file...".format(histFile)) for ln in gzip.open(histFile, mode='rt'): fd = ln.strip().split('\t') # Some very few entries in SNPHistory file are a...
727d5cc3e26a249b15246ab9bedf6152fc4e26dbea0063c8085b487b11bcc13e
Python
2,555
67
"""Diagnose which isomer group fails for the best selection methods.""" from __future__ import annotations from collections import defaultdict from pathlib import Path import numpy as np from oce.atomic_table import load_table from oce.correlations import correlations_for_molecule from oce.dataset import entry_to_at...
d3ea35fae9598387474110ed424906d60c1dfd5b14c5f336e8f3cebe20055942
Python
2,556
66
import pandas as pd import numpy as np import sys import argparse """ Contains a logic for making unique binary annotation categories from overlapping binary annotations produced by annot2annomat.py. All annotation categories: 100kDown 10kDown 1kDown 100kUp 10kUp 1kUp 3UTR 5UTR Exon Intron ProteinCoding Non...
50127c6cf42573799ea6d21d765b4e3dab5acf28b838c00e913408256b33d1c6
Python
2,557
93
import GeoJax as gj import numpy as np import pandas as pd df_point = pd.read_pickle() def generate_anisotropic_unit_vectors(n, scale=(1.0, 1.0, 1.0), orient_axis=None): """ Generate anisotropic unit vectors on a sphere, optionally oriented to a hemisphere. Parameters ---------- n : int ...
6a4425136b03defed7e0d4a8498050c4a041b9988314ee1cdb4a13a67212627a
Python
2,557
73
from itertools import product import numpy as np from pgmpy.factors.discrete import TabularCPD class NoisyORCPD(TabularCPD): """ Initializes the NoisyORCPD class. The NoisyOR CPD is a special case of TabularCPD for binary variables where a given variable can be activated by each of the parent varia...
971a1c37d00ece702ac827a47d7340561d99a22a1bd10544fd60bc503c67dbc5
Python
2,557
59
#!/usr/bin/env python # MIT License # # Copyright 2019 Broad Institute # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
04d32f0cf434cc8eb595a3fb241da94311f1f864c9ef03989c92fd5e9360bff9
Python
2,558
94
from __future__ import annotations from pathlib import Path def project_root() -> Path: return Path(__file__).resolve().parents[2] RESULTS_LAYOUT = { "tables": "tables", "figures": "figures", "metadata": "metadata", "artifacts": "artifacts", } def results_dir(path: str | Path) -> Path: re...
e5fac1124f0310d3be3936bff67c8b30d53473b32223161bda2eca2e7cec2214
Python
2,559
76
import pathlib from unittest import mock import pandas as pd import pytest import vak @pytest.mark.parametrize( "config_type, audio_format, spect_format, annot_format, dataset_prep_func_to_mock", [ ("eval", "cbin", None, "notmat", "vak.prep.prep_.prep_frame_classification_dataset"), ("learnc...
44202eadb88b998b9e90d135e3e5e749edd953185438005ab6cfacce803ef381
Python
2,560
56
from SparseCoding import fixed_s_mask import torch import torch.nn as nn class omics_net(nn.Module): ''' Two hidden layers One clinical layer (age) ''' def __init__(self, in_nodes, gene_nodes, pathway_nodes, hidden_nodes): super(omics_net, self).__init__() # activation fun...
7219b2226583630c8ec8406cd1530ac447d6c6c8f1bd50ca3a430b8b82a45cfe
Python
2,560
74
# /usr/bin/env python ''' Written by Kong Xiaolu and CBIG under MIT license: https://github.com/ThomasYeoLab/CBIG/blob/master/LICENSE.md ''' import os import numpy as np import torch import CBIG_pMFM_basic_functions as fc import warnings def CBIG_mfm_test_desikan_main(gpu_index=0): torch.cuda.set_device(gpu_inde...
ca1d0215af17db69f38af932428277829098b0ed8bc0b2ffb98f80c815a27ff7
Python
2,560
82
import pytest from skbase.utils.dependencies import _check_soft_dependencies, _safe_import from pgmpy import config torch = _safe_import("torch") @pytest.fixture(autouse=True) def reset_config(): """Reset pgmpy config to defaults after each test.""" yield config.set_backend("numpy") config.set_show_...
e1b3f5c8344ed5732edb718cdc10cff31526e520fe3a9fa3ce8a62c44923e4ec
Python
2,560
93
import GeoJax as gj import numpy as np import pandas as pd df_point = pd.read_pickle() def generate_anisotropic_unit_vectors(n, scale=(1.0, 1.0, 1.0), orient_axis=None): """ Generate anisotropic unit vectors on a sphere, optionally oriented to a hemisphere. Parameters ---------- n : int ...
3e23b44e1768f5096b9427af9449fcbc0674df82e5dd8c760871eec91b77a434
Python
2,561
85
#### ::: DNABERT-viz SNP analysis ::: #### import os import sys sys.path.append('../motif') import pandas as pd import numpy as np import argparse import motif_utils as utils def main(): parser = argparse.ArgumentParser() parser.add_argument( "--orig_seq_file", default='../examples/sample_dat...
84ea461a3b8c25716463129d305e379869e7a49ba9160abe11f4ad12d844bf64
Python
2,562
84
# Authors: Christian O'Reilly <christian.oreilly@sc.edu> # Scott Huberty <seh33@uw.edu> # License: MIT """Tests for topo_viz.py.""" import pytest import mne from dash import html from pylossless.dash.topo_viz import TopoPlot, GridTopoPlot, TopoData, TopoViz def get_raw_ica(): """Get raw and ICA objec...
8b162f5f7af4b765cbfe5e717be036050510ebf7c0c6e20b7ed6cbc7d32671c5
Python
2,562
76
from collections import OrderedDict import theano import theano.tensor as T from lasagne import utils from .base import Layer __all__ = [ "InputLayer", ] class InputLayer(Layer): """ This layer holds a symbolic variable that represents a network input. A variable can be specified when the layer i...
24a425cac6714e1eb79b44a911b7f39e32ad146beb1c7089d0e2efaafdeb1463
Python
2,564
75
import logging from typing import List import numpy as np import loompy class GSEA: """ Gene set enrichment analysis according to http://software.broadinstitute.org/gsea/doc/subramanian_tamayo_gsea_pnas.pdf Note: we rank genes based on the enrichment score from MarkerSelection, not correlation as in the paper....
4104b1438e2f262483f5a3700ce000e71f838d72bbc1f2c6d360fe7fe1dacd25
Python
2,565
76
import numpy as np import altair as alt from currentscape_visualization.utils import * def plot_currentscape(part_pos: pd.DataFrame, part_neg: pd.DataFrame, vm: np.array, taxis: np.array, tmin: int, tmax: int, return_segs: bool=False, segments_preselected: bool=True, vmin: ...
7d4719066211b293ccb13dca696f4c8fe2332cc3f87eec0cd6b3db4f654bd277
Python
2,565
71
import os import pandas as pd from BLRun.runner import Runner class PPCORRunner(Runner): """Concrete runner for the PPCOR GRN inference algorithm.""" def generateInputs(self): ''' Function to generate desired inputs for PPCOR. If the folder/files under self.input_dir exist, t...
854c628e2039db47d3f140e6dc88ba73789ecc8780fa49fc8e71fb102d1a8d11
Python
2,565
81
# 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 typing import List import torch from torch import nn from fairseq.modules.quant_noise import quant_noise class AdaptiveInput(nn.Modu...
bbfaa8436440731ee696bfc35251500781131c42a602c7967686692fcb5ad9df
Python
2,567
84
import numpy as np import scanpy as sc import ot import os import json import pandas as pd from scipy.spatial.distance import cdist from scipy.stats import pearsonr, spearmanr from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score def mclust(adata, arg, refine=False, key='z', pca_dim=32): f...
e6f6b95380be8e96b45d026eb6f4a24f380b8da7d35d91607e583cdfca044ec9
Python
2,568
107
# Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import os import torch from tqdm import tqdm class Stat: def __init__(self, keep_raw=False): self.x = 0.0 self.x2 = 0.0 ...
1c60cfe940e3bcda64ac1c121f24df4c62c18b9df8146d254b67964eef921383
Python
2,569
91
# -*- coding: utf-8 -*- # Copyright (C) 2018 Phillip Alday <me@phillipalday.com> # License: BSD (3-clause) """Utilities for (testing) MNE-based functionality.""" import warnings from tempfile import mkdtemp import mne import numpy as np def _mktmpdir(): """Create a temporary directory for testing writers.""" ...
a7093b53287f2a4f98c472e971858f7bd54c68c9e3bf3a97306bca7ec945505d
Python
2,569
98
#!/usr/bin/env python3 -u # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import argparse import sys from copy import deepcopy from scipy.signal import lfilter import numpy as np from tqdm...
6e5b5701cfb7a070f070fbee73cb9da9c7684c01faaf637f2132f8173b77fd36
Python
2,570
75
# 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. """ Train a network across multiple GPUs. """ from fairseq.dataclass.configs import FairseqConfig from fairseq.distributed import utils as di...
e2019bf86e5470e35b9cc2edff349fa85c2408ce23363aaa89698019485fb847
Python
2,571
41
import pytest class TestAICCondGauss: def test_score_bnlearn_no_parents(self, aic_cond_gauss_score): assert aic_cond_gauss_score.local_score(variable="B_cat", parents=()) == pytest.approx(-83.6952, abs=1e-3) assert aic_cond_gauss_score.local_score(variable="B", parents=()) == pytest.approx(-259.00...
2d6c3bd59ec560eafffd03be3017731bef81f878002c3ef0b4dbeb7bf9a95448
Python
2,572
75
__author__ = "alvaro barbeira" import gzip import os import logging import numpy from .Genotype import GF from .. import Utilities from . import Helpers def model_training_file_geno_lines(file, snp_annotation, snps=None): logging.log(9, "Processing Dosage geno %s", file) with gzip.open(file) as file: ...
e2e56a43b2b76c34459441e455b2299d9bea98102457c583f463ba82aaf30d62
Python
2,572
85
import pytest import torchvision import torch import cv2 from pytorch_grad_cam import GradCAM, \ ScoreCAM, \ GradCAMPlusPlus, \ AblationCAM, \ XGradCAM, \ EigenCAM, \ EigenGradCAM, \ LayerCAM, \ FullGrad, \ KPCA_CAM, \ SegEigenCAM from pytorch_grad_cam.utils.image import show_cam...
fcc7f05319be0c824ad3b61a8f0a28c4799b99af1ddc7c3148eaac4f3b3a8fb6
Python
2,572
73
import argparse import numpy as np import os import pickle import matplotlib.pyplot as plt parser = argparse.ArgumentParser( "Plot bivariate posteriors output by `compare-posteriors.py`" ) parser.add_argument( "--inpaths", help="Directories containing likelihood surfaces, etc output by `compare-posteriors...
0e3349e56b78e2626b2c434c074ddbcf925833fa29e7094465b650b9da5e5dcf
Python
2,574
83
import argparse from pathlib import Path import soundfile def get_insl_frame(parse): out = [] def is_ont_token(tok): return tok[0] in ["[", "]"]; res = [] x = [] for tok in parse.split(): if is_ont_token(tok): res.extend('_'.join(x)) x = [] res.a...
5d3ba2be3b5366c1f96743860c39d64dc1d4a3c3c34d0d966b3cb78f2f0f6015
Python
2,574
41
import pytest class TestBICCondGauss: def test_score_bnlearn_no_parents(self, bic_cond_gauss_score): assert bic_cond_gauss_score.local_score(variable="B_cat", parents=()) == pytest.approx(-86.3004, abs=1e-3) assert bic_cond_gauss_score.local_score(variable="B", parents=()) == pytest.approx(-261.61...
aa5a70a55e61acb2cf650f10a4d14bf09e72459e5196327b2a796a390bb33577
Python
2,574
81
import logging import os import anndata import pandas as pd from scvi.data._download import _pooch_retrieve_with_retries from scvi.utils import dependencies logger = logging.getLogger(__name__) _subtype_to_high_level_mapping = { "Astrocytes": ("Astrocyte Gfap", "Astrocyte Mfge8"), "Endothelials": ("Endothel...
21634f8af8f4d963e8b21b48a371d571ad45157fc2a0cb98ac40266d8dddf462
Python
2,575
65
import pandas as pd from pathlib import Path # Define root path (update 'root_path' with your base directory) root_path = Path(r'/data/elevchenko/MovieProject2/') output_path = Path(root_path / 'bids_data/derivatives') # Create output directory if it does not exist output_path.mkdir(parents=True, exist_ok=True) # In...
420d8ff6ae50aa4f6f569baaf8d8d164766879e2e867793e3bd8a6df1dc7f92c
Python
2,575
69
"""Tests for the functions in neuropil.py. Author: Sander Keemink (swkeemink@scimail.eu) Created: 2015-11-06 """ import numpy as np from .base_test import BaseTestCase from .. import neuropil as npil class TestNeuropilFuns(BaseTestCase): """Neuropil functions testing class.""" def setup_class(self): ...
df0b3bc734c2f8c986e42eaa7251c40eaa911e4c23100f65e04195c88a087821
Python
2,576
73
import os from os.path import join, basename, dirname import pandas as pd from matplotlib import pyplot as plt from config_path import PLOTS_PATH, PROSTATE_LOG_PATH base_dir = join(PROSTATE_LOG_PATH, 'review/9hotspot') files = [] files.append(dict(Model='Mutations with Hotspot adjusted', file=joi...
844b6c299f010fc0a0d5b39acc374fb92e1731e942d29324ebba9fee6d8d2fdc
Python
2,577
58
import gdb.printing class OutcomeBasicOutcomePrinter(object): """Print an outcome::basic_outcome<T>""" def __init__(self, val): self.val = val def children(self): if self.val['_state']['_status']['status_value'] & 1 == 1: yield ('value', self.val['_state']['_value']) i...
464d79997a74a885868bb82853c24dcdd1c614339abc602a655016068e9a7052
Python
2,579
94
import numpy as np from scipy.fft import fft, ifft def Surr_Theiler20200723(y,algorithm): """ z=Surr_Theiler20200723(y,algorithm) inputs - y, time series to be surrogated algorithm - the type of algorithm to be completed outputs - z, surrogated time series Remarks - This code ...
6c6493ae2cd327c224007182daa236a3e9a2ad4bf68084066b8fc99a51c3dde4
Python
2,580
75
"""The value-constrained aliases admit their range and refuse the rest.""" import math import pytest import torch from beartype.door import is_bearable from beartype.roar import BeartypeCallHintParamViolation from d3text import constraints from d3text.embeddings_store import StoreProvenance from d3text.models.base i...
c3651a55fdd555fc95194f200d0eeedcf17ad966657bc57641789ecd219674d3
Python
2,580
79
# -*- coding: utf-8 -*- """ @Time:Created on 2019/8/20 20:47 @author: LiFan Chen @Filename: lookahead.py @Software: PyCharm """ from collections import defaultdict from itertools import chain from torch.optim.optimizer import Optimizer import torch import warnings class Lookahead(Optimizer): def __init__(self, op...
8ae386843375f4da46aea69f2a7c94570c3cdeb4d7397f8e30b01ce2e27f0b76
Python
2,583
81
"""A setuptools based setup module. See: https://packaging.python.org/guides/distributing-packages-using-setuptools/ https://github.com/pypa/sampleproject """ try: from setuptools import setup, find_packages except ImportError: from distutils.core import setup, find_packages from os import path from io import...
a0fbd5a2e96ef78d108ad861fc9c28d72a5a8d35adb64a3ca9af514e886df087
Python
2,583
68
#!/usr/bin/env python3 # MIT License # # Copyright 2024 Broad Institute # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to u...
72dac81ab0bc9d9f860b065967e4405893298b00a73b772adc853d9d8016df1d
Python
2,584
82
"""Canonical SegRef3D mask-sequence naming and manifest helpers.""" from __future__ import annotations import json from pathlib import Path from typing import Iterable, Sequence MASK_MANIFEST_FILENAME = "segref3d-mask-manifest.json" MASK_SCHEMA_VERSION = 2 MASK_SLICE_ORDER = "segref3d-canonical-v1" def canonical_...