sha256
stringlengths
64
64
language
stringclasses
27 values
size
int32
1
491k
lines
int32
1
21.8k
content
stringlengths
1
200k
5717edd94574f6f68792432d10905d9548b8f58cbab66ac1a3af82dd027c08df
Python
3,739
101
import os import matplotlib.pyplot as plt import scanpy as sc import deepstkit as dt import pandas as pd from sklearn import metrics # ========== Configuration ========== SEED = 9 # Random seed for reproducibility DATA_DIR = "/DATA1/Roxana/GraphST-main/Data/1.DLPFC" # Directory containing spatial d...
105f57f47808a67c577d03a3d2a1be5a0fd85f36d6765ed9673568bc49769dcf
Python
3,742
70
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_amos_task1(amos_base_dir: str, nnunet_dataset_id: int = 218): """ AMOS doesn't say anything abo...
1beb11894e4639d728e97f60b405c9e2a2355b012ebc9dbc9ac7e6e85cff5fe8
Python
3,742
100
# 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 .how2processor import ( ShardedHow2MetaProcessor, ShardedVideoProcessor, ShardedTextProcessor, VariedLenAligner, Over...
8f64718df87c52599057b4e61b12564e8f7c8eafd65132c51fbac3493d471bb0
Python
3,742
104
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import sys from os.path import join from os.path import expanduser def get_config_name(input_type, output_type, dropout_sampling=False, tract_definition="TractQuerier+"): if tract_definition ==...
d7df37d8adecac0b6bae43a38e5ca36c587c8ade7a06fe549a86932b3ca87ff2
Python
3,742
106
import unittest from scipy.special import jnp_zeros import numpy as np from numpy.testing import assert_allclose import mdt from mot.configuration import CLRuntimeInfo from mot.lib.kernel_data import Array class test_VanGelderenCylindricalRestrictedSignal(unittest.TestCase): def __init__(self, *args, **kwargs): ...
f0ae1c63d1683a1238861bff82359a4244f3d7e11b242cd787f5578027359a01
Python
3,742
107
from torch.utils.data import DataLoader import torch import lightning.pytorch as pl from typing import Union, Optional from pathlib import Path from rinalmo.data.alphabet import Alphabet from rinalmo.data.constants import * from rinalmo.data.downstream.expression_level.dataset import ExpressionLevelDataset from rina...
9571addfb346b7c6c2d852964d1825fd66564269863f3e10a331657e71e036c0
Python
3,743
105
import numpy as np import torch from fairseq.data.audio import rand_uniform from fairseq.data.audio.dataset_transforms import ( AudioDatasetTransform, register_audio_dataset_transform, ) from fairseq.data.audio.waveform_transforms.noiseaugment import ( NoiseAugmentTransform, ) _DEFAULTS = { "rate": 0....
8acfe8a927f7c960523b783838d6d48dbff9ba4bc2e7f325fb673b391ce39b74
Python
3,744
64
import torch from transformers.deepspeed import HfTrainerDeepSpeedConfig class KMAETrainerDeepSpeedConfig(HfTrainerDeepSpeedConfig): """ The ``KMAETrainerDeepSpeedConfig`` object is meant to be created during ``TrainingArguments`` object creation and has the same lifespan as the latter. Note: It is r...
4bb1a37489e609e75f3b9234ec4a585fe21a35f537ce95655d1c9bf3ea70a70e
Python
3,745
131
"""Tests for ``aestetik.utils.utils_clustering``. Covers kmeans/bgm/leiden/louvain paths, the resolution-search helper, and the spatial cluster-refinement code path including the multi-batch branch. """ from __future__ import annotations import numpy as np import pytest from aestetik.utils.utils_clustering import ( ...
8d1be7bb5876068deca21acb8ee4a976f51a2a6ca909c8c54bdfc9b98c2058ce
Python
3,745
108
# 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 torch logger = logging.getLogger(__name__) class NanDetector: """ Detects the first NaN or Inf in forward a...
b3f1b5e32581c76b475ff996e16f572ece0650556fa221917ce079430eb0b1b3
Python
3,745
108
# /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 scipy.io as sio import CBIG_pMFM_basic_functions as fc import warnings def CBIG_pMFM_generate_simualted_fc_fcd(gpu_index=0): ...
e6d0c9f1ac73ac3eb520319eceb584c6cf0a09d766beaa82f9500a7b1bdba4ec
Python
3,745
98
import numpy as np def interpolant(t): return t*t*t*(t*(t*6 - 15) + 10) def interpolant1(t): return t*t*(t*(t*6 - 15) + 10) def interpolant2(t): return t*(t*(t*6 - 15) + 10) def generate_perlin_noise_2d( shape, res, tileable=(False, False), interpolant=interpolant ): """Generate a 2D numpy a...
580f188e28cce92fa7f46ba19f7b09c8a12fdfbfea3178def46faacf1c58a0e2
Python
3,746
128
# _ _ # | | | | # ___ __ _ __ _ ___| |_ ___ ___ | |___ # / __/ _` |/ _` / __| __/ _ \ / _ \| / __| # | (_| (_| | (_| \__ \ || (_) | (_) | \__ \ # \___\__,_|\__,_|___/\__\___/ \___/|_|___/ ''' A Convergent Amino Acid Substitution identif...
94702e1b70f5ec63d29e90098eacf867fd5f9a148d2d939d41bcaa60fc032f8d
Python
3,750
104
# 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 Dict, List, Optional, Tuple import torch.nn as nn from fairseq import utils from torch import Tensor class FairseqDecode...
c6678d23ea5aa6dfe3671af86dee491c9880f734e456974d7444c7e3665c9794
Python
3,750
93
import unittest from unittest.mock import patch from pyecharts import options as opts from pyecharts.charts import Radar v1 = [(4300, 10000, 28000, 35000, 50000, 19000)] v2 = [(5000, 14000, 28000, 31000, 42000, 21000)] class TestRadarChart(unittest.TestCase): @patch("pyecharts.render.engine.write_utf8_html_file...
428f48234fc28509ce71afbdeb09eaaf0eea5df36a14161d0c07854bff002a1b
Python
3,752
104
import numpy as np import pytest import torch import torch.nn as nn from moove.utils.segment_utils import segment_ml from moove.models.ConvMLP import ConvMLP class AlwaysSyllableModel(nn.Module): """Mock model that always predicts syllable (logit > 0).""" def forward(self, x): return torch.tensor([[5....
427e7229c8b8689aa932251bd0541dd9ed8b3a7fbe9d40bfe7e1d766ccbdb6ce
Python
3,754
105
import pandas as pd from os.path import join from config_path import PROSTATE_DATA_PATH processed_dir = 'processed' data_dir = 'raw_data' processed_dir = join(PROSTATE_DATA_PATH, processed_dir) data_dir = join(PROSTATE_DATA_PATH, data_dir) def prepare_design_matrix_crosstable(): print('preparing mutations ...')...
07608d93b8df8de115992cd01e6b071555ecf63167f095cce363791c441c982f
Python
3,755
102
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import warnings from dataclasses import dataclass, field from functools import cached_property import numpy as np from pymatgen.core import Structure from pymatgen.entries.compatibility import Compatibility, MaterialsProject2020Compatibility fro...
65116912c1391de6b0f3464c71119f33e043591d5a3017ae708a8d7419602b7b
Python
3,755
91
import os import pandas as pd import numpy as np from neuron import h # Dictionary mapping current types to their corresponding NEURON attributes current_types = { 'nax': '_ref_ina_nax', 'nad': '_ref_ina_nad', 'car': '_ref_ica_car', 'kdr': '_ref_ik_kdr', 'kap': '_ref_ik_kap', ...
65b4a753726bfaf599ca9e389905d50cfca46609ba3493200c7a020fed47e96f
Python
3,755
98
from __future__ import annotations from typing import TYPE_CHECKING import torch from torch import nn if TYPE_CHECKING: from collections.abc import Callable def _partial_freeze_hook_factory(freeze: int) -> Callable[[torch.Tensor], torch.Tensor]: """Factory for a hook that freezes the first ``freeze`` entri...
4d7511a22363de250629e649dbf1619c907aa80a0f2d4f47b2d91fb67df7ef5c
Python
3,758
105
""" Integration tests for file_management/file_loader.py. Verifies that loading example CSV and Excel files produces the expected DataFrames — correct shape, column names, selected column, and time detection. """ from pathlib import Path import pandas as pd import pytest from src.file_management.file_loader import l...
c76017a8477212ca3c97d31721adb02deb7f3edb213a77ae90069b49c332705b
Python
3,759
62
# -*- coding: utf-8 -*- """ Created on Mon Mar 18 16:44:50 2024 @author: Satoru Muro """ import pyautogui import time import tkinter as tk from tkinter import simpledialog from tkinter import messagebox import keyboard # keyboardモジュールをインポート def ungroup_selected_objects(): try: pyautogui....
e25edde625eab6e73339685a986c3076d13e5e12c54deeeae83ff781f3da7ef7
Python
3,759
129
import argparse import pandas as pd # Find the best orientation for index barcodes based on multiple % Undetermined reads results. # # Works around any issues with bcl-convert, RunInfo.xml, isReverseComplement, and barcode orientations which # "can be wrong in some cases due to software bugs."[0] # # See: # - [0] h...
ec4530c547ded5dc3725114861edc8cb68195cc52c1ea5c7b87c969e7f8c2dd7
Python
3,759
96
def run_seg_cmd( input_srr, cmd, cfg, singularity_path=None, singularity_mount=None, singularity_home=None, ): """ Run a segmentation command with the given input SRR. Args: input_srr (str or list): Path to the input SRR file or a list contain...
60e19795e8ce46e7576fbc6d91a6f7dcbba4419f9f66797b7150f3b9f1f1a30e
Python
3,764
126
__author__ = 'heroico' import numpy import logging import math NONE="none" FROM_PHENO="from_pheno" FROM_REFERENCE="from_reference" def normalizationScheme(scheme, covariances=None, weight_db_logic=None): n = None if scheme == NONE: n = NoNormalization() elif scheme == FROM_PHENO: n = _Bet...
f9b2f3c27234963e611479ace7b956ecd2dbfda136cf3f79c92ab7f4be8e5554
Python
3,764
105
#!/usr/bin/env python3 """Gera todos os inputs da campanha: 1784 perovskitas + 9 atomos isolados. Uso: python3 gen_inputs.py # tudo python3 gen_inputs.py --limit 8 # amostra, para teste local python3 gen_inputs.py --only nome1,nome2 Saida: inputs/<nome>.fdf um arquivo por est...
a32da0c573a0ab0ba5636d92343cc4c46fb455105e77d8877a9571473a0ae019
Python
3,766
101
from itertools import product from typing import Any import numpy as np from torch.optim import Adam, SGD from simulation_encoder.dataclass.config_schemas import ( HyperparameterDiscreteConfig, HyperparameterRangeConfig, ) def generate_hyperparameters( continuous_params: HyperparameterRangeConfig, discr...
aeca5afe20ed10974a0463e8f9ee964ed49072e103215a3e3fef66531b46d6ea
Python
3,766
82
# 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...
7cd4d5a04d5ae9c860272fca7bb5e4c5f8d1c926912c2dcd578068c1041d69d1
Python
3,767
118
# @license # Copyright 2020 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...
e3e16eb37994565c19ed2bf063687745ebb2985c15f58ccd3c9bcfdfa309e588
Python
3,767
83
# 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...
1a63f99c586f056578ab343a9cbe4376cada39e0c9a036740d356ea216c82c03
Python
3,769
105
# 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 dataclasses import dataclass import math from omegaconf import II import torch from fairseq import modules, utils from fairseq.logging i...
8aee9500118c7e04fe4909d2dc78a3d6e0ceba9dfb1624bb29fa28bfad77edf1
Python
3,769
124
import tkinter as tk from PIL import Image, ImageTk import glob import subprocess import os import sys def saveICs (indices, path, f): outfile = path + f with open(outfile, 'w') as file: for item in indices: file.write("{},".format(item)) def handler (event): if eve...
c6ae032496caab83c0852156cd0f6bbbfe53846ffa51a21b2690e47fa20d2190
Python
3,769
126
# extract 20% independent_test_set, do 5-fold split in remaining data from Bio.SeqRecord import SeqRecord from Bio import SeqIO from sklearn.model_selection import train_test_split import os from tqdm import tqdm import random from sklearn.model_selection import KFold import argparse import numpy as np import csv rand...
eea8a3d016d85be9d537f8b0908c8303058771dbb28fb593bbbc559fb9e899d5
Python
3,770
96
"""A module you can import that does one thing: It makes Tensorflow shut up. You can import this before you import tensorflow in your code, and some of the warning messages will go away. There is also a class (with context manager support) for capturing ALL stderr messages. Use with caution since it can delete import...
86c581782a607e5c138a8090bf122ebe9abf270ccd9de816e8ebf8bbdc7dbb98
Python
3,772
128
import os import subprocess import glob import shutil from create_input_json import createInputJson npx_directories = [r'N:\715093703_386129_20180627' ] probe_type = '3A' json_directory = r'C:\Users\svc_neuropix\Documents\json_files' def copy_to_local(source, destination): robocopy(source, destination) ...
0b403e0186e6090a639066ee7734c274de88bd3fe5946c2bf6b21d3a22021348
Python
3,773
125
import torch from neurovfm.pipelines.encoder import EncoderPipeline from neurovfm.systems.utils import NormalizationModule class DummyEncoderModel(torch.nn.Module): """Minimal stand-in for VisionTransformer in encoder pipeline tests.""" def __init__(self, out_dim: int = 64): super().__init__() ...
9a2df716bd91d7eb1e1565aee7a3289c7afb32bcfe345368de4966a180d1fdb3
Python
3,773
90
"""Manages GO group headers and optionally sections containing GO group headers.""" import collections as cx from goatools.gosubdag.go_tasks import chk_goids __copyright__ = "Copyright (C) 2016-2017, DV Klopfenstein, H Tang, All rights reserved." __author__ = "DV Klopfenstein" class HdrgosSections(object): """M...
ab3c06871874060c46a58819ef7d2d791ac1abaa2a632b0dbfd2b71fecbd4ea1
Python
3,773
113
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from collections import defaultdict from contextlib import nullcontext from typing import Callable, Dict, List, Type, Union import pytest import torch from mattergen.diffusion.corruption.sde_lib import SDE, VESDE, VPSDE from mattergen.diffusion...
b9cd2fde1bddf7bae678a9c97e67c959bed430cf1eeff47e9c2135c429e90c76
Python
3,773
94
#!/usr/bin/env -S uv run # /// script # requires-python = ">=3.11" # /// import os import pathlib SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__)) # Based on example here: https://blog.yaakov.online/zip64-go-big-or-go-home/ CONTENT = ( ( # --- Local File Header --- b"\x50\x4b\x03\x04" # L...
5a550d3a41f567509149032612f583890a7aaace68007f0977a66e66f2a9f52c
Python
3,774
109
from torch.utils.data import DataLoader import torch from sklearn.model_selection import KFold import lightning.pytorch as pl from typing import Union, Optional from pathlib import Path from rinalmo.data.alphabet import Alphabet from rinalmo.data.constants import * from rinalmo.data.downstream.translation_efficienc...
e51941730c62444e97379319150b093c9b7f4945444de66a4dec09a7571713d2
Python
3,774
122
""" Adapted from https://github.com/neuroailab/TDANN/tree/main/spacetorch/losses """ import numpy as np from scipy.spatial.distance import cdist, pdist, squareform from scipy.stats import pearsonr from spacestream.utils.array_utils import lower_tri from spacestream.utils.swapopt_utils import precompute_neighborhoods ...
b001de5619db65aaf376c5e5bfdfde69e275219e1a946cf83144b510d5cd59a6
Python
3,775
123
import itertools import joblib import numpy as np import pandas as pd import os import unittest import tempfile import pathlib from numpy import testing from sklearn import datasets, preprocessing #from matplotlib import pyplot from mentor import _cluster as cluster from mentor import _datasets as datasets from mento...
cebb2a911ea31c213dfa2e74a2cc4ddeec2fdbada611c95892d339a80bd6f3ba
Python
3,775
134
"""Culture-collection accession shape, gating what a StrainInfo match may join. `fix_missing_strains.py` is the only caller. `apiadapters.straininfo. StrainInfoAdapterBase.retrieve_strain_models` joins a record StrainInfo returns to whichever BRENDA strain shares its *first* matching designation, with no organism cons...
e506a7d0923497021eb00b219332cb266849c97ac19c2836693c84fcff07b3e5
Python
3,775
125
#!/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. from __future__ import absolute_import, division, print_function, unicode_literals import argparse import concurrent.f...
96731b0d2e09214e28e3d24dec937f07dde8e3af70e48c4008a84fa16f5fa404
Python
3,777
119
import os import pytest from sklearn.ensemble import RandomForestRegressor from pgmpy.ci_tests import GCM from pgmpy.factors.continuous import LinearGaussianCPD from pgmpy.models import LinearGaussianBayesianNetwork @pytest.fixture def df_indep(): model_indep = LinearGaussianBayesianNetwork( [ ...
0f2660c4f8ff219e48290eac78b06c277d8798aa35019715b86670b9cebe5d83
Python
3,778
83
#! /usr/bin/env python import os import logging from timeit import default_timer as timer import metax from metax import Logging from metax import Exceptions from metax import Utilities from metax.predixcan import PrediXcanAssociation as PA from metax.predixcan import Utilities as PrediXcanUtilities def run(args, p...
78ed56598a92ceb8a625e9a24b5e5e1ad20b14e3bef950d6a33d59585589af61
Python
3,780
101
import os from copy import deepcopy from os.path import dirname import numpy as np from model.builders.prostate_models import build_pnet2 base_dirname = dirname(dirname(__file__)) print (base_dirname) filename = os.path.basename(__file__) task = 'classification_binary' selected_genes = 'tcga_prostate_expressed_gene...
531c7715ae79e2a3bf134856a996dcd802f20b89d5f7024d02e08267db0c0269
Python
3,782
130
#!/usr/bin/env python # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import argparse import contextlib import sys from collections import Counter from multiprocessing imp...
6542a5de7466fb02d27dea07a14d1f0b0c7c5ffadfddc8bd9dab565a8f13ca3c
Python
3,782
103
import torch import torch.nn as nn from torch.utils.data import Dataset, DataLoader import numpy as np import pandas as pd from tqdm import tqdm from sklearn.metrics import roc_auc_score import warnings warnings.filterwarnings('ignore') from .encode_structure import * from .model import * from .utils import * def g...
93e15244236eb7ae03d70a3615240012dd30b91483fc1b559b9a29879de5e75f
Python
3,784
121
from __future__ import annotations from matplotlib import cbook from matplotlib.backends.backend_qtagg import FigureCanvasQTAgg, NavigationToolbar2QT from matplotlib.figure import Figure from PySide6.QtCore import QSize from PySide6.QtGui import QIcon, QPixmap from PySide6.QtWidgets import QVBoxLayout, QWidget from s...
a3b94506916c4dbf948a9270ca3c9bb117bab905786e14adc3e9559f015757f2
Python
3,784
115
"""Shared fixtures and helpers for the token-label test package. The tokenizer is built in-process from an inline vocabulary, because the assertions are about *offsets* and stubbing those would test the stub. Each word becomes one token per character, which gives exact control over which tokens cover which characters....
1d10c5c14013d16cec88bc97a7aa5b999ebd5837cc2d8f3db72f898d67bf1335
Python
3,785
105
# /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...
019c29ba9ccf824b14c49cb91622f1047cc5dc1077dcdc304f8e2577eda21d6e
Python
3,786
108
"""Function that gets an instance of a model, given its name and a configuration as a dict.""" from __future__ import annotations import inspect from typing import Callable import lightning from . import registry def get( name: str, config: dict, input_shape: tuple[int, int, int], num_classes: int...
1c56ae201ac8da1e485d7b1215e5d235eb48a75a8ae9e2f6ad7729c053695381
Python
3,786
135
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2020 Daisuke Matsuyoshi # Released under the GNU AGPLv3 # https://opensource.org/licenses/AGPL-3.0 """ API for DTI-NODDI """ __author__ = "Daisuke Matsuyoshi @dicemt" import os import os.path import re import numpy as np import nibabel as nib from dti_n...
84bffc70fd17113bb99aaf1525467378799aad42876826cc4b7b86b2fabf081b
Python
3,788
105
# /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...
94e26db0179da06d6d13dea279c284400e8def774c3d3e30e22e092e1de8835f
Python
3,789
91
"""Collect GO paths.""" __copyright__ = "Copyright (C) 2016-2018, DV Klopfenstein, H Tang, All rights reserved." __author__ = "DV Klopfenstein" import collections as cx import sys from itertools import tee class GoPaths(object): """Class for helping traverse GO paths.""" adjdir = { None: lambda go_...
d16af9fa29e6612d112a5978d185d9fce2b27d11596a9cd9fb8ab935873a2d4c
Python
3,789
108
import matplotlib.pyplot as plt import numpy as np import igraph as ig import networkx as nx import os import sys from weighted_rc import weighted_rich_club abspath = os.path.abspath(__file__) dname = os.path.dirname(abspath) os.chdir(dname) sys.path.append('..\\src\\') from read_graph import read_graph datapath = "....
243c709c98243570481b1b1efd72c4af10659458d5a9b4059d8ce08f7b8794b5
Python
3,791
107
import pandas as pd from sklearn.model_selection import train_test_split import torch from torch.utils.data import DataLoader, Dataset class PointDataset(Dataset): """Dataset for a single time point from sequence data""" def __init__(self, sequences: dict, time_point_idx: int): self.sequences = seque...
ceb0a24eb210f8feabcd6931bd1a22c34d8654f190cd51304b5e25a0e2b05cc9
Python
3,792
112
import os import torch import matplotlib.pyplot as plt class Plotter: """Class for creating and saving plots""" def __init__(self, results_dir: str = "results/", experiment_key: str = ""): self.experiment_key = experiment_key self.results_dir = results_dir self.results_path = os.path...
bcd8a11bb989886b8c5b75bce0d51987b8184a5a79b8bb7f3ec48f5e5627b128
Python
3,793
100
# 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 import utils from fairseq.criterions import LegacyFairseqCriterion, register_criterion from torch import nn @register_criterion...
7c9ce550884d6ec5835adae73c83cd8ee4d19e092465a410d7b5346d21563921
Python
3,794
117
# 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 from mmpt.utils import recursive_config class BaseJob(object): def __init__(self, yaml_file, dryrun=False): self.yaml_...
0c25d5540d93b0a9cf77478118c165253d7cd8686f9b2ebd0068c9d58a8c98f9
Python
3,795
89
import functools import torch import torch.nn as nn import torch.nn.functional as F import math class route_func(nn.Module): r"""CondConv: Conditionally Parameterized Convolutions for Efficient Inference https://papers.nips.cc/paper/8412-condconv-conditionally-parameterized-convolutions-for-efficient-inference...
f54babac62d1f4fb700aefd41ad0a089ee0ee29a733246ee7b88a660534726fc
Python
3,795
119
from __future__ import annotations from src.core.app_settings_manager import AppSettingsManager def test_app_settings_manager_instantiates_without_gui_state(): manager = AppSettingsManager(app_type="telemetry_photom_opto") assert manager.display_duration_box_var is True assert manager.num_instances_box_...
e971006214d0030dc50b8d6f648a02e74208f5c08449c66e9afb59b29eead340
Python
3,796
97
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Use this script in order to build symmetric alignments for your translation dataset. This script depends on fast_align and mosesdecoder too...
eab44facc22fc0c211c7b2c02f1890546e5cd351f3028cd42e7ce2094e4ccf29
Python
3,796
105
from copy import deepcopy import numpy as np def get_shape_must_be_divisible_by(net_numpool_per_axis): return 2 ** np.array(net_numpool_per_axis) def pad_shape(shape, must_be_divisible_by): """ pads shape so that it is divisible by must_be_divisible_by :param shape: :param must_be_divisible_by: ...
6b8d5cc2df35a804d2a7d9eee45f8c18bb4734e6308e971e7c251f319d456ce8
Python
3,799
122
# 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 typing as tp import unittest from tempfile import TemporaryDirectory from fairseq.binarizer import BinarizeSummary, FileBin...
c4fac2f87ec1f1776d5f1df1308c0abe36769dd4a931e9486813240abb55d8f1
Python
3,800
116
from os.path import join import pandas as pd from config_path import * def get_reactome_pathway_names(): ''' :return: dataframe of pathway ids and names ''' reactome_pathways_df = pd.read_csv( join(REACTOM_PATHWAY_PATH, 'ReactomePathways.txt'), sep=' ', header=None) reactome_path...
fd8be9d60f0218e219bc01a5e1c6465679595bb0bd3d19c7f338a1967bef1ec0
Python
3,802
99
# 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 math import torch from torch.nn.modules.loss import _Loss class LatentLayersKLLoss(_Loss): def __init__(self, args): sup...
32522fd92910e9457aa5f54de0328bff1b8fca5b49d7a7069748ac9b1de205ce
Python
3,803
81
"""Helper functions for loading pretrained gene embeddings.""" from pathlib import Path from typing import Dict, Tuple import torch from scanpy import AnnData import numpy as np import pandas as pd EMBEDDING_DIR = Path('model_files/protein_embeddings') MODEL_TO_SPECIES_TO_GENE_EMBEDDING_PATH = { 'ESM2': { ...
28fa7d4f4b10803473af35237450ba3fd9fdf510b207d00ef63bca0b03441acc
Python
3,804
110
import numpy as np from .model_functions import SimpleModelCLFunction from .parameters import CurrentObservationParam, CurrentModelSignalParam, NoiseStdFreeParameter from mot.library_functions import log_bessi0, normal_logpdf __author__ = 'Robbert Harms' __date__ = "2014-08-05" __license__ = "LGPL v3" __maintainer__ ...
ae9999784e7474342a47686538c46af0afaa817847fd6d5765094f340c640ea9
Python
3,808
129
"""Fetch the BRENDA data blobs from the Hugging Face Hub and verify them. Both paths come from ``brenda_references.data_paths``, the one place that decides where the blobs live, so the download lands exactly where every reader looks for it. Resolving them here instead would put them in the checkout while a non-editabl...
3e00738f4d6356c412310df683bea67fcca9f74283ecaade98991d67a694bb4e
Python
3,813
126
#!/usr/bin/env python3 """Generate a jobs.sh file for SLURM array job submission. This is step 1 of the SLURM workflow for reproducing the SymmNet paper figure. Each line of the output file contains one `python main_salnet.py ...` command, one per dataset × algo × seed combination. Already-completed runs (those with a...
63959137f48b9830ba33773686061d6f4f6274dc6398fcd9b2a9eb93034318fd
Python
3,813
118
# -*- coding: utf-8 -*- """ @Time:Created on 2019/5/20 20:49 @author: LiFan Chen @Filename: main_glu.py @Software: PyCharm """ import torch import numpy as np import random import os import time from model_glu import * import timeit def load_tensor(file_name, dtype): return [dtype(d).to(device) for d in np.load(f...
82917a4ec805190ffc5937488355eaec67ee3fa1e8fb1495da3667d5f0e7fe0b
Python
3,813
101
# @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...
c9af983eb726474c8445b6aae6753bb31288cf5ab6f4162063507156348e058d
Python
3,814
119
import numpy as np graph_file = 'hcpl_graph.npz' b0_file = 'hcpl_b0.nii.gz' output_file = 'hcpl_odf.nii.gz' import os import scipy.ndimage as ndi ''' ---------------------------------------- Create graph or read from file if exists ----------------------------------------''' if (os.path.isfi...
de98ed06ffbd69d947e9fbf9db8b2f51ef893003b796ba7156eae90d62c97e3d
Python
3,814
92
# -*- coding: UTF-8 -*- """ @Project: iDCF @File : main.py @IDE : PyCharm @Author : hjguo @Date : 2025/7/9 11:35 @Doc : Main function. Add model interpretability analysis """ import os import torch import numpy as np import pandas as pd import random from iDCF.utils import load_data, load_data_from_path, load...
42846e8870343a56e984e91736d77e90c08b372ec6f5bf055b4c274b5b6fec4f
Python
3,815
118
#### ::: mutate seqs ::: #### import os import sys sys.path.append('../motif') import pandas as pd import numpy as np import argparse import motif_utils as utils def mutate(seq, start, end, target=None): """ Mutate input sequence at specified position. If target is not None, returns the mutated seq....
8d92c927fab4e43a8c371855a98a2f1283a1cb63b7adbce6f273bfe041c6e12f
Python
3,816
89
import os import json import sys def add_intended_for_field(base_dir, subject, session): # Construct the subject and session identifiers subject = f"sub-{subject}" session = f"ses-{session}" # Define the field map directory fmap_dir = os.path.join(base_dir, subject, session, 'fmap') # Define ...
457ae2eb8c81a8c39edc4a85259253f9bffcfec89eea5cea6e920c129d09feff
Python
3,817
111
import numpy as np import cv2 import time import numba from msi_visual.normalization import spatial_total_ion_count, total_ion_count, median_ion class TOP3: def __init__(self, low=99.9, norm_percentile=99.9): self.low = low self.norm_percentile = norm_percentile def __repr__(self)...
ea740852eab78a63ece13653decde45e754c154a8fed4237755f9bdcbe7fdec0
Python
3,818
97
from kneed import KneeLocator import pickle from matplotlib import pyplot as plt import numpy as np highlight_rank = 3 with open("performance_metrics/objective_function.pkl", "rb") as f: objective_function = pickle.load(f) with open("performance_metrics/similarity_metric.pkl", "rb") as f: similarity_metric =...
306f7c3d8a122cdd2e44d4547185546844eb37063ec89d6b62f0d1c9d09f540b
Python
3,819
112
from os.path import join import numpy as np import pandas as pd import seaborn as sns from matplotlib import pyplot as plt, ticker from config_path import PROSTATE_LOG_PATH from setup import saving_dir custom_rcParams = { 'figure.figsize': (8, 3), 'font.family': 'Arial', 'font.size': 14, 'font.weight...
97fdcfc369a39e79f27e4ddb9dda042347f7bc1a50e083159668a5637ccac6bd
Python
3,821
79
"""Load the three Paper-#2 FTIR datasets into the shared `SpectralDataset` interface. Design choices (see spec §4–5): - `y` = the AUTHENTIC fraction (main-food %), single target. This makes the existing detection engine (`classification_from_tahini`, threshold scan) apply unchanged, and RMSE/R²/MAE/RPD are numeric...
ef8f61deb698c43cd816b44626896172861131653d3351a3d8ea368fa30c117d
Python
3,821
117
from __future__ import annotations import dataclasses from subprocess import CalledProcessError from typing import TYPE_CHECKING from typing import Literal import pbs_installer as pbi from poetry.core.constraints.version import Version from poetry.config.config import Config from poetry.console.exceptions import C...
702a452e60274d9f88b59c9dcdac69f07e2d1f9841be49c4e5db93683c3cde98
Python
3,825
105
import math from itertools import combinations import numpy as np import pandas as pd from scipy import stats from tqdm import tqdm from pgmpy.base import DAG from pgmpy.ci_tests import get_ci_test from pgmpy.global_vars import config from pgmpy.metrics import BaseUnsupervisedMetric class FisherC(BaseUnsupervisedMe...
cf652c16e7dd8ef13f63b620acc8597daf5caffa52cf19ce669cff8b08307706
Python
3,827
89
# 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...
9d5ff295cf8c0565bde01ad6a3ae438f8f8da49fd3298a255380bca4f2fbb8ae
Python
3,829
120
import pandas as pd from scipy.spatial.distance import jensenshannon import matplotlib matplotlib.use("TkAgg") def kmer_frequency_analysis(sequences, k=3): def generate_kmers(seq, k): return [seq[i:i + k] for i in range(len(seq) - k + 1)] kmer_counts = {} total_kmers = 0 for seq...
e9943eb7bae83d2a460b5c639b27caf0f3b94ec84d0d1123e60059d25c8f287e
Python
3,829
117
"""Configuration loader. Single entry point for parameters (`config/params.yaml`) and data locations (`config/paths.yaml`). Also the single source of the random seed, so every stochastic step in the package is reproducible. Usage ----- >>> from musicnarr import get_params, get_paths, get_rng >>> p = get_params() >>> ...
c3692aeece6f8e5323421940ba7d301cc563ef7cccfe0a227c08eb541cc7a717
Python
3,830
89
import jax import jax.numpy as jnp import pytest from oneqmc.geom import ( masked_pairwise_diffs, masked_pairwise_distance, masked_pairwise_self_distance, ) @pytest.mark.parametrize("shape_x", [(10,), (10, 2)]) @pytest.mark.parametrize("shape_y", [(10,), (10, 4)]) def test_masked_pairwise_distance(shape_...
4c22674d06d6db29a0e18ba297e1bf1ab01d3e18a557f77c20783cbd0f565961
Python
3,831
130
import re import logging import os import io import gzip import pandas from . import Expression from ..misc import Math ######################################################################################################################## class ExpressionManager(Expression.ExpressionManager): def __init__(self,...
b02a5d65e716d3c453537ee3b705c225416ceaa5d5c2b708074b191a91b1eac7
Python
3,832
119
#!/usr/bin/env python from __future__ import annotations import argparse import subprocess import sys from pathlib import Path from typing import List, Optional ROOT = Path(__file__).resolve().parent PYTHON = sys.executable def run_script(script: str, extra: Optional[List[str]] = None) -> None: command = [PYTHO...
02e2c82613e4aa810295e8b0940605231b7ff6c7b8e34fb2bf1245882f6225eb
Python
3,833
93
from copy import deepcopy import numpy as np def merge(dict1, dict2): keys = np.unique(list(dict1.keys()) + list(dict2.keys())) keys = np.unique(keys) res = {} for k in keys: all_configs = [] if dict1.get(k) is not None: all_configs += list(dict1[k]) if dict2.get(k)...
3ae101f427bd8d321d040f5de00501d8edd8534758e6b153dfbdfef7d0e65b76
Python
3,834
117
#!/usr/bin/env python # -*- coding: utf-8 -*- """Reads nd2 images and extracts layers of interest""" from pprint import pprint from PIL import Image import numpy as np import nd2 from nd2.structures import Volume from utils.types import MetaLike_ND2 def _process_volume(vol: Volume) -> dict: """Processs volume...
6ff7659ffdf7bb8fbb9d944d613345563c78eafa84870b5691bc344be620dd3c
Python
3,834
90
import os import textwrap import yaml import argparse from parcellate.cfg import * from parcellate.data import purge_bad_nii from parcellate.util import CFG_FILENAME, join from parcellate.model import parcellate if __name__ == '__main__': argparser = argparse.ArgumentParser('Compute a subject-specific brain parce...
60d3b1d0a0eecd8acb129f5b99ca7b10b79960316fd1c73b0b329384d1355895
Python
3,836
78
#!/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...
991ac42204ee777050376aee973af3b9f245c9c7e4dfd928b722544f08feeb2f
Python
3,839
60
"""Canonical medical sources for SegCT/MRI, independent of the input format.""" from pathlib import Path import nibabel as nib import numpy as np import pydicom from pydicom.pixels import apply_modality_lut from instant3d_bridge import Instant3DBridgeError, nifti_fingerprint from volume_geometry import dicom_datasets...
221fa1bebb0e1a0b8ded4008cff896c12e7c8d8b05c2252cefc18ea1ad0854e3
Python
3,840
82
"""Extract pinned Microsoft x64 redistributables without installing them. Input: https://aka.ms/vs/18/release/14.50.35719/VC_redist.x64.exe The installer also contains ARM64 payloads. Select only the amd64 minimum CAB. Never collect runtime DLLs from this build machine's System32 directory. """ from __future__ import ...
23642758067ec1ba4ea44bb0182c283fde2bf37baee0c0065141f7c6f8e925c4
Python
3,843
77
from dynamic_network_architectures.architectures.unet import PlainConvUNet, ResidualEncoderUNet from dynamic_network_architectures.building_blocks.helper import get_matching_instancenorm, convert_dim_to_conv_op from dynamic_network_architectures.initialization.weight_init import init_last_bn_before_add_to_0 from nnunet...
7e519a60e302c1937b6b01e59ea27f77aa7f8be7563c3a99edf7ae4522508b39
Python
3,846
109
#!/usr/bin/env python """ This script will query a SMRTLink instance based on a provided set of credentials, and pull a variety of run metrics for longitudinal tracking. Notably, if an output file of the same name exists, it will filter results by existing metrics to enable it to run quickly as new runs are introduced...
d66be30e831248c94d289317998c4223a840fe68281071fc03e76d6d5f669cfd
Python
3,846
90
import torch from nnunetv2.training.nnUNetTrainer.nnUNetTrainer import nnUNetTrainer class nnUNetTrainer_5epochs(nnUNetTrainer): def __init__(self, plans: dict, configuration: str, fold: int, dataset_json: dict, device: torch.device = torch.device('cuda')): """used for debugging plans et...
99fa4a8b12375f9da7623dcb959731ff80d54009e37a81ace4ad58c54eba3cba
Python
3,850
89
import sys import types import unittest import numpy as np if 'parmed' not in sys.modules: parmed = types.ModuleType('parmed') parmed.__version__ = 'stub' sys.modules['parmed'] = parmed from GMXMMPBSA.amber_outputs import DecompOut from GMXMMPBSA.output_file import _combine_entropy from GMXMMPBSA.utils i...