sha256 stringlengths 64 64 | language stringclasses 27
values | size int32 1 491k | lines int32 1 21.8k | content stringlengths 1 200k |
|---|---|---|---|---|
d66bc46bfb308596c79d48f5f1ef288a5acc5993e25732ce9843c3cdd01abf58 | Python | 7,370 | 190 | from functools import partial
import torch
from torch import Tensor
import math
import torch.nn.functional as F
from . import register_monotonic_attention
from .monotonic_multihead_attention import (
MonotonicAttention,
MonotonicInfiniteLookbackAttention,
WaitKAttention
)
from typing import Dict, Optional... |
4891031194801dcc781f83a939b2ef46be0a12e0babf4b2708863a63f1d871e2 | Python | 7,371 | 199 | import torch
import torch.nn as nn
from operator import itemgetter
from torch.autograd.function import Function
from torch.utils.checkpoint import get_device_states, set_device_states
# for routing arguments into the functions of the reversible layer
def route_args(router, args, depth):
routed_args = [(dict(), dic... |
832df89a617dca6112096e11d8e2d81816a77b1c80a09396a04247f8de9d6925 | Python | 7,372 | 192 | # 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 contextlib
import wave
try:
import webrtcvad
except ImportError:
raise ImportError("Please install py-webr... |
d1e9419210ac0cf06287928bc053986115eee5631c4d72f9a99dfdeb6cc17569 | Python | 7,373 | 220 | import itertools
from os.path import join
import numpy as np
import pandas as pd
from matplotlib import colors
from matplotlib import pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
from config_path import PROSTATE_LOG_PATH
from setup import saving_dir
def plot_(primary):
percent = 100 * p... |
f0078ee530bcf548caf9e3649d318d82c81fe7a05c1d9fc58e11b1921bf11483 | Python | 7,378 | 214 | #!/usr/bin/env python3
"""
Validate a previously trained distillation run without re-training.
"""
from __future__ import annotations
import argparse
from pathlib import Path
from typing import Iterable, List, Optional
import torch
from batchgenerators.utilities.file_and_folder_operations import maybe_mkdir_p
from n... |
75c971655e9a12cbbe18d3f75b8377303d0acc1795fab0f0253721ec14b750d0 | Python | 7,385 | 214 | import numpy as np
from sklearn.metrics import precision_score, recall_score
from pathlib import Path
def _read_relevant_lines(file_path: Path):
with open(file_path, 'r') as f:
lines = f.readlines()
lines = list(filter(lambda line: not line.lstrip().startswith("#"), lines)) # Ignore comment lines
... |
48ff7f04ac57906e8210af98efd809513bb6141402cfd087698876a0ee30558c | Python | 7,386 | 185 | """Training helpers for dynamic segmentation: paths, LR, checkpoints, label cache (TensorBoard for metrics)."""
from __future__ import annotations
import math
import os
from pathlib import Path
from typing import Any, Tuple
import torch
from omegaconf import DictConfig
from models.build import build_mod... |
128becc14116d81417047dedd17c90c9e74cf776b8a867537e2ba27464f8b401 | Python | 7,388 | 207 | #!/usr/bin/env python3
# MIT License
#
# Copyright 2025 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... |
7b27d6c9a4b9f2203310e400bcc92ef5df257ef87f63264a7462025eb9fda68e | Python | 7,388 | 232 | import numpy as np
import cv2
import math
from hausdorff import hausdorff_distance
from skimage.morphology import skeletonize as skelt
import torch
import copy
def find_max_region(mask_sel):
contours, hierarchy = cv2.findContours(mask_sel, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
if len(contours) == 0:
... |
e35543db67ee74296e5421431c8db8979dbb6075cd710027b72991598be33e0f | Python | 7,389 | 204 | from pgmpy.independencies import Independencies
from pgmpy.models import DiscreteBayesianNetwork
class NaiveBayes(DiscreteBayesianNetwork):
"""
Class to represent Naive Bayes. Naive Bayes is a special case of Bayesian Model
where the only edges in the model are from the feature variables to the dependent ... |
3fed74d74cb922c82fe524295df7abd3a94bb735ca7cd72da6de55d66339f521 | Python | 7,396 | 188 | from os.path import join
# matplotlib.style.use('ggplot')
import numpy as np
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
from data.data_access import Data
from setup import saving_dir
data_params = {'id': 'cnv', 'type': 'prostate_paper', 'params': {'data_type': 'cnv', 'drop_AR': Fa... |
a46feef64eae637c89f0c5ccc7fa8559293bc8b629621362cd8b6ca278d7969a | Python | 7,396 | 228 | import numpy as np
import pandas as pd
import scanpy as sc
import torch
from scipy.spatial.distance import cdist
from utils.data.dataholder import DataHolder
def create_anndata(
metadata_true: pd.DataFrame, metadata_pred: pd.DataFrame
) -> sc.AnnData:
"""
Creates an AnnData object from given metadata.
... |
78dc43b4f9499501016cf6507ad2c326e00f8f6b12e324e7b908de12a9e20fe7 | Python | 7,400 | 171 | """Phase 15 — DFT-PBE validation for C in 4 3D lattices.
Mirrors phase 12 (2D) but for 3D: SC, BCC, FCC, diamond. C only —
this phase is the carbon-only DFT closure that supports the PRL claim
that ε_V*(C) is universal across topology and dimension.
Setup: AIREBO relaxation + SIESTA single-point on the relaxed posit... |
54d5df88f987b2ca2e8e4b2fc92c15629ebb6f80e7e41f4ed364c8a8177d9479 | Python | 7,404 | 203 | import operator
import os
import random
import unittest
from unittest.mock import patch
import tempfile
import numpy as np
import pysam
import medaka.stitch
def _rand_seq(bases, n):
return ''.join(np.random.choice(list(bases), n, replace=True))
def _rand_qual(n):
return ''.join(chr(i + 33) for i in np.ran... |
b39948ee271e97eec580dfd182952b1cee1e5c7560921a1820c2f12e065a6c3b | Python | 7,406 | 206 | from __future__ import annotations
from typing import TYPE_CHECKING
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 poetry.reposito... |
bd25f4b8fe3336f7b24e33f015619d8ac4d1b5b5a47a154030aff0eff9b58b4e | Python | 7,414 | 189 | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from pathlib import Path
# Define paths
base_dir = Path('/egor2/egor/MovieProject2')
somatotopy_dir = 'somatotopy'
fd_file_pattern = 'motion_{subject_id}_enorm.1D'
plots_dir = base_dir / "bids_data/derivatives/group_analysis"
plots_dir.mkdir(par... |
da7c3999a770bbb56d21da0ece2373e3f871664147a80292655484d9c27e1442 | Python | 7,415 | 193 | """Pure unit tests for `d3text.models.heads`: the classification head, the
biaffine relation classifier, and the sentinel-aware bias initializer they
both build on.
"""
import math
import pytest
import torch
from d3text.models.heads import (
BiaffineRelationClassifier,
ClassificationHead,
PermutationBatc... |
f5abeffbbcfe73cf5818209ce32121fe2430175260118e68a3e5c64fd8b36eaa | Python | 7,415 | 196 | """Phase 10 — finite-size correction-to-scaling extrapolation.
Re-analyse the cached data from phases 5 (C site), 6 (Si site), 8 (bond)
with a 3-parameter fit:
⟨E/V⟩(L) = ε_V*(∞) + A · L^{-ω}
Universal prediction: ω ≈ 0.5 for 2D percolation (Levy & Aharony 1986
correction-to-scaling; Aharony & Stauffer "Introduc... |
3e7bb8a9b8613e5cead4651f691a80f267276d8efadd3c6c1466f527db6c629f | Python | 7,416 | 222 | import os, sys
import numpy as np
from six.moves import cPickle
from sklearn.metrics import roc_curve, auc, precision_recall_curve, accuracy_score, roc_auc_score, confusion_matrix
from scipy import stats
__all__ = [
"pearsonr",
"rsquare",
"accuracy",
"roc",
"pr",
"calculate_metrics"
]
# clas... |
50ced210ee2fac771031861235cfc21bd0c55a5eec0e4fb93fd908d14d17a792 | Python | 7,416 | 195 | # 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, field
import torch
from fairseq import utils
from fairseq.data import LanguagePairDataset
from fairseq.data... |
5d61494e9cc6d6383aeb6b65a06c5f697c947aa814a3fb69b653a52e9adaed4a | Python | 7,417 | 186 | """
hippie_wf3dacg — ACG encoder and 3D ACG computation
=================================================
Provides:
compute_3d_acg() — pure-numpy 3D autocorrelogram from raw spike times
(NEMO-compatible format: n_deciles × n_bins)
ACGEncoder — NEMO's ConvolutionalEncoder (2D CNN on 10... |
37839b91b1779c3c292214fabe0640eada95f72c6e022d71e8372d19477eca7b | Python | 7,418 | 260 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 9 17:18:48 2023
@author: Peter Rupprecht, ptrrupprecht+celldetection@gmail.com
Code to apply pretrained models for cell classification (cell vs. non-cell) from a 3D local volume (31x31x91 pixels)
Please change "folder_name" according to the loca... |
d3418ac1e350671ca18cabdf9d8b7eb013fab31b1dd7493321ba89568ad5efe7 | Python | 7,422 | 202 | # 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 ast
import argparse
import logging
import torch
from fairseq import utils
from fairseq.models.speech_dlm import SpeechDLM
l... |
8e7457777c30c1767bc30423a3301f73e7f29a4738cd502ad2fd7d37717882b3 | Python | 7,429 | 258 | #!/usr/bin/env python
# coding: utf-8
import os
import glob
import matplotlib.pyplot as plt #to enable plotting within notebook
from nilearn import image as nimg
from nilearn import plotting as nplot
from bids.layout import BIDSLayout
import numpy as np
import nibabel as nib
from nibabel import load
import pandas as p... |
b78e0a9db61cec067e1acce551e2012401388b9dd2041779be34d749fb567ca0 | Python | 7,431 | 231 | from __future__ import annotations
import logging
from pathlib import Path
from typing import TYPE_CHECKING
import torch
from lightning.pytorch import seed_everything
from rich.console import Console
from rich.logging import RichHandler
if TYPE_CHECKING:
from typing import Literal
scvi_logger = logging.getLogge... |
3ee7e8e9c19b11eb13905f44f71af5cc81830f20da3d8a8c02e94aa48c72ac27 | Python | 7,434 | 148 | #!/usr/bin/env python3
"""Regularizacao por bloco no gap das perovskitas, com o canal HYB.
O que se testa, e contra o que:
A. AFERICAO -- com alphas iguais em todos os blocos, o solver dual novo tem de
reproduzir o ridge uniforme do projeto. Se nao reproduzir, e bug.
B. wave15 SOZINHO, uniforme x por bloco --... |
cbfd0a3e8b9899f6068e59c8a1f0f703fbc5ce979dab4c284b2638f9e276ea50 | Python | 7,440 | 215 | from typing import Any
import torch
from torch import nn
class PatchEmbedding(nn.Module):
def __init__(self, in_channels, embed_dim, image_size, patch_size):
super().__init__()
self.patch_size = patch_size
self.num_patches = (image_size // patch_size) ** 2
self.proj = nn.Conv2d(in... |
3ff91e33b3d9ad1cc232a75179ae2e9722d97d8bc022ac3014647024bd082e53 | Python | 7,441 | 184 | from __future__ import annotations
import uuid
from pathlib import Path
from typing import TYPE_CHECKING
import pytest
from poetry.utils._compat import WINDOWS
from poetry.utils.env import SitePackages
if TYPE_CHECKING:
from importlib import metadata
from pytest_mock import MockerFixture
def test_env_s... |
b59d4c6564edb6786fa189f6f71d3adb495aab2791258a2b6780548b205df46f | Python | 7,442 | 147 | """A class to load up hdf5 files.
These files will have been generated by
:py:mod:`prepareTrainingData<bpreveal.prepareTrainingData>`.
"""
import math
import time
import h5py
import numpy as np
from numpy._typing import NDArray
from bpreveal.internal import disableTensorflowLogging # pylint: disable=unused-import # n... |
e26902b77c9c768c37c82b14ac550cf2ac8eb77b874158cb906c3c2dd5ab91e3 | Python | 7,442 | 226 | from Bio.PDB import PDBParser, PDBIO
from pdbfixer import PDBFixer
from openmm.app import PDBFile, Simulation, ForceField, NoCutoff, HBonds
from openmm import LangevinIntegrator, Vec3
from openmm.unit import dalton, kelvin, nanometer, picosecond, picoseconds
def ld_convert(input_pdb, output_pdb):
parser = PDBParse... |
a814405b9017992c52b3a549d9a7f389158bea2667acb19300b21a3faff0f383 | Python | 7,443 | 218 | from typing import Dict, Set, Tuple
import networkx as nx
import pandas as pd
from BLEval.evaluator import Evaluator
from BLEval.data import EvaluationData
def _build_ref_graph(true_edges: Set[Tuple[str, str]]) -> nx.DiGraph:
"""
Build a directed reference graph from a set of ground truth edges.
Self-l... |
b01a0517e519bcb64b433e465fc4ed1f12e7e36f66befc5088e51279c87861c0 | Python | 7,443 | 200 | # Copyright (c) Meta Platforms, Inc. and 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
import torch.nn as nn
import torch.nn.functional as F
from ..modules import (
TransformerLayer,
LearnedPo... |
05857ad4a154381503b7fb7b3a3aae0a8f52dc2b62208efbc8ce596a13dff431 | Python | 7,444 | 198 | """tests for vak.predict module"""
from pathlib import Path
import pandas as pd
import pytest
import vak.config
import vak.common.constants
import vak.predict
# written as separate function so we can re-use in tests/unit/test_cli/test_predict.py
def assert_predict_output_matches_expected(output_dir, annot_csv_filen... |
6aac7c9752372f83abb24b02b88137ff48adc395ce26f6f2bb27c51713a7ba39 | Python | 7,445 | 266 | # 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... |
61b9c2430885a6531269a2e514561947f251ba1ec90105acc48be828dcaf2591 | Python | 7,449 | 200 | # 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, field
import torch
import torch.distributed as dist
from fairseq.dataclass.configs import FairseqBMUFConfi... |
5d9876d1ef42cb86ce4e747f88bf25b53cbdec0fb939297e58af6f4484fe470e | Python | 7,450 | 212 | import sys
import numpy as np
def getchannelnumber(ep_file_path):
ch_num = int(ep_file_path.split('.')[-1][0:2])
print('number of channels: {0}'.format(ch_num))
return ch_num
def getversion(ep_file_path):
print(ep_file_path)
version_test = (ep_file_path.split('.')[-1]).split('-v')
if len(versi... |
a250c95edf0916f1da83386c9ce7bb14e9f668c9de9e12f288c5ed1af3988e24 | Python | 7,450 | 221 | import json
import re
import uuid
from jinja2 import Environment
from ... import types
from ...commons import utils
from ...globals import CurrentConfig, ThemeType
from ...options import PageLayoutOpts
from ...render import engine
from ..mixins import CompositeMixin
_MARK_FREEDOM_LAYOUT = "_MARK_FREEDOM_LAYOUT_"
DO... |
ff44060fbcfc1fa38855e23550f899e7f3f4b888f661effdd92f1b2742694f17 | Python | 7,450 | 262 | # -*- coding: utf-8 -*-
import json
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import nibabel as nb
import numpy as np
import os
import sys
def load_json(filename):
with open(filename, 'r') as f:
data = json.load(f)
return data
def save_json(data, filename):
with op... |
36b34065428508ab90063eae133b805b7ef0a4630daf614335c2980635e6fe92 | Python | 7,455 | 193 | """Generate learning-curve plot for the AL-OCE-SIESTA pipeline.
Produces data/perovskites/learning_curve.png with two panels:
(A) Overall RMSE & Spearman ρ vs n_train (non-strain pool, 1F+2F basis)
(B) Per-family RMSE curves
Also produces data/perovskites/parity_at_n230.png — scatter of
predicted vs SIESTA E_coh ... |
17e6985cef3a62c2a488133ab5a65050dcf0abeec2f55d1c0b068dfe37c44de6 | Python | 7,456 | 234 | import numpy as np
from typing import List, Tuple, Union
from Bio.Seq import Seq
from tqdm import tqdm
import torch
from vortex.model.model import StripedHyena
def prepare_batch(
seqs: List[str],
tokenizer: object,
prepend_bos: bool = False,
device: str = 'cuda:0'
) -> Tuple[torch.Ten... |
635acc04f0464d76c6575229f68cc7ec143d64dae07dbdede2e6a8409cb906c7 | Python | 7,456 | 209 | #!/usr/bin/env python
# ENCODE DCC bowtie2 wrapper
# Author: Jin Lee (leepc12@gmail.com), Daniel Kim
import sys
import os
import re
import argparse
import multiprocessing
from encode_common_genomic import *
def parse_arguments():
parser = argparse.ArgumentParser(prog='ENCODE DCC bowtie2 aligner.',
... |
eb18932454c95bf64b6d70325ea8a587a41a4e751987c3a4d9d5564e7d31da96 | Python | 7,456 | 229 | import os
import json
import neuralop
import torch
from torch.optim import Adam, SGD
from simulation_encoder.models.ae import AE
from simulation_encoder.models.vae import VAE
from simulation_encoder.models.base_nn import BaseNN
from simulation_encoder.utils.yaml_utils import load_model_yaml
torch.serialization.add_s... |
55672e098911d3a968841e4a251548b1b6a44ad9acf8ced1db5ff83461ca42d2 | Python | 7,458 | 213 | import logging
from argparse import ArgumentParser, Namespace
from typing import Any, List, Optional
from transformers import Pipeline
from transformers.commands import BaseTransformersCLICommand
from transformers.pipelines import SUPPORTED_TASKS, pipeline
try:
from fastapi import Body, FastAPI, HTTPException
... |
fc4d99867a28ca8802e39d2bc71d4f86a04b4ca5dcec266b96c300e41e0ec556 | Python | 7,459 | 214 | import logging
from argparse import ArgumentParser, Namespace
from typing import Any, List, Optional
from transformers import Pipeline
from transformers.commands import BaseTransformersCLICommand
from transformers.pipelines import SUPPORTED_TASKS, pipeline
try:
from uvicorn import run
from fastapi import Fas... |
88b80e56e202d8ec9e18783144e18440e3c371a251001625dae4bfb29f3b9f90 | Python | 7,460 | 193 | import logging
import os
import random
from typing import Dict, List, Optional, Tuple
import anndata
import lightning as L
import numpy as np
import torch
from joblib import Parallel, delayed
from scipy.spatial import KDTree
from sklearn.preprocessing import MinMaxScaler
from torch.backends import cudnn
logger = logg... |
12a999e1f7d63ab4d0c6415882140df4452a143bf3b8775920ec94e1aa81114a | Python | 7,461 | 290 | import argparse
import numpy as np
import csv
from copy import deepcopy
from sklearn.metrics import matthews_corrcoef, confusion_matrix, f1_score
def generate_pred(predict_results, i, slide, metric="max"):
results = predict_results[i*3:(i+1)*3]
if metric == "max":
pred = max(results)
elif metric ... |
4a9311f6f9c561e9a78deadf90b65be8bb4a8a2683799cadf2e5da8a230d76f3 | Python | 7,464 | 214 | import torch.nn as nn
import torch
class BasicConv(nn.Module):
def __init__(self,
in_planes,
out_planes,
kernel_size,
stride=1,
padding=0,
dilation=1,
groups=1,
relu=True,
... |
81bbf40053a81e7390e2f8a10c7b3c1c1fd935b0183d87e10e748071a8c6cb68 | Python | 7,465 | 176 | # _*_ coding: UTF-8 _*_
# Version information START --------------------------------------------------
VERSION_INFO = \
"""
Author: ZHANG YUBO
Version-01:
2019-10 Topology weighting for genealogies generated by ms using twisst
Version-02:
2019-11-04 Topology weighting for genealogies... |
ea2809d2d83f42d097cec1e416afb1ff1b50acf6a2199d6016d7402a4740a193 | Python | 7,465 | 139 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'UI/CorrRandomFrequencyUI.ui'
#
# Created by: PyQt5 UI code generator 5.5.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form... |
2d1b793bb7c1c46d35d4b66a71198f1d36716f1b48bd1b1596c06ed070662433 | Python | 7,467 | 184 | """Phase 1 smoke pipeline: site-percolation honeycomb at p_c, L ≤ 8.
Steps (all unrelaxed, single-point energies only):
1. For L ∈ {4, 6, 8}: sample N_realisations percolation clusters at p_c.
2. Compute xtb GFN2 single-point energy of each cluster (radical, no H).
3. Featurise each cluster with the OCE v1.0.0 ... |
9d1d9818e51f2d53503bbb9605ff87e1a3ae259715412798206e2d83bd247050 | Python | 7,467 | 139 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'UI\CorrDifficultySwitchUI.ui'
#
# Created by: PyQt5 UI code generator 5.5.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
For... |
db6e9bcadd9351782332064aa6e516c8227604cbb5c3b6ee7c33613683803a49 | Python | 7,467 | 242 | # -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup ------------------------------------------------------------... |
67ece71fec5ea09235aa6d2ce254b299e0b0c2a86dced5fb2f272ec9b624a6a6 | Python | 7,470 | 245 | from collections.abc import Sequence
from typing import Optional, Tuple, Union
import haiku as hk
import jax
import jax.numpy as jnp
import numpy as np
def _prepend_dims(x: np.ndarray, num_dims: int) -> np.ndarray:
return jnp.reshape(x, tuple([1] * num_dims) + x.shape)
def get_positional_features_central_mask_... |
a2cf724cda75c503077bd9f7888e515a1e26d76c1d189cb2c0544b6df105f60d | Python | 7,470 | 196 | import streamlit as st
import os
import base64
st.set_page_config(page_title="MSDA-Bench", page_icon="file.svg", layout="wide")
# ── Global CSS ────────────────────────────────────────────────────────────────
st.markdown('''
<style>
/* Refined spacing */
.block-container {
padding-top: 1.5rem !importa... |
3131ca22bff94824c1da448d9d6b53a7d4fee774758c50bb52ce0f6f499c3fa6 | Python | 7,473 | 214 | #!/usr/bin/env python3 -u
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
Translate pre-processed data with a trained model.
"""
import numpy as np
import torch
from fairseq import check... |
663e5432b51724b0268dd56fc66432aec82a1a73815449a9f873f1e6c8550772 | Python | 7,473 | 215 | import itertools
import numpy as np
from matplotlib.gridspec import GridSpec
from mdt.visualization.dict_conversion import SimpleClassConversion, IntConversion, SimpleDictConversion
__author__ = 'Robbert Harms'
__date__ = "2016-09-02"
__maintainer__ = "Robbert Harms"
__email__ = "robbert@xkls.nl"
class GridLayout:
... |
2aeca567fd2f30541f0bcbe7560352d4827b5895e24242ba9973dbe3a30f74ee | Python | 7,478 | 175 | #
# 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 .iadc import IADC
from simulator.backend import ComputeBackend
xp = ComputeBackend... |
e57e7015004b643c5d95740df182b1a373949d185ce6926976406fff9d293c26 | Python | 7,480 | 235 | #!/usr/bin/env python
# Author_and_contribution: Niklas Mueller-Boetticher; created template
# Author_and_contribution: Liya Zaygerman
import argparse
# TODO adjust description
parser = argparse.ArgumentParser(description="Method scanpy")
parser.add_argument(
"-c", "--coordinates", help="Path to coordinates (as... |
4d55fe1650b9f1ee882bc2c81b063c69eac4f1a346101f4441eaa284120f5b47 | Python | 7,481 | 217 | """Helpers for the DeepLabCut fin-tracking analysis (notebooks/02_fin_tracking).
Coordinate arrays are shaped `(n_frames, n_bodyparts, 2)` with the body-part order
`mouth, swim_bladder, tail_point_mid, tail_point_tip, left_pect_base, left_pect_tip,
right_pect_base, right_pect_tip` (swim bladder at index 5, tail mid at... |
db2bed9e054d03ce54e6a644592b5a41bde9a08d4af9c823f351ae4259d371e2 | Python | 7,485 | 225 | # -*- coding: utf-8 -*-
"""
Created on Fri Dec 17 08:13:09 2021
@author: jir
"""
import serial
import serial.tools.list_ports as s_ports
import time
import sys
timing_dbg = False
if timing_dbg:
import ctypes
winmm = ctypes.WinDLL('winmm')
winmm.timeBeginPeriod(1)
class sensornode:
"""Class t... |
90493b0d02c8765290af9d7efc5b0c1fa59080507497d3154b4be8aac8facc37 | Python | 7,490 | 209 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# NOTE: The purpose of this file is not to accumulate all useful utility
# func... |
dc8f9f101504e6697bc0fdff09d84cad942ca58dda9a791f151bd8e9d7941ad0 | Python | 7,491 | 220 | # Copyright 2020 The HuggingFace Team. 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 applicabl... |
bd4673f38bdb15f644167880fce9cd134ab7a337855b9285e048de69a44f1ed4 | Python | 7,492 | 200 | ## Modeified Code from https://github.com/TencentAILabHealthcare/scBERT
import torch
import torch.nn as nn
from operator import itemgetter
from torch.autograd.function import Function
from torch.utils.checkpoint import get_device_states, set_device_states
# for routing arguments into the functions of the reversible l... |
46419579abdea8bbedf3a162ba6dd2f8020368cece33655276d30cbd6f0a99f8 | Python | 7,495 | 178 | from abc import ABC, abstractmethod
from pathlib import Path
import subprocess
import pandas as pd
class Runner(ABC):
"""
Abstract base_input class for BEELINE GRN inference algorithm runners.
Subclasses must implement generateInputs, run, and parseOutput.
Attributes set here reflect the fields access... |
4543e16e5fd162ba935c8e7687059953503db1878189dfd33c0ecda3375428e9 | Python | 7,497 | 202 | from dataclasses import dataclass
from typing import Any, Dict, List, Mapping, Optional, Tuple, Union
import torch
import numpy as np
from .preprocess import binning
@dataclass
class DataCollator:
"""
Data collator for the mask value learning task. It pads the sequences to
the maximum length in the batc... |
6c9c89794da2c7a98c0ecc5253202186bc39cd9d0b7df3fc74789c47eb99b091 | Python | 7,509 | 255 | import torch
import torch.nn as nn
import torch.nn.functional as F
WVF_ENCODER_ARGS_SINGLE = {
"beta": 5,
"d_latent": 10,
"dropout_l0": 0.1,
"dropout_l1": 0.1,
"lr": 5e-5,
"n_layers": 2,
"n_units_l0": 600,
"n_units_l1": 300,
"optimizer": "Adam",
"batch_size": 128,
}
class Simp... |
93b828dd83ea9914c74e79caa63b9cfe60667e91edf8eddcbbf7f5ac0a8c1e71 | Python | 7,510 | 147 | import os
import sys
import pandas as pd
class CreateFineTuneDataset():
"""
Class to prepare datasets for fine-tuning a BERT model with different loss functions
by transforming document pairs and relevance labels into a format compatible with
specific loss function requirements.
"""
def __init... |
1220e99182202a3e8419ea5312220a4c3ac2332dad450c09a3f238a2a9d86275 | Python | 7,511 | 168 | # -*- coding: UTF-8 -*-
"""The elim GOEA algorithm: decorrelate the GO graph by eliminating genes.
Alexa A, Rahnenfuehrer J, Lengauer T (2006). "Improved scoring of functional
groups from gene expression data by decorrelating GO graph structure."
Bioinformatics 22(13):1600-1607.
Ported from topGO's `.sigGroups.elim` ... |
779f667ad433eafc967d7c22cbbb6015902490809185b73f14dbfe3a9d5f496c | Python | 7,511 | 216 | from __future__ import print_function
import argparse, os, copy
import numpy as np
import torch
import torch.nn as nn
from tqdm import tqdm
import prismnet.model as arch
from prismnet.utils import log_print, metrics, datautils
def train(args, model, device, train_loader, criterion, optimizer):
model.train()
... |
e10cac7969cdfa343c9e3c6203ca0d6afa4fba519bb799dbae147ab4d696fd05 | Python | 7,511 | 253 | import pandas as pd
import numpy as np
import os
import sys
from pathlib import Path
from sklearn import metrics
from torch.utils.data import DataLoader, TensorDataset, Dataset
from tqdm import tqdm
from sklearn.metrics import precision_recall_curve, auc, mean_squared_error
import torch
import torch.nn as nn
impor... |
253a0d5d33537cd0990295ef061a003bc3f668c97b39a0412fc019bc5ea99f27 | Python | 7,512 | 210 | __author__ = 'heroico'
import logging
import numpy
import math
import Exceptions
import KeyedDataSet
BETA_Z = "beta_z"
BETA_Z_SIGMA_REF = "beta_z_and_ref"
METAXCAN = "metaxcan"
METAXCAN_FROM_REFERENCE = "metaxcan_from_reference"
def ZScoreScheme(name):
scheme = None
if name == BETA_Z:
scheme = _BetaZ... |
2f3c22dd605f98d6ce33c3494581514fa3393482587de72f443edd62c9ddc99c | Python | 7,512 | 210 | #!/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 use... |
f9201f7517ffb45408e7de6a2429a9c0dff95ec11b3683133f4e8a983afe25ef | Python | 7,513 | 184 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from os.path import join
from builtins import object
import numpy as np
from tractseg.libs.system_config import SystemConfig as C
from tractseg.libs import exp_utils
from tractseg.libs import data_utils
from ... |
5a126e67295a8bc408cbea2a7cb5c0009542abe280ecc07acee192f6df810c54 | Python | 7,516 | 155 | #!/usr/bin/env python3
"""Duas coisas que um parecerista vai pedir: descritor externo e curva de aprendizado.
(1) MAGPIE. A linha de base do artigo e o proprio 1F (contagem elementar ponderada
por energias orbitais). Um revisor tem razao em perguntar se ela nao e um
espantalho. Magpie (Ward et al., npj Comput.... |
f9e0db7e40cc98d2bc9b291611015c676c2144e9efdce551a3ba15c4d8d40749 | Python | 7,519 | 196 | # /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 time
import torch
import CBIG_pMFM_basic_functions_main as fc
import warnings
def get_init(myelin_data, gradient_data, highest_order, init_p... |
9e504b61136db6e2ac6bcd12b2252f6f6dc1552833255e41d851d2277a735dce | Python | 7,520 | 180 | """Contract tests for python/emd.py.
EMD's contract is short and completely checkable:
1. It DECOMPOSES. The first IMF is not the input signal.
2. It RECONSTRUCTS. sum(imfs) == input, to machine precision.
3. Each IMF is oscillatory -- roughly equal numbers of extrema and zero
crossings, mean near zero.
... |
579fa0c3102a429eec84000b83d1f9d695be0cd965f4b07c353527f1d72fdd9f | Python | 7,521 | 230 | from typing import Dict, Set, Tuple
import networkx as nx
import pandas as pd
from BLEval.evaluator import Evaluator
from BLEval.data import EvaluationData, DatasetGroup
def _build_digraph(edges: Set[Tuple[str, str]]) -> nx.DiGraph:
"""
Build a directed graph from a set of edges, excluding self-loops.
... |
3c136e41913e71b6e69676e0a84059174626b01f1719eacce49f773d7025ffab | Python | 7,525 | 209 | # -*- coding: utf-8 -*-
"""
Benchmark of 23 deep-learning architectures on ear-EEG.
Subject-specific stratified k-fold cross-validation, applied independently
within each participant, recording day and task pair. One row is written per
(seed, condition, subject, fold); every number reported in the manuscript is
derive... |
ee0a79de3494176254d81a8ba7eeff39c412f36286c090e8e054efe688f6350d | Python | 7,528 | 199 | """
cli.py — command-line entry point for the crossda cross-session EEG pipeline.
Usage:
crossda
crossda --config my_config.yaml
crossda --datasets bnci004 --mode smoke
Equivalent module form: ``python -m crossda``.
"""
from __future__ import annotations
import argparse
import logging
import os
from pathlib i... |
0446d03acf194004860bf237919fb09cd41f3104f351a46548818d3f86bbc6be | Python | 7,529 | 183 | import logging
import shlex
import sys
from pathlib import Path
from unittest.mock import patch
import pandas as pd
import pytest
from gsMap.main import main
def parse_bash_command(command: str) -> list[str]:
"""Convert multi-line bash command to argument list for sys.argv"""
cleaned_command = command.repla... |
70be897254545228f073cc022fef98a1c51aaeb37ab4254896ceb8693242f775 | Python | 7,533 | 224 | # 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... |
98be066d00a0aaa9ad1f21b436a71a377fb5acdc4d40493dcd19a298432a3a3d | Python | 7,537 | 149 | # 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 options
def get_reranking_parser(default_task="translation"):
parser = options.get_parser("Generation and reranking"... |
eb6ace106ad9738217eb00599888f252275572154b83ab5c105b62a3ec5b5fd3 | Python | 7,542 | 232 | import os
import pickle
from itertools import islice
import numpy as np
import pytest
import torch
from torch.utils.data import DataLoader, TensorDataset
import scvi
from scvi.data import synthetic_iid
from scvi.external import GIMVI
from scvi.external.gimvi._task import CyclicMultiDataLoader
def test_saving_and_lo... |
a63ad8a12d8a59a091978d046e3aff1700a1f1aeca9959a765acfd44b2dfafbf | Python | 7,545 | 166 | """
This script simulates an agent moving in a spatially heterogeneous environment.
Author: Jonathan Gant
Date: 07.05.2025
"""
# imports
import numpy as np
import h5py
import os
from scipy.ndimage import gaussian_filter
class Environment:
def __init__(self, x_min, x_max, sigma_sp, n_bins=50, scale=1, seed=0, zsco... |
8507423f169208c61199c0e186b169b738cecf9edfa596372c72d5828af0c2de | Python | 7,547 | 187 | """Deprecated compatibility shims for :mod:`pgmpy.structure_score`.
This module is deprecated and will be removed in v2.0. Every class defined
here is a thin wrapper that delegates to its canonical implementation in
:mod:`pgmpy.structure_score`; no scoring logic lives in this module anymore.
Notes
-----
- ``Structure... |
c1b338ff624c598282d73a7815bb723f128e45e56ae4d0b91d764827280be8f0 | Python | 7,550 | 212 | import pytest
import torch
import scvi
from scvi.data import synthetic_iid
from scvi.model import SCVI
from scvi.train import TrainingPlan
from scvi.train._constants import METRIC_KEYS
from scvi.train._trainingplans import (
_compilation_fell_back,
_compute_kl_weight,
_dynamo_frame_counts,
)
@pytest.mark... |
234440222745ce2372df9bff1ad5c36953043f7c61c1c42292679955e1784984 | Python | 7,554 | 186 | from __future__ import annotations
from copy import deepcopy
from typing import TYPE_CHECKING
from unittest import mock
from poetry.factory import Factory
from poetry.mixology.version_solver import DependencyCache
from tests.helpers import MOCK_DEFAULT_GIT_REVISION
from tests.mixology.helpers import add_to_repo
if ... |
15e76fa2f52cd8d6e56e419038562c8ef8f68c26a6567f81f57b7054d652e9c6 | Python | 7,559 | 239 | import os
from dataclasses import dataclass
import torch
import torch.utils.cpp_extension
cuda_source = """
#include <ATen/core/TensorAccessor.h>
#include <ATen/cuda/CUDAContext.h>
#include <torch/extension.h>
#include <vector>
#include <limits.h>
#include <cub/cub.cuh>
#include <iostream>
using namespace torch::ind... |
58a63b3b3924804fef7cf78304a4d622953849e3027808a0a85362625449e6fe | Python | 7,560 | 200 | """Compute SIESTA-PBE single-point energies for 15 binary phases needed
to build the SIESTA decomposition energy
E_decomp(ABX3) = E_coh(ABX3) - E_coh(AX) - E_coh(BX2)
so that it becomes directly comparable to Mannodi's decomposition energy
(currently reported as VASP-PBE and VASP-HSE06). Without this conversion,
... |
ab7271f8dbb876dbc5e2010e2d88b086088aada096f04149436d315a4f256aac | Python | 7,562 | 188 | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import re
import urllib
import warnings
from argparse import Namespace
from pathlib import Path
import torch
import fm
def _has_regressi... |
c9847b8fe6880fe7c0a9c83b7ec8ca764085080e7a2834c0b05fb832625ac2c7 | Python | 7,562 | 160 | """This is the script run by nox session "test-data-generate".
It makes all the 'generated' test data, i.e. files created by vak,
It's called 'generated' test data to distinguish it from the
'source' test data, i.e., files *not* created by vak:
the input data such as audio and annotation files that are used
when vak *... |
e0a2e7888fa5fd4fb377d6025b5f0bd4786955d8b680214d1d95d43f2524646d | Python | 7,565 | 200 | import os
import sys
os.environ['WANDB_DIR'] = 'ADD YOUR DIRECTORY'
import shutil
import math
import wandb
import numpy as np
from Images.utils import load_HVM8data
from baseModels.utils import get_model#, get_device, get_BrainScoreMapping
import torch
from enum import Enum
from analysis.metrics import dPrime_model
im... |
21f3f4c705347d726392c0ecac4e606ef242b63f3f70041d07ba3329cbc33834 | Python | 7,566 | 212 | from typing import Any, Optional
from collections import defaultdict
import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision.models import resnet18, ResNet18_Weights
from simulation_encoder.models.base_cnn import BaseCNN
from simulation_encoder.logger import Logger
class Pretraine... |
cf4b8ba4036b8317292f65c256a2fb07596a69a3da8456e24221cc3fa3cd85f7 | Python | 7,566 | 219 | """
Knowledge retrieval module for RAG-GNN.
Implements document retrieval based on node embeddings and semantic similarity.
"""
import numpy as np
from typing import Optional, List, Dict, Union, Literal
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.preprocessing import StandardScaler
clas... |
58106e476eb700aa18988f52cc1a12f8f16e5a8e03a9da2de8c3ca166ae9f86b | Python | 7,569 | 201 | from itertools import permutations
from typing import Dict, List, Tuple
import numpy as np
import pandas as pd
from scipy.stats import spearmanr
from BLEval.evaluator import Evaluator
from BLEval.data import EvaluationData, RunResult
def _to_series(df: pd.DataFrame) -> pd.Series:
"""
Convert a ranked-edge D... |
287784eec42c46bfcdf19fc56186fcfc8d0a1f6e669cb648fa817fd7cc6d6951 | Python | 7,570 | 173 | """Helper functions for moving and modifying configs"""
import logging
import pathlib
import shutil
import tomlkit
import vak.cli.prep
from . import constants
logger = logging.getLogger(__name__)
def copy_config_files():
"""copy config files from setup to data_for_tests/configs
the copied files are the o... |
f23015abb97847bf5248554b281f0ae6234663fb177aaf428a16055300337712 | Python | 7,571 | 170 | #!/usr/bin/env python3
"""Gera os inputs da varredura de EOS + manifest.csv + pseudos.
Uso:
python3 gen_inputs.py # 12 compostos x 9 x 2 = 216
python3 gen_inputs.py --spins nosoc # so o controle escalar (108)
python3 gen_inputs.py --only CsPbI3,CsGeI3 # subconjunto
... |
8cb29ef4f233e1db15ce0990816f5df4a2508a09901c947732711bc20ae1af69 | Python | 7,572 | 219 | import numpy as np
import os
from scipy.io import loadmat
import matplotlib.pyplot as plt
import cv2
from sklearn.linear_model import LinearRegression
import json
import matplotlib.cm as cm
# Identical logic as L-DOPA (Neveu et al.)
root_path = "data_folder"
data_paths = [
"/23-12-11/002_filtered.mat", "/24-01-04... |
bd7ccb53fa2aaf4dbc40b85a0359af392d76194deeb484e63e9f4aafbf5a3a22 | Python | 7,572 | 244 | from __future__ import annotations
import importlib.metadata
from pathlib import Path
from typing import TYPE_CHECKING
from typing import Any
from packaging.utils import canonicalize_name
from poetry.core.constraints.version import Version
from poetry.core.utils.helpers import module_name
from poetry.core.utils.patt... |
eff9fdfbbc63396ebe0ce84d6fe34ef8b05563920602f95f36eac2fd8ad8130a | Python | 7,574 | 194 | """Refit OCE on SIESTA cohesive energies (E_coh = E_total - Σ E_atom_ref).
This removes the per-element pseudopotential offset from SIESTA's absolute
total energy, giving per-atom RMSE in interpretable meV/atom.
Pipeline:
1. Load atom_refs.json + siesta_szp_results.json
2. Compute E_coh per perovskite
3. Load f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.