sha256 stringlengths 64 64 | language stringclasses 27
values | size int32 1 491k | lines int32 1 21.8k | content stringlengths 1 200k |
|---|---|---|---|---|
071a8d9dc3d69d9f89b14939cc01d5c780949623c808e6704717b6444b5e905f | Python | 2,989 | 88 | import unittest
import numpy as np
import torch
import hypothesis.strategies as st
from hypothesis import assume, given, settings
from torch.testing._internal.common_utils import TestCase
from examples.simultaneous_translation.utils.functions import exclusive_cumprod
TEST_CUDA = torch.cuda.is_available()
class Al... |
0afecc5caa929c1bc5daec4a990e65e55023b1d80d581da32d7c833c8a8e0e48 | Python | 2,989 | 91 | from typing import Sequence, Callable, Dict
import numpy as np
import scipy
import torch
from seqeval.metrics import accuracy_score
from transformers import EvalPrediction
def accuracy_score_remote(y_true, y_pred):
pred_idx = np.argmax(y_pred, axis=1)
# for y_t, y_p in zip(y_true, pred_idx):
# print(... |
10e32ccd0e679b734203bd8be4d3bd9f3f08d5f2d58002ed9a36e10c1699b04e | Python | 2,989 | 58 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'UI/AdjustmentWidget.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_DockWidget(object):
def setupUi(self, DockWidget : QtWid... |
4d233996a73bb2219f53ef8e7fe7bc9ba372d608333f6e06fc63b49592fcf9e1 | Python | 2,989 | 77 | from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QWidget
from mdt.gui.maps_visualizer.actions import NewConfigAction
from mdt.gui.maps_visualizer.base import DataConfigModel
from mdt.gui.maps_visualizer.design.ui_TabTextual import Ui_TabTextual
from mdt.gui.utils import blocked_signals
from mdt.visualizat... |
2f6c0104a38255075ade89301ad3a424decea608c11335457a88d22aa01a5b95 | Python | 2,991 | 74 | import numpy as np
import pytest
from paper2.loaders import load_oil, load_coffee, load_juice
from paper2.parsers import oil_group_key
CASES = {
# (loader, n_scans, n_groups, target-range). Oil = 55 physical samples (5 brands x 11 levels)
# after merging the appended pure-oil 'Z' block and the '18_5_2' re-scan... |
e041ea941dfdeeefcb833fd90b8c37e3ca376bb86696c38dceb77019f8501f94 | Python | 2,991 | 101 | #
# 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
#
import numpy as np
from scipy.optimize import minimize
import time
import os
# Use th... |
502fae7f305abc38ccf970caa497a375acb3d14d7d7ef4ad0210c277e713aecf | Python | 2,993 | 101 | #
# 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
#
import numpy as np
from scipy.optimize import minimize
import time
import os
# Use th... |
4c4914be86fa0bf29f8cbe0a8451ae2c7b5bdfe35360642a21e7cffd9dde899d | Python | 2,994 | 93 | # Copyright 2026 Hongyu Sun
# Licensed under the Apache License, Version 2.0
from pathlib import Path
import random
import numpy as np
import h5py
import torch
import pytorch_lightning as pl
def set_seed(seed: int = 0):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_... |
ab8c7e7c094eae0ff9abba62706263e29abfe0d463acb135b46363e9a41d5607 | Python | 2,995 | 107 | #this file contains functions for measuring whole cell level properties when differing morphology
from neuron import h
from neuron.units import ms, mV
import cell_singlespine_randomloc as cellrl
#measure input resistance (at soma) when differing dendrite combination
#this function uses default weight values of cont... |
5d27736068b5513af00414ca5824d789e43968c3f34b42974b5b4dd51a850283 | Python | 2,996 | 83 | # 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
from . import BaseWrapperDataset, data_utils
from fairseq.data.text_compressor import TextCompressor, TextCompressionLevel
cla... |
eed7a0aadf8cbfd34c663964d2209cdf36914922aeac3cfe4e219834293d462f | Python | 2,997 | 83 | from copy import deepcopy
from model.builders.prostate_models import build_pnet2
task = 'classification_binary'
selected_genes = 'tcga_prostate_expressed_genes_and_cancer_genes_and_memebr_of_reactome.csv'
data_base = {'id': 'ALL', 'type': 'prostate_paper',
'params': {
'data_type': ['mut_... |
2088770de063604afd54cc775cf6eba1c0704e27b9fe7dcec8ab3e8c717e6f10 | Python | 2,999 | 62 | import unittest
from pathlib import Path
from GMXMMPBSA.input_parser import SUPPORTED_QM_THEORIES
ROOT = Path(__file__).resolve().parents[1]
class QMMMGBSASupportDocumentationTest(unittest.TestCase):
def test_input_documentation_lists_exact_canonical_theories(self):
documentation = (ROOT / 'docs' / 'in... |
2e07de333bf96538c0d8c44c0082160fc85d462ab0af0f81be8b29503101e888 | Python | 2,999 | 70 | """Regression tests for the bug-hunt batch."""
import numpy as np
from crossda.config import Config
from crossda.core.cross_cv import _outer_folds
from crossda.core.method_bank import generate_method_bank
from crossda.core import workers as W
def test_config_accepts_scalar_string_pipelines_and_datasets():
cfg =... |
66ae914bd1ea9008fdda9262f2fdce6cb09dc7e9dc3374d15762ded4b963e664 | Python | 3,000 | 84 | """A multiprocessing queue class that clears out the queue if an exception is raised."""
import multiprocessing as mp
from typing import Any
import queue
from bpreveal.internal.constants import QUEUE_TIMEOUT
from bpreveal import logUtils
class CrashQueue:
"""A queue that closes itself if a timeout expires during ... |
c231aff2d3b545d5c15acbe278b683ae920f1c571141c4c1fa8141add739da14 | Python | 3,003 | 108 | from __future__ import annotations
import argparse
import importlib.util
import logging
import sys
from src.dashboard.catalog import get_app_definition
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.WARNING)
logging.basicConfig(
level=logging.INFO,
handlers=[console_handler],
... |
ccc29263e5c294209c7d53097f1ed8eeadfc2b1a539b0052841a79f851b2d4c3 | Python | 3,008 | 98 | # 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 os
import sys
import numpy as np
import joblib
import torch
import tqdm
logging.basicConfig(
format="%(asctime)s ... |
fdc0f1eba9b35de3300ed583556bd09a17a6134ece6977d55f2c14d688e39600 | Python | 3,009 | 88 | #!/usr/bin/env python
"""Build the BRENDA-enzyme -> EC-number table the linking score reads.
The cheapest of the bridges and the strongest: `ec_class` is a curated column
on every BRENDA enzyme, so this is a pure identifier join with no name
comparison anywhere. Run it once and commit the table::
python scripts/b... |
73e9c9e16c74c12cbc13c53cfed892e4fb68e669921d9d9e4a406d3e7336d68a | Python | 3,010 | 71 | import os
import argparse
from pathlib import Path
import pandas as pd
import zarr
from tqdm import tqdm
import cv2
import numpy as np
from skimage import measure
def count_blobs(mask, size_threshold=20):
#are there too many labels? check how many to see if this can be optimized
labels = measure.label(mask, co... |
6c993ccd315b9da32e6e26355980f4ff34f25e184622cb88422ed666fed1da6b | Python | 3,015 | 103 | import argparse
import csv
import os
import numpy as np
import random
from process_pretrain_data import get_kmer_sentence
def Process(args):
path = args.file_path
all_folders = os.listdir(path)
count = 0
for folder in all_folders:
# load data
train_seq_path = os.path.join(args.f... |
dbe7e091dc11697e8966e3f2393f7723e5c5164ffc4857acd41e51e0cb530e31 | Python | 3,015 | 85 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
from os.path import join
import nibabel as nib
import numpy as np
from dipy.tracking.streamline import transform_streamlines
from tractseg.libs import fiber_utils
from tractseg.libs import exp_uti... |
3b770ca79828015c106602498ad6080ed056004095a49d3e951794a1f58da0a8 | Python | 3,018 | 90 | from __future__ import annotations
import torch
import torch.nn as nn
class ConvEncoder(nn.Module):
"""Convolutional encoder,
used by Parametric UMAP model.
"""
def __init__(
self,
input_shape: tuple[int],
conv1_filters: int = 32,
conv2_filters: int = 64,
conv... |
dce314da58e46a7fe831390cbfc70727b7045420e8908abd006407811bab84f1 | Python | 3,019 | 81 | #!/usr/bin/env python3
import polars as pl
import pyBigWig
import argparse
def add_phyloP(df, pbw_path):
"""
Add phyloP scores to the splice sites DataFrame.
Args:
df (pl.DataFrame): DataFrame containing splice sites with 'chrom' and 'coord' columns.
Returns:
pl.DataFrame:... |
098fc90e0db0f1599e3f4d113ffbef91061a4550477e2fa4eac60c8a6cbc0483 | Python | 3,022 | 86 | from __future__ import annotations
from types import SimpleNamespace
import pandas as pd
import pytest
from src.features.telemetry_alignment.services.cluster_analysis import (
TelemetryClusterService,
)
def test_find_longest_times_supports_global_and_per_cluster_windows():
app = SimpleNamespace(
da... |
275769a134ca9e413045baab6625c3aefd8fcf57dad24645cf1627a2760329ae | Python | 3,023 | 93 | """
This module contains method to input pulse parameters to
get desired pulse.
"""
"""
Copyright (c) 2019, 2022 [copyright holders here]
This file is part of NoSeMaze.
NoSeMaze is free software: you can redistribute it and/or
modify it under the terms of GNU General Public License as
published by the Free Softwar... |
3ff0a336ca661988d7242a01dce4f0f1b59100f69848119a235b843d02e90e05 | Python | 3,023 | 87 | import unittest
import jax
import jax.numpy as jnp
import numpy as np
from laplacian_testcase import LaplacianTestCase
from parameterized import parameterized
from folx import forward_laplacian
class TestForwardLaplacian(LaplacianTestCase):
def test_mlp(self):
x = np.random.normal(size=(16,))
la... |
3d13e2a4da697661124d0710fe6ac9f16b03dcbcb9799502978423a8fdbc87ef | Python | 3,024 | 73 | # -------------------------------------------------------------------------------------------------------------------------------------
# Following code curated for GCPNet-EMA (https://github.com/BioinfoMachineLearning/GCPNet-EMA):
# --------------------------------------------------------------------------------------... |
ab0325179140437501c752d6f2585059b6f148c5aa366ffabf7a428485776120 | Python | 3,026 | 86 | import os, sys, pdb, h5py
import os.path
import numpy as np
import torch
import torch.utils.data
class SeqicSHAPE(torch.utils.data.Dataset):
def __init__(self, data_path, is_test=False, is_infer=False, use_structure=True):
"""data loader
Args:
data_path ([str]): h5 file path
... |
eb41f243ae9a9d88f73ea0138c334b9b0cbb9d8a02ad87a9b851f07ec577d89f | Python | 3,026 | 66 | import argparse
import pandas as pd
import os
import matplotlib.pyplot as plt
# Argument parser
def parse_args():
parser = argparse.ArgumentParser(description="Update summary cluster stats dynamically")
parser.add_argument("--cluster-stat", required=True, help="new cluster stat TSV files")
parser.add_argum... |
fa97f74522cb526153b862c127bd577f0c1537c432aabd7bb01ab43ab08d882a | Python | 3,026 | 84 | import streamlit as st
import numpy as np
from msi_visual import visualizations
from msi_visual.app_utils.extraction_info import display_paths_to_extraction_paths, \
get_files_from_folder
import cv2
from pathlib import Path
from argparse import Namespace
def load_image(path):
if path in st.session_st... |
35b5af0a8b66e87236ccf9e4e44b6f9a6e47be2dc473ee20686b0e36b467b4e2 | Python | 3,027 | 122 | #!/usr/bin/env python3
import hail as hl
import os
import time
hl.init()
from datetime import datetime
start = datetime.now()
bucket = os.getenv("WORKSPACE_BUCKET")
bucket
# hardcode the VDS path in case you are not in a v8 workspace bucket
vds_srwgs_path = "gs://fc-aou-datasets-controlled/v8/wgs/short_read/snpin... |
b610a179d341d4c966e22003ce10296f8e6effd6e0a60aec4610974213dbf8ab | Python | 3,027 | 100 | """Tests for ``aestetik.utils.utils_morphology.extract_morphology_embeddings``.
The full extractor requires the optional ``pyvips`` package (and a
system libvips). We skip the module if either isn't available so the
test runs on machines without the morphology stack.
"""
from __future__ import annotations
import io
... |
92810aea03d8b9fc21142487633826f3e42f8e5fce571f88ca57c9ca3e5c05d0 | Python | 3,029 | 100 | # Copyright (C) 2025 ETH Zurich, Moritz Thürlemann, and other AMP contributors
import torch
import numpy as np
@torch.jit.script
class Graph:
def __init__(
self,
Z,
nodes,
coords_qm,
mm_monos_esp,
mm_monos_pol,
mol_charge,
mol_size,
R1,
... |
f837fb0dd8029468f065a9cc68d181b25ae4455477ab957b0efb5d1378a7518f | Python | 3,029 | 92 | """
This module contains method to make pulse according to parameter inputed.
"""
"""
Copyright (c) 2019, 2022 [copyright holders here]
This file is part of NoSeMaze.
NoSeMaze is free software: you can redistribute it and/or
modify it under the terms of GNU General Public License as
published by the Free Software F... |
51e88b0c49882465acc4e592b606b508b400b887cc969ccbbea748ef5de9cc80 | Python | 3,030 | 75 | import numpy as np
import pandas as pd
from anndata import AnnData
from .._constants import Keys
def _slides_indices(adatas: list[AnnData], only_valid_obs: bool = True) -> tuple[list[int], list[np.ndarray]]:
adata_indices, slides_obs_indices = [], []
for i, adata in enumerate(adatas):
slide_ids = ad... |
7db2b2e399071dfc5bf6dd2aa7afe6e5912b20ea6753b7f8ba6c2a774ca27c30 | Python | 3,030 | 87 | """Pytest fixtures that can be reused across our unit tests."""
# Author: Scott Huberty <seh33@uw.edu>
# Christian O'Reilly <christian.oreilly@sc.edu>
#
# License: MIT
from pathlib import Path
import shutil
import warnings
import mne
import numpy as np
from mne import Annotations
import pylossless as ll
from... |
a99b7340f854e1d19d1894555dc9347b351707d78fcf09c2d30ab10f0b3b62f0 | Python | 3,030 | 87 | # -*- coding: UTF-8 -*-
"""
@Project: iDCF
@File : train.py
@IDE : PyCharm
@Author : hjguo
@Date : 2025/7/9 11:37
@Doc : Train the iDCF model
"""
import torch
import torch.nn as nn
from torch.nn import functional as F
import pandas as pd
from tqdm import tqdm
from .model import iDCF
from torch.utils.data imp... |
f0992888f941545474cca76553099b8d5bd46b822aa7fe6e8e1eccabbe687f1d | Python | 3,033 | 82 | import itertools
import pandas as pd
def load_TREC_data(input_path: str, is_simplified: bool = True) -> pd.DataFrame:
trec_df = pd.read_csv(input_path, delimiter="\t", names = ["Topic", "Zeros", "PMID", "Relevance"], usecols=["Topic", "PMID", "Relevance"])
# Replace all relevance with value of 2 with the valu... |
57ab2697acf15ecff280c5014cfa1ca93f75231498e8c8bf860710f21cf263e7 | Python | 3,034 | 126 | import sys
ROOT_DIR = __file__.rsplit("/", 5)[0]
if ROOT_DIR not in sys.path:
sys.path.append(ROOT_DIR)
import uvicorn
import socket
import os
import torch
import glob
import json
import argparse
from model.ProTrek.protrek_trimodal_model import ProTrekTrimodalModel
from fastapi import FastAPI
app = FastAPI()
BA... |
ef4ac235f0400fbd73e86e677119ca71886bc50f580f9cd22b48426a42131eb7 | Python | 3,034 | 91 | # @license
# Copyright 2017 Google Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... |
461e5c7485844f6c9f10a39ab21acea02c075b6a12ccb87b7f68f45c947344bf | Python | 3,035 | 80 | # -*- coding: utf-8 -*-
# Copyright (C) 2023 Phillip Alday <me@phillipalday.com>
# License: BSD (3-clause)
"""Epoch manipulation tests."""
import mne
from nose.tools import assert_true
import numpy as np
from numpy.testing import assert_array_equal
import pandas as pd
from philistine.mne import abs_threshold, retr... |
62934ff8ebea13fac429aa48f975dff5837b9639286af1aec9cade0ccb54d4f4 | Python | 3,035 | 62 | import yaml
import pandas as pd
import tqdm
import semantic_similarity_infer as ssi
import target_family_classifier as tfc
import function_predictor as fp
import binding_affinity_estimator as bae
print("\n\nPROBE (Protein RepresentatiOn Benchmark) run is started...\n\n")
with open('probe_config.yaml') as f:
args = y... |
5e99889d68a69ba03a7aab8f7d68b52ca55b46b3481bf291f977cddf9bf5c08e | Python | 3,036 | 83 | #! /usr/bin/env python
__author__ = 'heroico'
import logging
import numpy
import gzip
import os
import metax.WeightDBUtilities as WeightDBUtilities
import metax.Utilities as Utilities
import metax.PrediXcanFormatUtilities as PrediXcanFormatUtilities
import metax.Logging as Logging
class CalculateVariances(object):
... |
5100894a4d96206996c39f8387a9ef471f2bc91ee67898ad087c74c17a10b643 | Python | 3,037 | 67 | # Copyright (C) 2025 ETH Zurich, Moritz Thürlemann, and other AMP contributors
import json
import os
import numpy as np
from pathlib import Path
def write_qm_mm_json(path):
parameters = {}
parameters["qm_zone_resnames"] = ["UNL"]
parameters["mm_zone_resnames"] = ["HOH"]
with open(path, "w") as file:... |
cd3ac3346f9f635fcd0286c279910d5b0450bfb9412c86aef8d1dfd48fe9b059 | Python | 3,037 | 88 |
import logging
import pandas as pd
from src.math_ops.time_converters import check_and_convert_time_column, is_time_data
from src.processing.photometry_metadata import get_column_titles
logger = logging.getLogger(__name__)
PREFERRED_SIGNAL_COLUMNS = ("dfof_465", "dfof_470", "490df/f")
def _normalise_column_name(c... |
dad25b56850a666fd28bca7c2875aa2f9826298020a93f1f3753b1546fd13e2d | Python | 3,037 | 86 | import zarr
import argparse
import numpy as np
import multiprocessing as mp
from pathlib import Path
def gen_col(gdir, odir,
hst=20480, wst=40960,
hnm=16, pw=0,
size=256):
wsz = pw * size
gen_col = []
for h in range(hnm):
hsz = h * size
g_pos = [hst+hs... |
285b5e159a14f7eaf1e521a9e17978780545c26e6ef1fd49d1d3f9081ff7249e | Python | 3,040 | 104 | import jax
import jax.numpy as jnp
from jax.random import uniform
from jax.scipy.special import gammaln
__all__ = ()
def flatten(x, start_axis=0):
return x.reshape(*x.shape[:start_axis], -1)
def multinomial_resampling(rng, weights, n_samples=None):
n = len(weights)
n_samples = n_samples or n
weight... |
a93e6394cd63f7a8de57b630a5d09ccca5fcbca9b9d48e354c4d6690b5fc7649 | Python | 3,042 | 93 | # 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... |
784e954af67fae7b656923e35aaf72b2655437b476299ac856f595cca42ff709 | Python | 3,043 | 87 | # /usr/bin/env python
'''
Written by Kong Xiaolu and CBIG under MIT license:
https://github.com/ThomasYeoLab/CBIG/blob/master/LICENSE.md
'''
import numpy as np
import torch
import os
import scipy.io as sio
import CBIG_pMFM_basic_functions as fc
def CBIG_mfm_validation_desikan_main(gpu_index=0, weight=1):
'''
... |
00bf0d2f582812763344d6462a58b19e15ae437b98786760206640f3b87498c3 | Python | 3,044 | 85 | # @license
# Copyright 2017 Google Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... |
64cef8f2ca452d0b8078c37f06015c3be172f53bbeac927469f9a0eefa8c4294 | Python | 3,044 | 97 | # from omegaconf import DictConfig, OmegaConf
import os
from torch.distributed import init_process_group
from ..models import models, sde, encoders, decoders, decode_stats
from ..models.encoders import controller
def get_hparams(hparams):
hparams = {k: v for k, v in hparams.items() if k != "_target_"}
return... |
da24d312d0c3479a286ad5941b1f0b78b32771d2f605b8f16505f1c95ac8a48a | Python | 3,044 | 88 | import vtk, slicer, ctk, qt
import numpy as np
from ..Widgets.ToolWidget import AbstractToolWidget
from ..Effects.ShrinkExpandEffect import AbstractShrinkExpandEffect
from ..Helpers import GridNodeHelper
class ShrinkExpandToolWidget(AbstractToolWidget):
def __init__(self):
toolTip = ''
AbstractTool... |
3761d794dd073dabf4dd764f9f10e9f2493cffd17a3245349c3a6ffb1009792a | Python | 3,045 | 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.
"""
make a general fairseq task for MM pretraining.
"""
import random
from fairseq.tasks import LegacyFairseqTask, register_task
from .task ... |
18b0954436e3b9a4b3817c1f417c4ce3b946bb8637bdcaeaae71896b2ba6bef4 | Python | 3,046 | 89 | # /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
def CBIG_mfm_validation_desikan_main(gpu_index=0, subject=1):
'''
This function is to v... |
f9bdac3f421ccc63f160c00a1ff97b8c9d6c614dc9ee91251d066e27bb0453e8 | Python | 3,046 | 83 | """
Copyright (c) Facebook, Inc. and its affiliates.
Copyright (c) Microsoft Corporation.
Licensed under the MIT License.
Adapted from https://github.com/FAIR-Chem/fairchem/blob/main/src/fairchem/core/models/gemnet/layers/spherical_basis.py.
"""
import sympy as sym
import torch
from torch_geometric.nn.models.schnet im... |
7db8ada875ddccad77a73403e5e36f83d31683820f238109a2c9da52c42f0bea | Python | 3,047 | 103 | import pytest
from pgmpy.base import DAG, PDAG
from pgmpy.metrics import SHD
@pytest.fixture
def shd_scorer():
return SHD()
@pytest.fixture
def shd_scorer_double():
return SHD(edge_reverse_penalty=2)
def test_shd1(shd_scorer, shd_scorer_double):
dag1 = DAG([(1, 2)])
dag2 = DAG([(2, 1)])
asser... |
80f79b6410ab0b118f4672a0297bd6cc73d9dde746298af67cd6bae5ca45cccf | Python | 3,047 | 74 | # Copyright (C) 2025 ETH Zurich, Moritz Thürlemann, and other AMP contributors
import json
import os
import numpy as np
from helper_functions import write_config_yaml
from pathlib import Path
HERE = Path(__file__).resolve()
EXAMPLES_DIR = HERE.parent
CALIBRATION_DIR = EXAMPLES_DIR.parent
DATA_DIR = CALIBRATION_DIR / ... |
d1a5c239ba7bd3daa307b4f6063b575f92ed9d0956ad17817feec98dcab57f4a | Python | 3,048 | 88 | import os
import pickle
from dadi_simulators import *
import numpy as np
import torch
from sbi.inference import SNPE
from sbi.inference.posteriors import DirectPosterior
from sbi.utils import posterior_nn
from natsort import natsorted
from torch.utils.tensorboard import SummaryWriter
def load_data_files(data_dir, n_t... |
767c48315540f1d6f14cd1654c71ec5fabdf0c9f5b6693139d02fc1f5a5976df | Python | 3,049 | 85 | """Decorator that makes a :class:`vak.models.ModelFactory`,
given a definition of the model,
and a :class:`lightning.LightningModule` that represents a
family of models that the new model belongs to.
The function returns a new instance of :class:`vak.models.ModelFactory`,
that can create new instances of the model wit... |
9da781ca31bd71e70b5135be582ed4f1f6ab374a4a0661cf339bf4e14f24065b | Python | 3,050 | 60 | """Remove collected test/cache artifacts and add the explicitly shipped support files."""
import argparse
from datetime import datetime, timezone
import json
from pathlib import Path
import re
import shutil
import subprocess
APP_ROOT = Path(__file__).resolve().parents[1]
NON_RUNTIME_DIRS = {"tests", "test", "__pycache... |
1d4b045166e8c1bc7a3718b9d92294f93b554a2a94e23da4eb474d8d8a05cda2 | Python | 3,051 | 60 | import numpy as np
import torch
from nnunetv2.training.loss.compound_losses import DC_and_BCE_loss, DC_and_CE_loss
from nnunetv2.training.loss.deep_supervision import DeepSupervisionWrapper
from nnunetv2.training.loss.dice import MemoryEfficientSoftDiceLoss
from nnunetv2.training.nnUNetTrainer.nnUNetTrainer import nnU... |
508318c39a52764ce2216758d5a7bb999d583ed3c5cc02af22744841eb220508 | Python | 3,054 | 78 | import os
import h5py
import numpy as np
from uncertainties.unumpy import uarray
def read_result(job_path, keys=None, subkeys=None, mols=None, subdir="training", format="sparse"):
assert format == "sparse"
if not os.path.isdir(job_path):
raise ValueError(f"Job directory {job_path} does not exist. Did... |
41b4958faae0524858dcf1b1d3195c1c1da67d6a412aaf5fbe117e0cc0bd1d54 | Python | 3,056 | 77 | import os
import numpy as np
import pandas as pd
from torchvision.io import read_image
from torch.utils.data import Dataset
from torchvision import datasets
import json
import torch
class JacquardDataset(Dataset):
def __init__(self, data_dir, label_type="MAP", data_type="SEP", transform=None, depth_transform=None,... |
91afb37eab8565965d6758afc0d9f29029c4dee6f9b60f3f05b765bd7dbe299a | Python | 3,057 | 67 | import os
import torch
def target_gene_celltype(train_loader, args):
n_gene = int(args.n_gene)
n_celltype = int(args.n_celltype)
target_gene = list(range(n_gene))
if n_celltype == int(args.output_channel):
target_celltype = list(range(n_celltype))
else:
print("\n[Stats... |
d9e5eba6cbec09cf9edb3fa05719a90a99fa939c1eef7cc043e264c8751d9443 | Python | 3,057 | 98 | import numpy as np
import torch
from msi_visual.visualizations import visualizations_from_explanations
from matplotlib import pyplot as plt
class SegmentationDataset:
def __init__(self, data, labels):
self.data = np.float32(data)
self.labels = np.int32(labels)
def __len__(self):
... |
1df92f04a3313cec5cd6dff7200501984dd83bdb8b1b5167e4dd300944648bd6 | Python | 3,059 | 93 | from typing import List
import torch.nn as nn
import torch.nn.functional as F
from torch_geometric.nn import GCNConv, global_mean_pool, BatchNorm
import torch
class UGCNN(nn.Module):
def __init__(self, hidden_dims: List[int], input_dim: int, out_channels: int):
super(UGCNN, self).__init__()
dims =... |
37efa7222841abba983cfb9dfc79108296023eca5729f7ce93092f119c9957b1 | Python | 3,059 | 77 | import os
import logging
import loompy
import numpy as np
import numpy_groupies as npg
from scipy.spatial.distance import squareform, pdist
import matplotlib.pyplot as plt
from ..plotting.colors import colorize
from ..species import Species
from ..enrichment import FeatureSelectionByEnrichment
def merge_subset(subset... |
43437c9425d70f9984514e0503307c4953a7ad8bd23b1d70bb8ac79ea5f6160f | Python | 3,059 | 88 | #!/usr/bin/env python
# Author: Jin Lee (leepc12@gmail.com)
import sys
import argparse
from encode_lib_common import (
assert_file_not_empty, log, ls_l, mkdir_p)
from encode_lib_genomic import (
peak_to_bigbed, peak_to_hammock, get_region_size_metrics, get_num_peaks)
from encode_lib_blacklist_filter import bl... |
ae5a003152825decbe588af20560b8a47e3f757dd28ff32d48637284c8845096 | Python | 3,061 | 89 | # /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
def CBIG_mfm_validation_desikan_main(gpu_index=0, subject=1):
'''
This function is to v... |
889fe4f7f2e22a484fa9c97b2131f4402286636807c954eba727a058b85c7174 | Python | 3,063 | 97 | """Checkpoint save/load compatible with DLBase-style dict checkpoints; supports legacy list format."""
from __future__ import annotations
import os
from typing import Any, Dict, Optional, Tuple
import torch
import torch.nn as nn
import torch.optim as optim
def save_checkpoint(
path: str,
epoc... |
0741b9eb947de357918e7ade292adea0bd9eb63d38729126c3386871eefc2ce0 | Python | 3,064 | 100 | # Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the LICENSE file in
# the root directory of this source tree. An additional grant of patent rights
# can be found in the PATENTS file in the same directory.
import logging
import sys
import t... |
1231c9f882fc5bd1ad8c3cb4b62efa55aa7adc3bb73094ed8bf2bb23548ced99 | Python | 3,064 | 94 | # 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 defaultdict
from functools import partial
import numpy as np
import torch
from tqdm import tqdm
from data_utils impor... |
47ca2ceb601f67e8e617acee52bf7959bf37f26bd17b58c4a6ff1e0974b3c5f0 | Python | 3,068 | 103 | # 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
class InferenceDataset:
def __init__(
self,
dataset,
prefix,
only_prefix=True,
pres... |
e6aea74b00062ff75533855f69426722677bf8840de212ad46cfa315bedd32e1 | Python | 3,071 | 94 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Logs information and errors from analysis"""
import os
import datetime
from pathlib import Path
from pprint import pformat
from typing import Optional, Literal
from utils.data_pickling import StoredData2
def save_info(
path: str | Path,
source_dir: str | Pat... |
e8424956e4d15ceb6e938b927589a6f04500d5c6a725d9d3bbfdeb43ce801626 | Python | 3,072 | 74 | from __future__ import annotations
import multiprocessing
import os
from typing import List
from pathlib import Path
from warnings import warn
import numpy as np
from batchgenerators.utilities.file_and_folder_operations import isfile, subfiles
from nnunetv2.configuration import default_num_processes
def _convert_to_... |
61f7d658d5492fb25c4f674695328bb81f08fbfb40c5968f3274bca22f0455ae | Python | 3,074 | 81 | # 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 math
class AttnHeadSelector(nn.Module):
"""
Latent variable modeling of attention head selection
"""
def __init__(
self, num_ta... |
5dfdc065c6bd52c8d852029042c4cd74163049e7db00e74c4c4119f608c5b4d2 | Python | 3,075 | 107 | """ from https://github.com/keithito/tacotron """
import numpy as np
import re
from . import cleaners
from .symbols import symbols
# Mappings from symbol to numeric ID and vice versa:
_symbol_to_id = {s: i for i, s in enumerate(symbols)}
_id_to_symbol = {i: s for i, s in enumerate(symbols)}
# Regular expression matc... |
64313935b085ecc948a33594f2486efe1e4a5293f2489ad74af9d04ff57d5c10 | Python | 3,076 | 77 | from os.path import join
import numpy as np
import pandas as pd
from config_path import PROSTATE_LOG_PATH
base_dir = join(PROSTATE_LOG_PATH, 'review/fusion')
files = []
files.append(dict(Model='Fusion', file=join(base_dir, 'onsplit_average_reg_10_tanh_large_testing_fusion')))
files.append(dict(Model='no-Fusion', file... |
e2a8a96b16b3deb40eb654694d809f9753b3e24cff03abcd0756b0f3f8062bf9 | Python | 3,076 | 85 | import logging
import time
import torch
import torch.nn.functional as F
from tqdm import tqdm
from gsMap.GNN.model import GATModel
logger = logging.getLogger(__name__)
def reconstruction_loss(decoded, x):
"""Compute the mean squared error loss."""
return F.mse_loss(decoded, x)
def label_loss(pred_label, ... |
fa45f1539ae4efc0c580a05cd436fdda83d48bbf9531f336b563fb6b418fd21a | Python | 3,076 | 82 | """Signal sheet helpers for telemetry workbook exports."""
from __future__ import annotations
import pandas as pd
from src.features.telemetry_alignment.exporters.export_frames import (
build_intercluster_interval_frame,
build_native_signal_frame,
get_standardized_native_window_bounds,
)
def populate_in... |
4368b52b3d54b3791fde4bea1a661a6ecf44c10bd6c48f4ab80b8aed74e19929 | Python | 3,077 | 91 | import cvxpy
from AugmentData import *
from cvxpy.atoms.norm import norm
from cvxpy.expressions.expression import Expression
def correct_heading_jumps(fly_trajectory_and_body):
"""
The heading values randomly jump 180 degrees. This function corrects for such jumps.
Parameters:
- fly_data (pd... |
464b543fc9e994f265292070d6767126dc478a92b74c3a10c00893877bb5840b | Python | 3,077 | 88 | # 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
from ..ops import emulate_int
class ActivationQuantizer:
"""
Fake scalar quantization of the activations using a forwa... |
49f3c5893a834704d9c00df7f2462ca86656a3d92a03a21f3769a990b573855d | Python | 3,077 | 85 | import importlib.util
from pathlib import Path
import numpy as np
SCRIPT = Path(__file__).with_name("slip_correction_applicability_diagnostic.py")
def load_module():
spec = importlib.util.spec_from_file_location("slip_correction_applicability_diagnostic", SCRIPT)
module = importlib.util.module_from_spec(sp... |
694ca58e28d80e0d27f36e50b343bb1ba05d794ae1f6c7ef45b16782a903ddcf | Python | 3,078 | 81 | from functools import partial
from typing import Tuple
import jax
from .device_utils import DEVICE_AXIS, rng_iterator_on_devices, split_rng_key_on_devices
from .optimizers import Optimizer
from .types import TrainState, WeightedElectronConfiguration
__all__ = ()
def fit_wf( # noqa: C901
rng,
ansatz,
o... |
7ad2036f743395b5622b6c8b7005f325346d00162916bfa9c2d3949fcf741287 | Python | 3,078 | 63 | import numpy as np
import pandas as pd
import os
import re
from plip.structure.preparation import PDBComplex
from plip.exchange.report import BindingSiteReport
class PDBInteractionExtractor:
def __init__(self, pdb_path, spatial_information_folder='./3D'):
self.pdb_path = pdb_path
self.spatial_infor... |
2f76061e27f63b483902f314f1def99186f4251a8eae4eef465c10e1557de1c0 | Python | 3,079 | 66 | import torch
from nnunetv2.training.lr_scheduler.polylr import PolyLRScheduler
from nnunetv2.training.nnUNetTrainer.nnUNetTrainer import nnUNetTrainer
from torch.optim.lr_scheduler import CosineAnnealingLR
try:
from adan_pytorch import Adan
except ImportError:
Adan = None
class nnUNetTrainerAdan(nnUNetTraine... |
355b7b87a4ccfb2e523a4b242585b905b4d77f4b74daf4c0bd18282ca0a26896 | Python | 3,079 | 85 | import unittest
from unittest.mock import patch
from pyecharts import options as opts
from pyecharts.charts import GMap
from pyecharts.globals import ChartType
FAKE_API_KEY = "fake_application_key"
GMAP_API_PREFIX = "https://maps.googleapis.com/maps/api/js"
TEST_LOCATION = ["London"]
TEST_VALUE = [1]
class TestGMa... |
71482f4312d6451e570c5197552ca5fae23c7c46fca2321b2b9b6009a8c66be2 | Python | 3,079 | 101 | import subprocess
import shutil
import os
import time
from create_input_json import createInputJson
######################### UPDATE ME ###############################
npx_directories = [ r"J:\750332458_412791_20180910_probeA",
r"K:\750332458_412791_20180910_probeB",
r"L:\750332458_412791_20180910_probeC"... |
7744a0d774ecf9bf54c2699a54b95e3b5e8ddb15b37c5fa1eec2a54027f0ee51 | Python | 3,079 | 91 | import os
from typing import Optional, Any
from collections import defaultdict
from simulation_encoder.logger import Logger
from simulation_encoder.loaders.loader import Loader
class GlimsLoader(Loader):
"""Loader class for loading labeled images from a directory."""
def __init__(
self,
imag... |
5fe51078f432b315dcd43e8b564c7c51242c59d40353614482e52a6039339066 | Python | 3,080 | 109 | from __future__ import annotations
from contextlib import contextmanager
from typing import TYPE_CHECKING
from typing import Any
from tomlkit import document
from tomlkit import table
from poetry.config.config_source import ConfigSource
from poetry.config.config_source import PropertyNotFoundError
from poetry.config... |
1df80edef3dedec6ceec8964144f04352a3e0ac94f165a4db1af01098ce536e4 | Python | 3,081 | 91 | 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
AMAP_API = "https://webapi.amap.com/maps?v=2.0&key={}&plugin=AMap.Scale,AM... |
6cb12a9580f10eed3974963212303ec80fae7fbeefa3f8663f25b5ce6032ac6c | Python | 3,083 | 79 | from ... import options as opts
from ... import types
from ...charts.chart import Chart
from ...globals import ChartType
class Sunburst(Chart):
"""
<<< Sunburst >>
Sunburst graphs are composed of multiple layers of ring graphs.
In terms of data structure, inner circle is the parent node of outer circ... |
7ee07d504b6219734f3346a0d141bae873316daf0185da78cb688b0f4fbb3037 | Python | 3,084 | 84 | import math
from itertools import combinations
import pandas as pd
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 ImpliedCIs(BaseUnsupervisedMetric):
"""
Tests the implied Con... |
2185e1c5b138c74ecb095f6dee4e56a26060b1b145b9729291b4d6de3ddd3d57 | Python | 3,086 | 104 | """Recordname structure for encoding/decoding metadata to/from strings."""
import re
import medaka.common
class RecordName(object):
"""Simple class for encoding/decoding sequence metadata to/from strings."""
def __init__(
self,
*,
query_name,
ref_name,
ref_start,
... |
420f96243ac4095ae6ef9ff95e723a95672e3e5fa8f721fb5a23b7994603d685 | Python | 3,086 | 83 | """Run SIESTA SZP on the 50 active-learning-selected perovskites.
Resumes from siesta_szp_results.json (will append, not overwrite). Output:
extends data/perovskites/siesta_szp_results.json so the n=143 set is
immediately available for refit.
"""
from __future__ import annotations
import argparse
import json
import ... |
47105ceb927553a9ce3da8389d1d9ba471c7712084355d79a7662e3de9ceb151 | Python | 3,086 | 52 | #!/usr/bin/env python
import logging
import sys
import argparse
from version import VERSION as __version__, MASTHEAD
import gsa_mixer.cli
import bivar_mixer.cli
import common.utils_cli
if __name__ == "__main__":
logging.getLogger().setLevel(logging.INFO)
parser = argparse.ArgumentParser(description=f"MiXeR ... |
e3c26138860b765cd51002d604d3ac2341d56b30a9e59e37a132647b6ae208a2 | Python | 3,087 | 93 | # @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... |
d077352f74e4d5bfa92f927bc1e765a8bc5d3a6bd3149a788f8f9b923c804c29 | Python | 3,088 | 98 | """Definition of AE Model"""
import math
import torch
from torch import nn
class Encode(nn.Module):
def __init__(self, num_input_channels, c_hid, latent_dim, kernel_size, p, conv_out_2):
super().__init__()
# Encoder layers
self.encoder = nn.Sequential(
nn.Conv2d(num_input_ch... |
fafb42b1e09429d1ae2342492b8341ed96615da19f4dba14093b97cbcb991630 | Python | 3,089 | 99 | import os
import json
from typing import Optional
import pandas as pd
from torch.utils.data import Dataset
class CSVLoader(Dataset):
"""
Loader class for loading labeled data from a CSV file.
Parameters
----------
exp_id : str
Experiment ID.
labels : list[str]
List of target... |
9f35e4287eb55377c72057dbf1974fe377bb17dbd6c367bd2782e73b00c37ee8 | Python | 3,090 | 96 | # 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.nn as nn
import torch.nn.functional as F
from fairseq.data import Dictionary
from fairseq.models import (
FairseqDecoder,
... |
28c0d4647f5aa38c9106aa448bde268b4466cfd324b857aa9ffbba69f8da563c | Python | 3,092 | 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.
import logging
import os
import signal
import threading
from torch import nn
logger = logging.getLogger(__name__)
class DistributedTimeou... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.