sha256
stringlengths
64
64
language
stringclasses
27 values
size
int32
1
491k
lines
int32
1
21.8k
content
stringlengths
1
200k
524b5de7b846ef319c16372de7e607f4d10845e0d0048cd16c233f8728586096
Python
4,287
130
import os from typing import Any, Iterable, List, Optional import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from sklearn.metrics import ( accuracy_score, balanced_accuracy_score, confusion_matrix, f1_score, ) def performance_eval( df, ground_truth_c...
9a63a936a752aeb171c5c32996839f6a90aff85a8adf780b4557fcf7666aaaa5
Python
4,287
124
import requests import zipfile import os from pathlib import Path from typing import Union def download_sample_data( destination_folder: str = ".", data_type: str = "h5_dir", ) -> Union[str, None]: """ Download sample data for Voluseg. Parameters ---------- destination_folder : str, optio...
b58a1aeb86619d2f24aa5c564255c2c05b384b41716bdc2ec031e7c8c3c33bdf
Python
4,287
92
#!/usr/bin/env python3 """Add the gene-level methylation weighting columns promised in Methods and in the reply to Reviewer 1 point 8, to Supplementary Table S2. Columns added, all from the pan-tissue combined stratum (05_combined), which is the stratum whose methylation statistics the manuscript reports: Reviewer 1'...
9dc23957506cf378c1581a7aa0f9cdc1b8123caa3e9441fefd7700e74cf1f07c
Python
4,292
128
# 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 .em import EM, EmptyClusterResolveError class PQ(EM): """ Quantizes the layer weights W with the standard Product Quantization ...
6c15678e5bd0d4ef7c01251aeed5e8eb6dcf56279610d982f0a8d80fd7f125ea
Python
4,293
134
"""`config.unfrozen_top_layers` leaves the base model's top layers trainable. Real models with a tiny 2-layer random BERT injected (`patch_base_model`), so there is no download. `unfrozen_top_layers=0` (the default) must stay byte-identical to the fully-frozen behaviour `test_base_model_eval_mode.py` already pins; the...
2431dab553c57d2e2b6dc9fcf0d5ae9f0736210f36c750a71901218de27d5fe3
Python
4,295
122
"""Smoke test for the `[project.scripts]` console-script entry points. The contract is stronger than "the module imports": the shim runs with the venv's `bin/` as `sys.path[0]`, never the repo root, so the module has to be part of the *installed distribution*. An earlier version resolved each entry point with `importl...
751287993435a7f0303f551440c790a23e2c458b7c158596e896847f00eb76ec
Python
4,295
129
#!/usr/bin/env python """ Process cluster-based power simulation results and plot empirical power. This script: 1. Resolves the result filename pattern. 2. Infers the block/subject grid from filenames. 3. Uses user-provided block/subject labels when they align safely. 4. Falls back to inferred file indices wit...
cd7b8606b9ab69cab70b12f799388bff2701bc734ebc76d709c13ebe4c1a93bd
Python
4,296
108
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from typing import Optional, Tuple, Union import torch from torch_scatter import scatter_add from mattergen.diffusion.corruption.corruption import B, Corruption, maybe_expand from mattergen.diffusion.d3pm import d3pm from mattergen.diffusion.da...
77a80fa880e84f87d563842012f96fc0dd4fb184e952e5882eb530801bb8da86
Python
4,297
104
from ... import options as opts from ... import types from ...charts.chart import RectChart from ...globals import ChartType class EffectScatter(RectChart): """ <<< Scatter plots with ripple effects animation >>> Use animation effects to visually highlight designated data set. """ d...
4a81402030bc3e0bed8826a8be0f272fdf21584413746a5bc30ffbeaf1a65e4d
Python
4,298
109
from mdt import CompartmentTemplate __author__ = 'Robbert Harms' __date__ = '2018-09-07' __maintainer__ = 'Robbert Harms' __email__ = 'robbert@xkls.nl' __licence__ = 'LGPL v3' class NODDI_EC(CompartmentTemplate): """The Extra-Cellular compartment of the NODDI-Watson model. This is the compartment as describ...
38905accb70c7252c6b58d2c534010f24cd7d8051b124fbb9f66261926d1d3ac
Python
4,300
134
"""functions to plot learning curve results""" import os import pickle from configparser import ConfigParser from glob import glob import joblib import matplotlib.pyplot as plt import numpy as np def get_all_results_list(root, these_dirs_branch, config_file): these_dirs = [ (root + this_dir[0], this_dir...
9a1991400baada972ddb45254a976ba0f397ff44fdf12b1fff56e46fca806424
Python
4,302
101
# Copyright (C) 2025 ETH Zurich, Moritz Thürlemann, and other AMP contributors import json import os import numpy as np import yaml from pathlib import Path def write_qm_mm_json(path:str): parameters = {} parameters["qm_zone_resnames"] = ["UNL"] parameters["mm_zone_resnames"] = ["HOH"] with open(pat...
370d716eab767ffede840dee81defcea790392616d9d2675daa7a7e4a6c3d1ea
Python
4,303
134
#!/usr/bin/env python import urllib.request from urllib.parse import urlparse import os import anndata import argparse import shutil import pandas as pd import scipy import json import tempfile # 6 available but only 2 contain region label and coordinates LINKS = [ "https://ftp.cngb.org/pub/SciRAID/stomics/STDS000005...
4b6233477794def048e56104ecabed706b849425f60fee7ae1abb64c59770361
Python
4,306
132
# # 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 .idac import IDAC from simulator.backend import ComputeBackend xp = ComputeBackend() # Repr...
b7e8aa49cb1c3e1e424d769987fc3471fb21f2e06af546d985f44ae12facdc91
Python
4,306
124
import numpy as np import pandas as pd from scipy import stats from scipy import special ## Confidence interval estimation using boostrapping ## Confidence interval estimation using boostrapping def get_bootstrap_sample(X_df, y_df, n_splits=2): """ Returns a stratified bootstrap sample of X and y, prese...
3eec8b026ac7f979d0a52f7a63c6ac5f0c3b52182f9057a13bfd1079d0634ddd
Python
4,310
151
"""Dataset and nucleotide-array utilities shared by model families.""" from __future__ import annotations from typing import Any import numpy as np import pandas as pd from datasets import Dataset, load_dataset from jaxtyping import UInt8 def load_table(path: str) -> pd.DataFrame: """Read one supported genomic...
ca43119ca604b8f14f7d7b6ccd7db60d11a9ecc55880b3d823480804228cdf1b
Python
4,312
114
#!/usr/bin/env python from pgmpy.structure_score import BaseStructureScore from pgmpy.utils._warnings import _warn_external class ScoreCache(BaseStructureScore): """ A wrapper class for StructureScore instances, which implement a decomposable score, that caches local scores. Based on the global decom...
67ea16563b41849771b72a54cf973d09d7b8d4c5c470f43e21f801c7c24ae94e
Python
4,314
139
# 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 import numpy as np from fairseq.data import BaseWrapperDataset, plasma_utils logger = logging.getLogger(__name__) class Re...
62295504aa981c2dc54a5e571e0f0a4cf21726b586018d28094174efb1186f97
Python
4,317
126
#!/usr/bin/env python3 """ Basic FASTQ quality control for Nanopore long-read cDNA-seq data. This script reads gzipped FASTQ files, calculates read lengths and mean per-read Phred quality scores, and generates histogram plots for each metric. Edit FASTQ_FILES and OUTPUT_DIR below, or adapt the script to use command-l...
62864be0ed4ae182a7490a5259f9247150a50eb9d4e8a59d4e94dea44cdcfd4b
Python
4,317
101
"""Manages GO Term fill colors and bordercolors.""" __copyright__ = "Copyright (C) 2016-2018, DV Klopfenstein, H Tang, All rights reserved." __author__ = "DV Klopfenstein" import collections as cx from goatools.gosubdag.utils import get_kwargs class Go2Color(object): """Manages GO Term fill colors and bordercol...
a38c91dcb4c5f1367d7d1ed57fa3c8f55a03a7fc2c02aad5e8f4a79cb42e406c
Python
4,318
116
""" Compute the percentage of fusion transcripts whose splice junctions are all supported by short-read RNA-seq, and plot as a pie chart. """ import sys from pathlib import Path import polars as pl from ryp import r, to_r sys.path.insert(0, "bin") from src.utils import read_gtf, read_SJ # ── Paths ─────────────────...
2905047c80171117084b0e0ccd112a5d49abc4b31675473e7a3c44dc7e973a76
Python
4,319
99
""" This package contains all of the functions for gmx_MMPBSA that it needs to run smoothly. """ # ############################################################################## # GPLv3 LICENSE INFO # # ...
d9f2b1cb975e50c607afec5e431a449be60f4b7e412a47c532f688784de9fc51
Python
4,319
154
#!/usr/bin/env python3 import argparse from typing import Any, Callable import yaml from symmnet.datasets import cifar10, fmnist, mnist, svhn # noqa # Hardcoded defaults DEFAULT_PARAMS = { "params": { "n_epochs": 100, "batch_size": 64, "lr": 0.01, "momentum": 0.9, "weigh...
1d318fd3b19b6fb00e37c4755d1538b3a0648c0c986485c05b7bdc1b17400502
Python
4,321
118
""" Original work by ProGamerGov at https://github.com/ProGamerGov/neural-dream/blob/master/neural_dream/helper_layers.py The MIT License (MIT) Copyright (c) 2020 ProGamerGov Copyright (c) 2015 Justin Johnson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associate...
7f0175ae17d3bdc6c0d0e8d27da532690275be0009fd7210d79fe0039b0f416c
Python
4,321
107
import numpy as np import matplotlib.pyplot as plt from pathlib import Path # Define paths base_dir = Path('/egor2/egor/MovieProject2') retinotopy_dir = 'retinotopy' fd_file_pattern = 'motion_{subject_id}_enorm.1D' plots_dir = base_dir / "bids_data/derivatives/group_analysis" plots_dir.mkdir(parents=True, exist_ok=T...
cf44b0e745f2b7e110191375d1d1c2129bca973b77e9a00eb7dd0c8d284bc69d
Python
4,325
97
import numpy import numpy.testing import unittest from . import SampleData from metax import PredictionModel from metax import MatrixManager D = MatrixManager.GENE_SNP_COVARIANCE_DEFINITION from metax.metaxcan import Utilities from metax.metaxcan import AssociationCalculation def _gwas(): gwas = SampleData.dataf...
841965602b0bbe87140c8cd5b27afdccc531f2f851775f200ba49d2250b6a68f
Python
4,326
139
# 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 Callable, Optional import torch import torch.nn as nn from fairseq import utils from fairseq.modules import LayerNorm, Mul...
89a46934b78c5ad32af3855c0c3a8e0cff95f78259807ea2f9640c7ffbf34ce5
Python
4,326
132
from __future__ import annotations from typing import TYPE_CHECKING import pytest from poetry.factory import Factory from tests.mixology.helpers import add_to_repo from tests.mixology.helpers import check_solver_result if TYPE_CHECKING: from poetry.core.packages.project_package import ProjectPackage from ...
dbc74c2aed4dedfccb4078ce31674f0217e67bd4d688cb8c4693f4b18d59db2a
Python
4,326
126
import pytest from rnalysis import __attr_file_key__, __biotype_file_key__ from rnalysis.utils.settings import * @pytest.fixture def use_temp_settings_file(request): make_temp_copy_of_settings_file() request.addfinalizer(remove_temp_copy_of_settings_file) request.addfinalizer(set_temp_copy_of_settings_fi...
f5cb83c63b1be8be6f7b901d89b664aa845efbc6bb6e60166654ac8b6307cd12
Python
4,326
108
"""Regenerate datasets_hippie/toy/ from a fixed seed. The toy dataset is 20 synthetic neurons (10 fake-PV / 10 fake-SOM) used as a smoke-test fixture for the loader, the inference API, and the release test suite. It is committed to the repo so that a fresh clone can run examples/extract_embeddings.py with no external ...
20de6110ed70af360fb3bfedd3d3e9b2be1a1bab667d01733968924bc18fdb41
Python
4,328
86
import cv2 as cv import numpy as np import os for t in range(25): targetserial_path = self.filepath + '/Averaged_result%d' % (t + 1) ##获取当前需要进行加窗处理的serial(完成了组内叠加平均)的路径 imgNumber = len(os.listdir(targetserial_path)) ##电刺激下图像数量就是选择的路径下的数量 windowNumber = int(imgNumber / self.windowimgNumber) # 10张图...
6eff1b425333513acb95e2e90b5468bcd301f3a70f2f9232e7f3937c46f6a06b
Python
4,329
157
#!/usr/bin/env python3 """Sweep launcher for pure SAL symmetrization experiments (salnet_symm.py). Iterates over learning rates × seeds. Each combination is stored in a structured directory tree that plot_puresymm.ipynb can read directly. Sequential run (default): python sweep_symm.py Parallel run with 4 workers...
1cd312da284f59f8f38a9bd4e078982d6671794d15e1b2b2eefdb3f86e97d3a0
Python
4,330
118
import os import unittest from io import BytesIO from unittest.mock import patch from pyecharts.charts import Bar from pyecharts.render import make_snapshot from pyecharts.render.snapshot import ( save_as, save_as_png, save_as_text, decode_base64, ) def _gen_faker_engine(content: str):...
cb8070d73d1c9849877c07f9e450470c4bdf497c4f7e9e93ff7a31bce0d994fc
Python
4,331
114
"""QM/MM diagnostics extracted from SANDER output.""" from dataclasses import dataclass import re @dataclass(frozen=True) class QMMMDiagnostic: """A diagnostic extracted from a SANDER QM/MM output file.""" code: str severity: str message: str remediation: str def parse_qmmm_diagnostics(output_...
dc6b0c40445f1cab07c31f4f11f627df3b32e577873b03a4ce80eedf614df7de
Python
4,332
143
# 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 collections import OrderedDict import numpy as np from fairseq.data import BaseWrapperDataset, FairseqDataset, iterators class MultiI...
acdf505c6209e0932c1ffa3522c8ff2791e90957e5f996fd533fe9e734ab9da5
Python
4,333
118
import json import os import urllib.request import matplotlib.pyplot as plt import matplotlib.font_manager as font_manager from matplotlib.backends.backend_pdf import PdfPages urllib.request.urlretrieve( 'https://github.com/google/fonts/raw/main/ofl/ibmplexmono/IBMPlexMono-Regular.ttf', 'IBMPlexMono-Regular.t...
599900acde10d434e5c683bfdd4e9dd8355f8d028c491ca09e8d6ddfb2e57070
Python
4,335
109
import cv2 import cmapy from PIL import Image import numpy as np from msi_visual.utils import normalize_image_grayscale, image_histogram_equalization from msi_visual.normalization import spatial_total_ion_count def get_pr(normalized, high=99.9, low=99): novel = np.percentile(normalized, high, axis=-1) / ...
bec36a27c2d015dda93fb290c884eca69fc838301d958a72ffc94d646ad4ae49
Python
4,335
139
from __future__ import annotations from contextlib import suppress from functools import cached_property from typing import TYPE_CHECKING from typing import Any import requests.adapters from poetry.core.packages.package import Package from poetry.inspection.info import PackageInfo from poetry.repositories.exception...
0c295584f72691866daa2df4b9d23d34251a53927df4eee5869c5fe38b0aec76
Python
4,337
107
#!/usr/bin/env python3 """Build Methylation_Data/meth_sex.csv, the per-sample sex table sex_adjusted_sensitivity.R reads. WHY THIS EXISTS. sex_adjusted_sensitivity.R (Reviewer 3) fits the AllMeth MS-vs-HC model with and without a sex term on the samples for which sex is known, and reads that sex from meth_sex.csv. No ...
9fcd3ea63833376e76eb29375eade2c4ff165780d75a0febb083a85a826253c3
Python
4,337
131
import numpy as np import torch from typing import List, Tuple from stripedhyena.model import StripedHyena from .tokenizer import CharLevelTokenizer def prepare_batch( seqs: List[str], tokenizer: CharLevelTokenizer, prepend_bos: bool = True, device: str = 'cuda:0' ) -> Tuple[torch.Tensor, List[int]]:...
7ddb32eedd8632a7b65c3ac22f2593e749e08fb5b567bb2c456246880ee3f892
Python
4,341
147
# -*- coding: utf-8 -*- """ Created on Tue Jul 30 16:15:31 2019 @author: 俊男 """ # In[] Naive Bayesian Classifier default with Gaussian Kernal from sklearn.naive_bayes import BernoulliNB, MultinomialNB, GaussianNB import pandas as pd class NaiveBayesClassifier: __classifier = None __y_columns = None def _...
4b9a7d2c9b991a10edfc5119a1dbd6cca91f30223fd97cb384bf741c0fae6077
Python
4,342
145
"""Transfer matrix for the two neuron buesing model Defines a class with generators for the creation of the transfer matrix T. The T can cope with every kind of PSP shapes. """ from typing import Callable, Iterator import numpy as np def sigma(u: float, tau: float) -> float: return 1 / (1 + tau * np.exp(-u)) ...
66144a191ff17112faad9df6dcfe40912cb97bf1115bb7072b9e990721ca88e0
Python
4,342
164
import os import re import numpy import logging import h5py try: import h5py_cache except: logging.info("Couldn't import h5py_cache. Anyway, this dependency should be removed. It has been folded into h5py") from . import Expression as _Expression from ..misc import Math ######################################...
2bf127a782e6d6ea6059ddb043a7626f14aa967e441b3e84feb23bbfdde044b7
Python
4,348
133
# 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...
1288830de8c694dc15229c2c4bd7d050fb4fa9333951a2f67fa7c6bbdc1accd4
Python
4,352
136
# -*- coding:utf-8 -*- """ Copy of the module scilpy.io.utils.py. """ import numpy as np import os def get_sh_order_and_fullness(ncoeffs): """ Get the order of the SH basis from the number of SH coefficients as well as a boolean indicating if the basis is full. """ # the two curves (sym and full) ...
e38595893b491c3455e0453fa244f25036060d685dc3c92424727c6e51bb318c
Python
4,353
133
import numpy as np import pytest import torch from neurovfm.data.cache import CacheManager from neurovfm.datasets import ImageDataset, StudyAwareBatchSampler from neurovfm.data.metadata import DatasetMetadata class _DummyImage: """ Simple stand-in for a SimpleITK image providing only GetSpacing(). """ def __init...
f78b6a4936e038f781478dadcf32a0a6e09fae5a37c3efad311b885b1d5d94e4
Python
4,355
113
# import from plugins/cluster_metrics.py """Show how to add a custom cluster metrics.""" import numpy as np from phy import IPlugin from scipy.optimize import curve_fit from scipy.special import ndtr class qMetricsPlugin(IPlugin): def attach_to_controller(self, controller): """Note that this function is ...
50b3680efe600bf2421f54a13f284c0a7543fc186f450b4291474e965d7c2e8c
Python
4,356
102
import networkx as nx import pandas as pd def create_directed_graph(iax: pd.DataFrame, tp: int) -> nx.DiGraph: """ Creates a directed graph based on the axial current value (iax) at a specified time point (tp). Parameters: iax (df): A pandas DataFrame with axial current data. It must include a co...
180db8afeec7c5423b45b7689cd7f741114e6d2e8320d870b9b909a099db4a7d
Python
4,359
96
#!/usr/bin/env python3 """Canal de HIBRIDAÇÃO para o OCE: repulsão de nível s(B)–p(X) em 2ª ordem. MOTIVO, medido. O diagnóstico de 28/07 mostrou que o `wave15` erra de forma sistemática nos IODETOS: resíduo mediano +0,077 eV e |res| 2,4× maior que nos demais haletos. E o mecanismo foi nomeado: descendo a série do hal...
54d5efc7b8187fa23e5506425268a6a69fca4c431dba61a0d6d2856027a019d1
Python
4,359
94
import torch.nn as nn import torch import torch.nn.functional as F import config.cfg_lodet as cfg class Ordinary_Head(nn.Module): def __init__(self, nC, anchors, stride): super(Ordinary_Head, self).__init__() self.__anchors = anchors self.__nA = len(anchors) self.__nC = nC#类别 ...
bec004f80ef95b4caedf591931fb69b6170bd66efc8332cf18695a4be42be221
Python
4,363
85
import os import numpy as np import subprocess from subprocess import Popen import pandas as pd from meld_classifier.tools_commands_prints import get_m from meld_classifier.paths import FS_SUBJECTS_PATH #Function for sampling per patient, at various intracortical/subcortical depth def sample_T1_features(subject_id, v...
781e74140f51bd35a2351e3c18dd12a2b9ad43190a240e7f35e1d85b32f87754
Python
4,364
111
import ast import inspect from textwrap import indent, dedent __author__ = 'Robbert Harms' __date__ = '2017-07-24' __maintainer__ = 'Robbert Harms' __email__ = 'robbert@xkls.nl' __licence__ = 'LGPL v3' class TemplateModifier: def __init__(self, template): """Given a template instance, this class can upd...
91782ef3921f3cb5de8f1f9d5bc26f6ebb1a64234c14f84dfd09612b8e904e66
Python
4,364
140
from pathlib import Path import torch from torchvision.models import resnet152, ResNet152_Weights from torchvision.models import resnet101, ResNet101_Weights from torchvision.models import resnet18, ResNet18_Weights from torchvision.models import resnet34, ResNet34_Weights from torchvision.models import resnet50, ResN...
294b845487d7d10e035c8433875aab311fc41af7fd6d5d891f98636d0895b772
Python
4,366
80
#!/usr/bin/env python3 """R1 ponto 3: refaz a Fig. 1(a) com MAE e R^2 ao lado do RMSE. Copia fiel de `fig_manuscrito.py` no que produz os pontos -- mesmo GroupKFold, mesma grade de alpha, mesma normalizacao -- para que a figura nao mude de valor, so de anotacao. As tres medidas sao a MEDIA SOBRE AS DOBRAS, que e a con...
6c85167bfe3bc153f50f97077994972221c5d4758fe7be031b06b03f2aab2b06
Python
4,368
104
"""Propagate counts for associations""" __copyright__ = "Copyright (C) 2016-2019, DV Klopfenstein, H Tang, All rights reserved." __author__ = "DV Klopfenstein" import sys from collections import defaultdict from goatools.gosubdag.go_tasks import get_go2parents_go2obj from goatools.anno.broad_gos import NS2GOS_SHORT f...
77a7afc7bdc29dd9fe6df3d943adeba0639e2231a506bcb4bac8b0f61a362fae
Python
4,368
105
import json import os import unittest import zipfile from contextlib import contextmanager from pathlib import Path from tempfile import TemporaryDirectory from types import SimpleNamespace from unittest.mock import patch from GMXMMPBSA.commandlineparser import parser from GMXMMPBSA.error_bundle import create_error_bu...
17ca8294cecf32e87fa80ab5e91025af1328600437324644395b6ada6f5f5d72
Python
4,369
142
from __future__ import annotations from typing import TYPE_CHECKING from typing import ClassVar from cleo.helpers import argument from cleo.helpers import option from poetry.core.constraints.version import parse_constraint from poetry.core.version.exceptions import InvalidVersionError from poetry.config.config impor...
319b3da2ef15ccae95162b1b4f4a9a0b0da63fa0062a7f6006a06dd567258d85
Python
4,369
148
# From: gluonts/src/gluonts/time_feature/_base.py # Copyright 2018 Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at # # http://www.apac...
090c8a148437b765f446df7971c5dba42fa20a2396f00df156b2fb8c56ea0be4
Python
4,370
139
import pickle import numpy as np import pdb from celltype_ibl.params.config import ULTRA_DATA_PATH, STIM_REMOVED_DATA_PATH def get_ultra_wvf_acg_pairs( data_path: str = ULTRA_DATA_PATH, return_optotagged: bool = True, return_half: bool = True, return_radius: bool = False, load_new: bool = False, )...
4b08568b9cfb53029791c64195b727437848d299a6a9b82a34d9325650da753b
Python
4,371
120
#!/usr/bin/env python3 # Florian Bénitière 16/03/2025 # Script to find unique short variants (SNVs and Indels) from a large .parquet file and produce VCF files per chromosome for use by VEP import os import sys import pandas as pd import subprocess from pyspark.sql import SparkSession from pyspark.sql import function...
9a7060c31630cf68b4d92817eb0f63196174695118eeb11287fa10e9cdb6415e
Python
4,372
130
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import re from functools import cached_property from pymatgen.analysis.structure_analyzer import oxide_type from pymatgen.core import Structure from pymatgen.entries.compatibility import Compatibility from pymatgen.entries.computed_entries impor...
faa59805cc400c621527cba36767e9d4a9dfea5aa58e55a4492bb19e1b61239c
Python
4,372
133
#!/usr/bin/env python # ENCODE DCC fingerprint/JSD plot wrapper # Author: Jin Lee (leepc12@gmail.com) import sys import os import argparse from encode_lib_common import ( log, ls_l, mkdir_p, rm_f, run_shell_cmd, strip_ext_bam) from encode_lib_genomic import ( samtools_index) from encode_lib_blacklist_filter ...
4f3c308c89fd4306ade09c39ee701bfcf77d2524b4115a0217ecb98bb2f2853b
Python
4,373
133
from pathlib import Path import joblib from baseModels.transforms import load_transforms from baseModels.models import * class WrappedModel(torch.nn.Module): def __init__(self, module): super(WrappedModel, self).__init__() self.module = module # that I actually define. def forward(self, x): return self.module...
2479fc066d78196c6da62d6deaa1e99a1afbfaa4f29202cd4635deb3f1ecb4ba
Python
4,374
128
# 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 torch.optim import Adagrad from fairseq.optim import LegacyFairseqOptimizer, register_optimizer @register_optimizer("adagrad_with_grad...
7f20cd7483e55b4634655711fd5f195977b8cff6ddb0d2f7ad0f917252ca2357
Python
4,377
130
import argparse import os import textwrap import argcomplete import sys import mdt __author__ = 'Robbert Harms' __date__ = "2015-10-16" __maintainer__ = "Robbert Harms" __email__ = "robbert@xkls.nl" def get_argparse_extension_checker(choices, dir_allowed=False): """Get an :class:`argparge.Action` class that can...
354feed7be590a66d3548172e751233e8a5d6e215061dddd6b1824fa18010dc6
Python
4,378
121
# 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.models import register_model, register_model_architecture from fairseq.models.nat import NATransformerModel, base_architecture f...
359e6dbc1296e046fbfc385a696c900373569e941f0ec4fd1606d39e2297b23c
Python
4,378
134
import pandas as pd import pytest from pgmpy.base import DAG, PDAG from pgmpy.metrics import AdjacencyConfusionMatrix # The models in true_dag and est_dag fixtures are taken from the paper: https://arxiv.org/pdf/2412.10039 @pytest.fixture def true_dag(): return DAG( [ ("x1", "x2"), ...
dbd826f594fda0c46aa8c97a14d9ab75cbde8e333f4331ad34decc534ece9624
Python
4,378
120
import matplotlib.pyplot as plt import numpy as np import loompy from .colors import colorize from cytograph.enrichment import FeatureSelectionByVariance from cytograph.embedding import art_of_tsne from sklearn.decomposition import PCA from sklearn.manifold import TSNE def all_QC_plots(ds: loompy.LoomConnection = Non...
dff1ea84d45683dfdc2af97b25e8f9d4cd184ac618ced71635ffe3faab03425d
Python
4,381
112
# -*- coding: utf-8 -*- """ @Time:Created on 2019/4/30 14:19 @author: LiFan Chen @Filename: mol_featurizer.py @Software: PyCharm """ import numpy as np from rdkit import Chem from rdkit.Chem import Descriptors num_atom_feat = 34 def one_of_k_encoding(x, allowable_set): if x not in allowable_set: raise Exce...
998912e9149917dd847ca26d27ce3349ab2387daac5a95c8fc62f8d711ba6733
Python
4,382
81
#!/usr/bin/env python3 """Normalisation-based pseudobulk aggregation, as a sensitivity comparison against the summed-raw-count (muscat standard) aggregation. The deposited Kaufmann matrix is log-normalised: lognorm = log1p(count / total * 1e4). Therefore expm1(lognorm) = count/total*1e4 = the cell's CP10K (counts per ...
80bf630c88a1c84992c1c1d0b8c4aa7646daf76b79f9c052108478d45236cd17
Python
4,384
175
from typing import Optional import haiku as hk import jax import jax.numpy as jnp class ConvBlock(hk.Module): """ Conv Block. """ def __init__( self, dim: int, dim_out: Optional[int] = None, kernel_size: int = 1, layer_norm_axis: int = -1, name: Option...
4b0626b59c6770c49349f294cf0447f6a5f317d5cb10ecc0a0c153ca0a15cab1
Python
4,385
134
# 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 collections import os import shutil import tempfile import unittest import numpy as np import torch from scripts.average_checkpoints i...
4bc70dc68e32550416ddafc034ff003e86105afbfd28c55f9d6b5c20b95b1b6c
Python
4,386
119
"""Fit OCE coefficients J_F by linear regression on xtb training energies.""" from __future__ import annotations import json from dataclasses import dataclass from pathlib import Path import numpy as np from sklearn.linear_model import Ridge, LinearRegression from oce.atomic_table import load_table from oce.correlat...
68e661248ccfa37d1c9d8c37ff40b770c4c78967e798aabd5c5659fbd703c182
Python
4,386
82
import argparse from typing import Union from batchgenerators.utilities.file_and_folder_operations import join, isdir, isfile, load_json, save_json from nnunetv2.imageio.reader_writer_registry import determine_reader_writer_from_dataset_json from nnunetv2.paths import nnUNet_preprocessed, nnUNet_raw from nnunetv2.uti...
d54916f495ec17fb292a036dc4961e4b6886714b03d088c9a0e1c2a7c3cb4fdc
Python
4,386
112
# -*- coding: utf-8 -*- """ @Time:Created on 2019/4/30 14:19 @author: LiFan Chen @Filename: mol_featurizer.py @Software: PyCharm """ import numpy as np from rdkit import Chem from rdkit.Chem import Descriptors num_atom_feat = 34 def one_of_k_encoding(x, allowable_set): if x not in allowable_set: raise Exce...
e823fc24ab9b943399baa98a966557186efa36e7332b6acaf98f3dd3f2dd9d24
Python
4,390
148
import numpy as np from scipy.special import hyp2f1, gammaln def get_r2(iv, dv, stack_intercept=True): """ Regress dv onto iv and return r-squared. Parameters ---------- iv : numpy array Array of shape N (samples) x K (features) dv : numpy array Array of shape N (samples) x 1 ...
6e078a70da990321a4c826d7f47920ca373ac0d599910a0fe34b137c39c6705b
Python
4,396
159
# build_pairs_c1_by_task_session.py # Build time-shifted pairs per (task, session) for C1 from extracted ROI timeseries. # Outputs one NPZ per system: ses<id>_<task>_pairs.npz with 90/10 split. # # Works with filenames like: # sub-01__ses-1-func-wrsub-01_ses-1_task-encoding_run-1_bold__timeseries.npy import o...
d69d2d57d9eb95830658d07fbbf580a850e6a1fc7d0f583f1bc729dac0b34c26
Python
4,396
120
#!/usr/bin/env python3 """ @file test_blackbox.py @author Simon Yu @date 02/12/2024 @brief Script for testing blackbox models. """ import argparse import dataset import header import logger import model import torch import tqdm import utility import wandb def initializeRunName(run_name = ""): if run_name !=...
c00e239c16b363b3023139090428e2b82333cc809111f3bce17f9a5a841db53c
Python
4,397
112
"""Property-based tests for the embeddings-store codec. `test_embeddings_store.py` pins the round trip at a handful of hand-picked tensors. What the codec actually promises is a property over any token/feature matrix — shape preserved exactly, values surviving up to bf16's rounding — so this generates the shapes and v...
4f8162080c39a276a677992c3dee32d855af2ebf80b7fdca058cbc59a3f36e73
Python
4,400
122
import nibabel as nib import matplotlib.pyplot as plt import numpy as np from nilearn.image import resample_to_img import matplotlib as mpl # === Paths === isc_group = "/egor2/egor/MovieProject2/bids_data/derivatives/group_analysis/backtothefuture/isc/ISC_group.nii.gz" anat_template = "/egor2/egor/MovieProject2/bids_d...
60c95a84ce642d227e7a31d17e45fd55b7755e0a04b137ace640506b2a937408
Python
4,401
125
#!/usr/bin/env python # coding: utf-8 # # This file is part of multiQC software. Using a metadata file, it writes part of the multiQC config file # # Copyright (c) 2018 - Institut Curie # # File author(s): # Dimitri Desvillechabrol <dimitri.desvillechabrol@curie.fr>, # Nicolas Servant <nicolas.servant@curi...
14d0d3c85e308312f0e9b7266b26a7506e94e2269fd1337342f5beb1dc61f064
Python
4,403
117
import unittest import numpy as np from numpy import cos, exp, sin from numpy.testing import assert_allclose import mdt from mot.configuration import CLRuntimeInfo from mot.lib.kernel_data import Array class test_SSFP(unittest.TestCase): def __init__(self, *args, **kwargs): super().__init__(*args, **kwar...
a2af253168ddfa8b39fe0a02910d0ac8e25dce0aa2f754d3a7447eb28ec01290
Python
4,403
129
import faiss import numpy as np import pandas as pd import os import yaml import glob import torch from easydict import EasyDict from utils.constants import sequence_level from utils.file_reader import FileReader from utils.faiss_index import FaissIndex from model.ProTrek.protrek_trimodal_model import ProTrekTrimodalM...
5ac1ecbd2769260b051c3d41838d682350084ea4c2c5e10d0c2270c835e53826
Python
4,404
120
#!/usr/bin/env python3 # Florian Bénitière 16/03/2025 # Script to find unique short variants (SNVs and Indels) from a large .parquet file and produce VCF files per chromosome for use by VEP import os import sys import pandas as pd import subprocess from pyspark.sql import SparkSession from pyspark.sql import function...
288fb188ed6a910c3484b926ca6107760149bfa3f908dd53f482868bfe913bb1
Python
4,405
110
#!/usr/bin/env python3 # Florian Bénitière 16/03/2025 # Script to generate a .parquet file by merging all TSV gVCF files from a directory import os import shutil import sys import pandas as pd import subprocess import psutil # System and process utilities from math import floor # For rounding down numbers from col...
36b0b41d90b7b642b6e4c425b5e1647ff1d5fb0301be026d545026f6af8881c9
Python
4,405
142
""" Decorators for handling errors, debugging, timing, and convergence warnings. """ import functools import time import traceback import warnings from functools import wraps import click from dask.distributed import Client, LocalCluster from sklearn.exceptions import ConvergenceWarning from rich.console import Cons...
1348e21c9abceeb1b67cf22f4f8b3d5dcb6ea0638902ab8900da887cd2fb8e3d
Python
4,408
155
#!/usr/bin/env python # Author_and_contribution: Niklas Mueller-Boetticher; created template # Author_and_contribution: ENTER YOUR NAME AND CONTRIBUTION HERE import argparse # TODO adjust description parser = argparse.ArgumentParser(description="Method ...") parser.add_argument( "-c", "--coordinates", help="Pat...
022fa10bf5951a48ace92e7b011f5d7e31cf15ce06fd94acf4f7fe073e13c955
Python
4,409
143
from __future__ import annotations import pytest from poetry.config.config_source import PropertyNotFoundError from poetry.config.dict_config_source import DictConfigSource def test_dict_config_source_add_property() -> None: config_source = DictConfigSource() assert config_source._config == {} config_s...
272c50413725076826824192ebbc8c80e89d15ffd68e3841dc68d4ba84c1109b
Python
4,410
133
__author__ = 'Robbert Harms' __date__ = "2015-03-26" __license__ = "LGPL v3" __maintainer__ = "Robbert Harms" __email__ = "robbert@xkls.nl" class Tree: def __init__(self, data=None, tag=None, children=None, parent=None): """Create a new Tree. In this tree, every node is a tree object as well. T...
fea10f7713bd30128fa01c3fccd3854ff58a697dbe22e444d139a891348d03ee
Python
4,415
90
import numpy as np from . import io_mesh as io import subprocess import argparse import os import copy def calculate_area(surfname, fwhm, software="CIVET", subject="fsid", surf="pial", hemi="lh"): """Calculate and smooth surface area using CIVET or freesurfer.""" tmpdir = '/tmp/' + str(np.random.randint(1000))...
6219c0ade4476866a100c868ce4907f201b0f25e5a3ded16c42bf8b79ad2966f
Python
4,416
114
"""`brenda_references/tests/` must be collected by CI, from its own job. The root `testpaths` points only at the top-level `tests/` and the subpackage had no `.github/` of its own, so nothing in CI ever collected its suite. It is not folded into the root job: `brenda_references` is its own pdm project with its own git...
e413cbff10f68ad54ddc5c1c56d7f8615b462fa19d159b5406aacd672d982d1a
Python
4,417
128
import pandas import os import io import logging import re import gzip from numpy import dot, transpose, cov from .. import MatrixManager from .. import Utilities from . import Math from .. import Exceptions K_GENE_MODEL_HEADER=["gene", "model1", "model2", "value"] class FeatureMatrixManager(object): def __init_...
2b39ce365f13773dac6d0f1f41856f5da2c489cacb0e03d7ecd3efc53e50a560
Python
4,418
100
from typing import Callable import torch def train_pcoders(net: torch.nn.Module, optimizer: torch.optim.Optimizer, loss_function: Callable, epoch: int, train_loader: torch.utils.data.DataLoader, device: str, writer: torch.utils.tensorboard.SummaryWriter=None): r""" Trains the feedback modules of PCoders using ...
567a651ad3b4aa143ac24b030fe403141bc7d09cf4c39a408d6ac318fc3d44c2
Python
4,418
111
import polars as pl from src.utils import read_gtf # Read in datasets classification = pl.read_parquet("nextflow_results/V47/final_classification.parquet") reftss = pl.read_csv("data/liftovered_mm39_to_hg38_peaks_overlapped_reftss_hg38_500bp.bed", separator="\t", has_header = False, new_columns=["chrom", "start", "end...
b82aec235796a4060e93d6e21b43ba8239f8779d3744567d9d845c954473fdef
Python
4,418
118
import os # import logging import json import torch.nn as nn from transformers import HfArgumentParser, set_seed from transformers import BertTokenizer, AutoTokenizer, logging from transformers.trainer_pt_utils import get_parameter_names from src.models import KeAP, KeAPConfig, KnowledgeDecoder from src.trainer import...
d82c52d6322fa374dcb2db1861826c2f84a491614bd56ec2b565d4f018e4dc75
Python
4,421
126
#!/usr/bin/env python # -*- coding: utf-8 -*- import re import glob from textwrap import dedent import os import sys from setuptools import setup, find_packages, Command def load_requirements(fname): is_comment = re.compile('^\s*(#|--).*').match with open(fname) as fo: return [line.strip() for line i...
656f89c69704eea3557f8340e653aa4df1c99bb23a38aae7d7f99cb2e7b78a0b
Python
4,424
135
"""Utility functions to help setup the model, optimizer, distributed compute, etc. """ import typing import logging from pathlib import Path import sys import torch import torch.distributed as dist from torch.utils.data import DataLoader, RandomSampler, Dataset from torch.utils.data.distributed import DistributedSampl...
9a36d7e083015ff9ea5ac264b10d56cd967d8c7977c86d84406968133c7bf98a
Python
4,424
134
from __future__ import annotations from typing import TYPE_CHECKING import pytest from poetry.console.commands.version import VersionCommand if TYPE_CHECKING: from cleo.testers.command_tester import CommandTester from poetry.poetry import Poetry from tests.types import CommandTesterFactory from te...
b946343eb1f720404e6aa990321861c1ef31905a20c58e42ab4643d038210c92
Python
4,424
107
import torch import torch.nn as nn import torch.nn.functional as F from ..layers.conv_module import Convolutional class Upsample(nn.Module): def __init__(self, scale_factor=1, mode='nearest'): super(Upsample, self).__init__() self.scale_factor = scale_factor self.mode = mode ...
0906c51bc3265bc5a06845f707ea3d3ff4b6ab38393b40536b94a2458773feca
Python
4,426
145
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...