sha256
stringlengths
64
64
language
stringclasses
27 values
size
int32
1
491k
lines
int32
1
21.8k
content
stringlengths
1
200k
38a59ea5ca76a7402319f114c48fdb3ce6e2ce3f933dfc387bebbcee05d01aed
Python
5,405
185
import argparse import json import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import os from pathlib import Path import random import sys import tensorflow as tf from tensorflow.keras.models import load_model import transistor_extract as...
e6d240a7f137033c16185cf2396015e572d5a71ff2780cb6e0518b76fd7538a4
Python
5,405
141
# # 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 .idevice import IDevice from .generic_device import ( UniformIndependentDevice, ...
6f45abb0281e1c37748be26d63a1d4dae1f7ec0329cf19f7bf09ac7924d2b55f
Python
5,406
132
from __future__ import annotations import torch import torch.nn.functional as F from torch.distributions import Distribution, constraints from torch.distributions.utils import broadcast_all from scvi.distributions._negative_binomial import _gamma, _lgamma_fn from scvi.distributions._utils import _needs_cpu_detour c...
915e8fa846edb0529aa0668e22b6be38535b5fc11df6dddc60a4228013371cc6
Python
5,406
134
import datetime import logging from copy import deepcopy from functools import partial from os import makedirs from os.path import join, exists from posixpath import abspath import numpy as np import pandas as pd import yaml from sklearn.model_selection import LeaveOneOut from data.data_access import Data from model....
70813e3011a3652e527aafb531d20a227678ecebab785a59b72e44951d957282
Python
5,407
126
import os import pandas as pd import numpy as np from BLRun.runner import Runner class SCODERunner(Runner): """Concrete runner for the SCODE GRN inference algorithm.""" def generateInputs(self): ''' Function to generate desired inputs for SCODE. If the folder/files under self.input_d...
f632715fac78d0c236cb68cdf047ffc5069d14b9da63b8a158c7e901dca895d3
Python
5,407
152
#!/usr/bin/env python # # Kui Xu, xukui.cs@gmail.com # 2019-02-25 # ref smoothGrad import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import grad,Variable import numpy as np class SmoothGrad(object): def __init__(self, model, device='cpu', only_seq=False, train=False, ...
d340e7eb5a129926782ad62a5a9aee580eb526e47cb75dfca06295444adf6f17
Python
5,411
152
"""Console logging for the entry points. The library installs nothing on import: deciding where anyone else's records go is the same first-writer-wins hazard `runtime.configure` exists for. `configure` puts one handler on the `d3text` logger, and on `brenda_references` (the dependency `d3text.datasets` imports for the...
9d93f44d3b6bceeb44c6093ac36ca17e7ff296a179ddc124357f2e72b34bba4e
Python
5,412
154
"""A dataclass that represents metadata associated with a dimensionality reduction dataset, as generated by :func:`vak.core.prep.frame_classification.prep_dimensionality_reduction_dataset`""" from __future__ import annotations import json import pathlib from typing import ClassVar import attr def is_valid_dataset_...
8aec12562d29ce9324ea45f539137e7e4c05d408484c1d0c7e752939272864ad
Python
5,413
159
import logging import pickle from dataclasses import dataclass from pathlib import Path from typing import Dict, Optional, Tuple, Union import numpy as np import torch from spacestream.core.constants import (IT_SIZE, RETINA_SIZE, V1_SIZE, V2_SIZE, V4_SIZE) from spacestream.util...
a4db99b13b20cd817a5b1af163ddb4b32d073f57dbd6ea3db561f12da1e34b22
Python
5,413
157
from typing import List, Tuple import pytest from pymatgen.core import Element, Structure from mattergen.evaluation.utils.structure_matcher import ( DefaultDisorderedStructureMatcher, DefaultOrderedStructureMatcher, check_is_disordered, ) @pytest.fixture def test_structures_for_matcher() -> List[Structu...
2bfbf4ca3fbe24f0b45f82ab84e3fb620b7e3aa55ac7c437ba3972d6ab3b8f9b
Python
5,414
150
import asyncio import itertools import logging import math from collections.abc import Callable, Mapping from aiotinydb import AIOTinyDB from aiotinydb.storage import AIOJSONStorage from tinydb import where from tqdm import tqdm from apiadapters.straininfo import ( AsyncStrainInfoAdapter, normalize_strain_nam...
d9d9d64bdf6380ed5e2bd7cff31d6bb8c0078c22d17a5163ceb52df1e23cc1ce
Python
5,414
119
import torch.nn as nn import torch import torch.nn.functional as F #from dcn_v2 import DCNv2 from modelR.layers.deform_conv_v2 import DeformConv2d, DeformConv2d_offset class hsigmoid(nn.Module): def forward(self, x): out = F.relu6(x + 3, inplace=True) / 6 return out class MTR_Head1(nn.Module): ...
7caebc175b44b3c727fc50420ada1a6a9500f3e4ce9e2839f69205437aa85e7a
Python
5,415
177
#!/usr/bin/env python # # Copyright 2006, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list...
0e0ea17c6fd1082b37189e27a302b3f70d2b0227e2c4ff0da35c31c0e2b4ef9c
Python
5,419
200
from __future__ import annotations from typing import TYPE_CHECKING import pytest from poetry.repositories.pypi_repository import PyPiRepository if TYPE_CHECKING: from cleo.testers.command_tester import CommandTester from poetry.config.source import Source from poetry.poetry import Poetry from tes...
fa3ef7573df06cd6f5f8999ead6d9d998883bb32c5c33ae8614e62d8fcde3a0d
Python
5,420
161
"""Training losses follow the loss-weight ramp; selection does not.""" import pytest import torch from torch.utils.data import DataLoader from d3text.models.config import ModelConfig from d3text.models.entity_linking import BrendaClassificationModel from d3text.models.ete import ETEBrendaModel from d3text.models.mode...
74efa8ff153df4f4e1394c43590f30c3e5e74d32d478d6a58e1f98ccdcfff90a
Python
5,422
170
# # 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...
5a69bef73c416af236538beb311a8256760ba29556a46b71cab66ba16ec90f25
Python
5,423
156
"""Controller for graph helper operations used by plot orchestration.""" from __future__ import annotations import pandas as pd from src.gui.framework.graph_plotter import ( convert_time_data, draw_behaviour_boxes, retrieve_behaviour_records, set_ax_tick_spacing, ) from src.gui.framework.graph_plotte...
a0cab4ded09f5882109e54563b88814e31a4c725f2ea88b5f3bbf77925d87941
Python
5,423
196
import os import nipype.pipeline.engine as pe from fetpype.pipelines.full_pipeline import ( create_rec_pipeline, ) from fetpype.utils.utils_bids import ( create_datasource, create_bids_datasink, create_description_file, ) from fetpype.workflows.utils import ( init_and_load_cfg, check_and_updat...
938dfcda6350537f84d69d0b5f8050cb881cfef136d672e89298c9ad5a4dabd8
Python
5,427
114
import pandas as pd import networkx as nx def get_segment_iax(segment, df): """ Returns a DataFrame containing the axial current values for a specific segment. This function extracts the axial currents associated with a specified segment. It handles both cases where the segment is a reference (ref) ...
439fa45bf67ae5834115e4468bc90481c23da272ce40192a0d9cc37a2d9bf1c5
Python
5,428
171
# %% """Generate Lorenz and Rossler signal datasets. The training and analysis scripts expect paired files named ``Chaos_Signals/data1_<id>.npy`` and ``Chaos_Signals/data2_<id>.npy``. Here ``data1`` is the normalized Lorenz trajectory and ``data2`` is the normalized Rossler trajectory. Each output has shape ``(data_s...
7da30e07edc611e69304430b7ead813c461ddf238cff4f2b26de24ac96978a57
Python
5,428
147
import unittest from unittest.mock import MagicMock from simulation_encoder.runner import Runner from simulation_encoder.dataclass.param_sets import ModelParams, DatasetParams def _make_model_params(name="test_model", model_type="AE"): """Minimal ModelParams for tests that don't need a real model instance.""" ...
5144bae6053bc6e7db2399e924e022311ca62516361d819779c30defa07a7225
Python
5,429
151
from abc import ABC, abstractmethod import numpy as np import pandas as pd import rich from scvi._types import AnnOrMuData from scvi.data import _constants from scvi.data._utils import get_anndata_attribute class BaseAnnDataField(ABC): """Abstract class for a single AnnData/MuData field. A Field class defi...
7a1b39615dec7d3516ea5f3fd0390317792c3ff35005a1b7df90bf52b844eb54
Python
5,430
125
# coding=utf-8 # Copyright 2019 Facebook AI Research and the HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. 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 Licens...
b43a89121d9c262a0550d663251e557bb3ce67c1675f2c520d31a2505af2ad7d
Python
5,431
126
# coding=utf-8 # Copyright 2019 Facebook AI Research and the HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. 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 Licens...
7fc606d63593fa0b5551e9857d0c5f05e468d075a323ebc713292beb7ee5f4c9
Python
5,432
156
"""Whether a pass actually waited on prefetched layer-boundary reads. `_resolve_layer_boundary_cached` (`src/d3text/models/base.py`) blocks each batch item's `store.get` future on `.result()`; nothing recorded how long that took, so a run could not say whether the reads keep ahead of the GPU. This pins `log_pass_stats...
b271e7eb0f4db0f750828e97ca10998e559d20242d5a947307933c2f76a05ac1
Python
5,432
114
import pandas as pd import networkx as nx def get_segment_iax(segment, df): """ Returns a DataFrame containing the axial current values for a specific segment. This function extracts the axial currents associated with a specified segment. It handles both cases where the segment is a reference (ref) ...
d824e9244568b7f677289844c20a2ac5758ebd98c2ab9be1fceb4ad75fecb760
Python
5,433
130
import torch import numpy as np import math import copy from scipy.interpolate import interp1d from Survival_CostFunc_CIndex import neg_par_log_likelihood def dropout_mask(n_node, drop_p): '''Construct a binary matrix to randomly drop nodes in a layer. Input: n_node: number of nodes in the ...
613ad01787617de9c6e6a6eb67628c55e723294f44ffbb8fd92ea0234cd3d856
Python
5,434
143
import pandas as pd import numpy as np import matplotlib.pyplot as plt from scipy.spatial import distance_matrix """ This function computes nearest-neighbor distances (NND) and furthest-neighbor distances between chromatophores based on epicenter coordinates stored in a CSV file. The CSV must include `chrom_id`, `epic...
970db41335c60141a7bc1757d75d94d67cbd581fb82b8e277d6faf2a561bf701
Python
5,434
90
import importlib.util import json import os from pathlib import Path import subprocess import shutil import sys import tempfile import unittest import zipfile ROOT = Path(__file__).resolve().parents[1] spec = importlib.util.spec_from_file_location("prepare_release", ROOT / "tools/prepare_windows_release.py") prepare_r...
e27b652d91e60a00d4b022c9e21495d6401b956e974adce6c56930a64e54adc8
Python
5,435
139
import os import re import argparse from bs4 import BeautifulSoup import warnings import logging logging.basicConfig(filename='../monq/logging/annotation.log', filemode='w', level=logging.DEBUG, format='%(asctime)s %(levelname)-8s %(message)s', datefmt='%Y-%m-%d %H:%M:%S') def format_input(input...
dde7bb355e86949c03e77bc185cd2f11cd09e0e80ed517a2efc8dbd63402a674
Python
5,442
66
#!/usr/bin/env python import logging import sys import argparse from version import VERSION as __version__, MASTHEAD import gsa_mixer.cli import mixer_dev.cli import bivar_mixer.figures import common.utils_cli if __name__ == "__main__": logging.getLogger().setLevel(logging.INFO) parser = argparse.ArgumentPa...
85424efdbb8994793c032dc97fa88af56e2cf0e44262251d7f5a1722dd27c1e0
Python
5,443
123
from PyQt5.QtWidgets import * import os from PyQt5.QtGui import * from PyQt5.QtCore import * import cv2 as cv import numpy as np import sys from scipy import stats class tTestMap(QWidget): def __init__(self): super(tTestMap, self).__init__() self.setFixedSize(400,240) self....
9b39cc6e4968de563f065bd9ca0b3fba9065f5b8ed384ae636eca7ea0aa9ecfb
Python
5,443
128
# %% """Formal statistics for the selective-ablation effect (Reviewer 1, point 5). For each output (Lorenz, Rossler) and each training condition (MI+L2, L2-only), ablation is evaluated on the same models for both the primary and the non-primary subgroup. This script quantifies the selective-damage signature: 1. gap(k...
10c8eae0fbbd6638080ea2ec5088ca7030b2c56895531dbdaf238ba85dd0effb
Python
5,449
172
#!/usr/bin/env fbpython # (c) Meta Platforms, Inc. and affiliates. Confidential and proprietary. import contextlib import logging import unittest from io import StringIO from unittest.mock import MagicMock, patch import torch from fairseq import checkpoint_utils, data from omegaconf import OmegaConf def mock_traine...
bfffa671f3361f50c3f201cdcae409b5819bb6411dd4146175eaccf0d12421bb
Python
5,450
153
# 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 sys import torch from fairseq import utils class SequenceScorer(object): """Scores the target for a given source sentence.""" ...
4d8b418698cbb4fb6cb0ee92526af7e0b866fcfd067c7f1115b853cd32f1d402
Python
5,451
144
"""File discovery, filename parsing, and CSV loading helpers. Experiment files follow the naming convention `DATE-YYYY-MM-DD_TIME-HH-MM-SS_..._fish-N_Ddpa_<genotype>_..._tracking-data.csv`. """ import os from datetime import datetime from pathlib import Path import numpy as np import pandas as pd def find_files(fo...
27e55ed9d74b0f59269a805302549e8693955bb69f27b2ed3786b71465849e3c
Python
5,452
197
# %% from pathlib import Path import pickle import matplotlib.pyplot as plt import numpy as np from scipy.stats import t # %% # ================================ # Settings # ================================ INPUT_DIR = Path(".") OUTPUT_PATH = Path("Fig/dropout_robustness_primary_nonprimary.pdf") OUTPUT_PATH_RIGHT_LE...
73eb177e66ea6fa555fc8395b0e81c07937ed1bdcb57900e9e6bae44f3a8e1ba
Python
5,461
143
import math import warnings from typing import Optional, cast, List from torch import Tensor from torch.optim import Optimizer from torch.optim.lr_scheduler import _LRScheduler, CosineAnnealingLR, _enable_get_lr_call class Lin_incr_LRScheduler(_LRScheduler): def __init__(self, optimizer, max_lr: float, max_steps...
ba43c13819b95251576330b266605c85eb3c3066d6785a3f430036dd821add4e
Python
5,461
146
"""Function that evaluates trained models in the parametric UMAP family.""" from __future__ import annotations import logging import pathlib from collections import OrderedDict from datetime import datetime import lightning import pandas as pd import torch.utils.data from .. import models from ..common import valid...
349ed8f6e0e699a254e332e88977bd87b737ae407b2c60a591d36ccaf54bafbb
Python
5,465
138
import unittest from unittest.mock import patch from pyecharts import options as opts from pyecharts.charts import BMap from pyecharts.globals import BMapType, ChartType BAIDU_MAP_API_PREFIX = "https://api.map.baidu.com/api?v=2.0" FAKE_API_KEY = "fake_application_key" TEST_LOCATION = ["London"] TEST_VALUE = [1] cl...
1fa0d55a7dc143cf30c91c50f6e3246c7d21ef36c04a3d3b93e72996d1133a3b
Python
5,467
142
import numpy as np import cv2 def rotate_2d_vector_array(va,angle,axis=0,rad=True):#len along 'axis' should =2, transform vector to a newcorr system rotated with angle assert va.shape[axis]==2 #va_r=np.copy(va) X=np.take(va,0,axis=axis) #print (X) Y=np.take(va,1,axis=axis) #print (Y) ...
1ff28f88dd9d3e82ea328456a8e8db889818fabb0b81aa9bc75be1b3ff287581
Python
5,469
136
"""High-level function that evaluates trained models.""" from __future__ import annotations import logging import pathlib from .. import models from ..common import validators from .frame_classification import eval_frame_classification_model from .parametric_umap import eval_parametric_umap_model logger = logging.g...
6d57039517f07d942862e3150440946780176abf2ea2cd9e578e0c5726884dfa
Python
5,469
139
import torch import numpy as np import os from networks.cnn import BINND, BINNDLite from utils.paths import ROOT_DIR MODEL_PATH = f"{ROOT_DIR}/inference_demo/BINND.pt" # Path to the pre-trained model file. Choose between BINND.pt or BINNDLite.pt MAX_SEQUENCE_LENGTH = 20 # The current implementation only supports sequen...
d84f8e9e5b520b8ee476b4b796452e7039b7594cf54134ae258e24f7f5a2462d
Python
5,475
158
from __future__ import annotations from typing import TYPE_CHECKING import pytest from poetry.factory import Factory from poetry.puzzle.provider import IncompatibleConstraintsError from tests.mixology.helpers import add_to_repo from tests.mixology.helpers import check_solver_result if TYPE_CHECKING: from poetr...
5c6063ce3170d2df52c0a11f651a6166bd7e0d27040deafd4b97212578c2560c
Python
5,476
153
import argparse import subprocess import torch import numpy as np import biotite.structure.io as bsio from Bio import SeqIO from Bio.Seq import Seq from Bio.SeqRecord import SeqRecord from transformers import ( AutoConfig, AutoModelForCausalLM, AutoTokenizer, EsmForProteinFolding, set_seed ) from e...
dd80aac1304af2f2fa41da5340d7d9dc3f75017b75deec620306dc9aa2442868
Python
5,476
141
import logging import tempfile import unittest from pathlib import Path from GMXMMPBSA.fake_mpi import MPI as FakeMPI from GMXMMPBSA.exceptions import GMXMMPBSA_ERROR, MMPBSA_Error from GMXMMPBSA.logging_utils import ( enable_file_logging, format_command_line, setup_logging as _setup_logging, ) from GMXMMP...
1cd05ec2c8cbef2d02b2b0a05f8e7eb8df335bd2a870870d5c4f2e8b94cb7a0b
Python
5,481
150
import asyncio import itertools import logging import math from collections.abc import Callable, Mapping from aiotinydb import AIOTinyDB from aiotinydb.storage import AIOJSONStorage from tinydb import where from tqdm import tqdm from apiadapters.straininfo import ( AsyncStrainInfoAdapter, normalize_strain_nam...
9d7281d6753c89f7b0a20b49b1b3b05983c7299856370f1a499a3c8f5093b9a4
Python
5,482
125
from pathlib import Path import numpy as np import pandas as pd import thermodynamic_consistency_diagnostic as diag def test_partition_helpers_use_gas_to_water_direction(): x = diag.aqueous_mole_fraction_from_molality(1.0) assert np.isclose(x, 1.0 / (55.508 + 1.0)) lower_solubility_index = diag.gas_to_...
3e7c4d86fb7dff29b9a95088dec74f931430b39a26c1234e603086fc6de2554b
Python
5,484
162
import os import numpy as np import pandas as pd import pytest from scipy import stats from pgmpy.ci_tests import FisherZ, Pearsonr from pgmpy.factors.continuous import LinearGaussianCPD from pgmpy.models import LinearGaussianBayesianNetwork @pytest.fixture def fisher_data(): rng = np.random.default_rng(seed=42...
c30a9f9d175088c5228de36a29c8cc5770fd1f045d458d579f1196e53791d8ab
Python
5,484
113
import matplotlib.pyplot as plt import numpy as np import igraph as ig import networkx as nx import os import sys import pandas as pd sys.path.append('..\\src\\') from read_graph import read_graph, k_core_weights, display_graph, display_graph_3d from utils import get_category_indices labels = ["G1", "G2", "G3", "G4", ...
acc3217248e60d1a7ef18cd5935eda2bdd6dd61d22b3763ead8340d90a7bfe82
Python
5,486
128
import pytest import vak.config class TestConfig: @pytest.mark.parametrize( 'tables_to_parse', [ None, 'prep', ['prep'], ] ) def test_init_with_real_config( self, a_generated_config_dict, tables_to_parse ): ...
4f3905a7b7abf0ccae64cc54abe05eaa4a86e60158aae0acf0bf084e4808aab4
Python
5,487
140
"""Check that the shipped datasets match the cached benchmark predictions. Why this exists --------------- The training scripts locate their inputs with ``find_dataset_file``, which searches a fallback chain:: $HIPPIE_DATA_ROOT/<dataset>/<file> ./datasets/<dataset>/<file> ./datasets_hippie/<dataset>/<file...
083210554c63316c039a11379c5975107fe1b73fc3a8d370803ac1b8d6c4ebd2
Python
5,495
103
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'optimization_extra_data_add_protocol_map_dialog.ui' # # Created by: PyQt5 UI code generator 5.10.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_AddProtocolMapDialog(object): ...
c545fc5acebc19c63de4118bc493be80f0d11cc447c2396dde428fe1170fc75f
Python
5,496
158
import networkx as nx import pytest from pgmpy.base import SimpleCausalModel def test_simple_string_variables(): model = SimpleCausalModel(exposures="X", outcomes="Y", confounders="Z", mediators="M", instruments="I") assert set(model.nodes()) == {"X", "Y", "Z", "M", "I"} expected_edges = {("Z", "X"), ("Z...
395abd4479239407308c3f383814861679d475ef672c671a03d612e051ba7004
Python
5,500
100
#!/usr/bin/env python3 """Reviewer point 2: add an explicit methylation-compartment flag to Supplementary Table S2 and run the promoter-only sensitivity analysis. Each of the 82 inverse-concordant genes is classified by the source of its methylation call: - mCSEA promoter-region enrichment (promoter-anchored, consis...
172d77f55d805a704af558bb7f38205f728728d2e5a4c91e1472c4f3128815ad
Python
5,501
11
import numpy as np import pandas as pd cn = {'P':0,'M':1,'A':2,'B':3} cn_ = {0:'P',1:'M',2:'A',3:'B'} chain_1_hot = np.eye(4) b50 = {'A': np.array((5,-2,-1,-2,-1,-1,-1,0,-2,-1,-2,-1,-1,-3,-1,1,0,-3,-2,0)),'R': np.array((-2,7,-1,-2,-4,1,0,-3,0,-4,-3,3,-2,-3,-3,-1,-1,-3,-1,-3)),'N': np.array((-1,-1,7,2,-2,0,0,0,1,-3,-4,...
420dfc8260aa27f54fe1336b1a82bec9178eadaa08d647a404b3df12d239b9c7
Python
5,504
152
# -*- coding: utf-8 -*- """ Created on Thu Feb 6 14:42:30 2025 @author: hanna """ from tqdm import tqdm import numpy as np from sklearn.decomposition import FactorAnalysis from sklearn.model_selection import cross_val_score from sklearn.model_selection import KFold def perform_cv(data, n_components, n_splits, n_...
d1d4caed52fe9fe061d015ef3c2b29521b716894b07e28dac3c7d27e6d42c7fe
Python
5,504
155
# 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...
ea931678459153c39161931b9ea8cb8edf537c2b028868a3e402c1adda863990
Python
5,504
162
"""Training UX callbacks: ETA in hours, val loss history for two-phase schedule.""" from __future__ import annotations import time from typing import Any, List, Optional import pytorch_lightning as pl from omegaconf import DictConfig import torch from pytorch_lightning.callbacks import TQDMProgressBar from pytorch_l...
b7c2ee4a7d6cc3af891ab4e6aa79374eb1aef51ed05da46ce11400476cdbfa50
Python
5,505
144
import os import sys import warnings from typing import Any import pandas as pd from scvi import settings from scvi.utils import dependencies @dependencies("mlflow") def mlflow_log_artifact( local_path: str, artifact_path: str | None = None, run_id: str | None = None, max_size_mb: float = 5.0, ) -> ...
cedba9505139462384e939b2ea6a11ee74c91f15a9cd739b7e1df0b745447d2e
Python
5,506
151
"""Signal-processing utilities shared across the OMR analyses.""" import numpy as np def interpolate_nans(data: np.ndarray) -> np.ndarray: """Linearly interpolate NaN values, extrapolating the edges with 0.""" out = data.copy() if np.isnan(out[0]): out[0] = 0.0 if np.isnan(out[-1]): o...
c5b2d9b204af2e64778ca284c2bb9fe6062b9f772b96732e5aeda1653f385524
Python
5,507
143
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging from fairseq.modules.quantization import pq, quantization_options, scalar from omegaconf import DictConfig logger = logging....
54421dc81d692751abf5dee9a5567473d287481ceacc5a3266b1811e3a2fee33
Python
5,514
163
import torch import numpy as np import utils.Geometry as Geometry def meshgirdFromXY(x,y): X,Y = torch.meshgrid(x, y) X=X.reshape(-1) Y=Y.reshape(-1) return X,Y def genMeshNodes2D(xstart,xend,xnum,ystart,yend,ynum): '''生成规则网格排列的二维点''' x = torch.linspace(xstart,xend,xnum) y = torc...
612b6b41090657327e9ef8aee333ace94bba05fd0d6a3dcd6fb4a34228b3d873
Python
5,514
161
# 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 from dataclasses import dataclass from functools import partial from typing import Callable, Dict, Optional import torch.nn as nn...
f13ac3ee767960439055727b7aa170f264f05f8af5bddebfbac457eb5f770ab6
Python
5,514
139
"""Active learning iteration 3 — 50 picks, non-strain only, train on n=193. Same protocol as iter 2 but with the n=193 SIESTA pool (initial 93 + AL1 50 + AL2 50). Confines selection to non-strain candidates. """ from __future__ import annotations import json import re from collections import defaultdict from pathlib...
73fb69ae0c8cf4b239cbab8e0b88af82178f412d66c8cbfbfcedc72f7444bec6
Python
5,515
169
from __future__ import annotations from PySide6.QtCore import QPoint, Qt, Signal from PySide6.QtWidgets import ( QFrame, QListWidget, QListWidgetItem, QPushButton, QVBoxLayout, QWidget, ) from src.gui.framework.qt_view_styles import PALETTE, apply_button_role _POPUP_STYLESHEET = f""" QFrame#c...
2ca88d4dfcd8465df352d5a3ee8de3c06cece42d6b25e3b8c14b685b32badb9b
Python
5,518
197
import gzip import io from skbase.base import BaseObject from skbase.lookup import all_objects from pgmpy.base import DAG from pgmpy.readwrite import BIFReader from pgmpy.utils.hf_hub import read_hf_file class BaseExampleModel(BaseObject): """ Base class for all models in pgmpy. Inherits from `skbase.b...
244c21845493d4461ddb496a7b0be4867f94eaccd266e7fe4d7219edd5678ae8
Python
5,520
178
# # 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 ...
4ebecd3344b79fcb49844cac1a7a0293bcf7b78fd301afd210f16d5d52c9f162
Python
5,522
143
#!/usr/bin/env python # ENCODE DCC Naive overlap wrapper # Author: Jin Lee (leepc12@gmail.com) import sys import os import argparse from encode_common import * from encode_common_genomic import peak_to_bigbed, peak_to_hammock from encode_blacklist_filter import blacklist_filter from encode_frip import frip, frip_shif...
2fc25827fc37425bdb750728857f58db2824feb3470a3150804d504c3df0c986
Python
5,525
109
#!/usr/bin/env python3 """Controles do resultado positivo da rodada 2. Quatro perguntas: C1. Baseline constante: prever a mediana para todos. Se o erro do OCE nao for bem menor, nao ha resolucao nenhuma. C2. Baseline de volume: B correlaciona com 1/V0 por argumento fisico trivial (celula menor, mais rigida...
5800c4f2ba0ffa908779e9b85fe31bc14adac2b6598624c262fd3d95c870b4e2
Python
5,525
160
import random from typing import Optional, Sequence, Tuple, Any, List from pathlib import Path import numpy as np from omegaconf import DictConfig import torch from torch.utils.data import Dataset, DistributedSampler from torch.utils.data.distributed import DistributedSampler from torch_geometric.loader import DataLo...
0ca0a97ddbdef37d4d7217c25c45530383864472eed5e4a0870c06b281bd6024
Python
5,526
147
from copy import deepcopy import numpy as np 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 import SimpleITK as sitk if __name__ == '__main__': """ Downlo...
d011dc77d391965b74d9d4c4bab62c0367fb5e7e2bc655fda4d11eeba396114f
Python
5,526
138
from copy import deepcopy from mdt.component_templates.base import ComponentBuilder, ComponentTemplate from mot.lib.cl_function import SimpleCLFunction, SimpleCLCodeObject from mdt.model_building.parameters import LibraryParameter from mdt.lib.components import get_component from mot.library_functions.base import CLLib...
5c41b2940a349741fca4bf1f0566dc7f7f3d9550aaee569b902df1a145c80428
Python
5,527
109
import sys sys.path.append("../utils") import torch import torch.nn as nn import torch.nn.functional as F from utils import utils_basic import config.cfg_lodet as cfg class FocalLoss(nn.Module): def __init__(self, gamma=2.0, alpha=1.0, reduction="mean"): super(FocalLoss, self).__init__() self.__gam...
4c8d8da55f432be3915d7c8b9834b90a17f927acdbbabca9c9b859347d80d4e6
Python
5,529
157
# Copyright Howto100M authors. # Copyright (c) Facebook, Inc. All Rights Reserved import torch as th import torch.nn.functional as F import math import numpy as np import argparse from torch.utils.data import DataLoader from model import get_model from preprocessing import Preprocessing from random_sequence_shuffler ...
6787c53a0252be8a3f3d0b77a7c9da4f82d8f411b33921fbceb73530269a540b
Python
5,529
154
import pytest import torch import scvi.distributions._gamma as gamma_module from scvi.distributions import ZeroInflatedGamma def test_zero_inflated_gamma_distribution(): """Test ZeroInflatedGamma distribution.""" concentration = torch.tensor([2.0, 3.0]) rate = torch.tensor([1.0, 2.0]) zi_logits = tor...
d317dd4112accbd5b0f2f52e8e64ce5c27ed06a87e3ef9f61703844ae76e0963
Python
5,532
152
import os from pathlib import Path import pandas as pd os.environ['WANDB_DIR'] = 'ADD YOUR DIRECTORY' import wandb import numpy as np import torch, torchvision from baseModels.utils import get_model from training.training_utils import test_one_epoch from analysis.metrics import dPrime_model def getPerformance(mode...
a1bde584f69856218ce7d42b04e614333d38e9e78f8ae3d64e66907a3d010283
Python
5,533
125
import numpy as np import collections from mdt.lib.components import get_model from mdt.lib.nifti import get_all_nifti_data from mdt.utils import create_roi, restore_volumes from mdt.lib.input_data import MockMRIInputData from mot.lib.cl_function import SimpleCLFunction from mot.lib.kernel_data import Array, Zeros __a...
c2579f3f02876db70948d51bcba11a1c11a02cfed72cc4278834f458c6027f49
Python
5,537
145
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. 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 cop...
3b507c9a875222999a229526275b3c9efeaca16f376e9e66e49d15d58d86dda9
Python
5,538
144
"""Hybrid CE + Dice and metrics for dynamic segmentation.""" from __future__ import annotations import torch import torch.nn as nn import torch.nn.functional as F def compute_class_weight_from_loader(loader, num_classes, device="cuda"): counts = torch.zeros(num_classes).to(device) max_batches = 5...
ee1d91105f482d20b279a8831008135ab501ae03e679f4b41ee94daf704b1cbe
Python
5,538
143
from ... import options as opts from ... import types from ...charts.chart import Chart from ...commons.utils import JsCode from ...globals import ChartType class Polar(Chart): """ <<< Polar >>> Polar coordinates can be used for scatter and polyline graphs. """ def __init__( ...
7cc743035ce01b6bf6327133b6c3dd73e0f086ab27dd5f8a8b2275efa0d6ad12
Python
5,539
157
""" Copy part of code from https://github.com/MIC-DKFZ/batchgenerators needed for inference so we do not need this dependency during inference. This way we can become windows compatible. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from builtins impo...
34cd6f18b824ae4a917ef069fc0e03d506ab0fe09c4836aa5980df2c97609786
Python
5,540
155
"""Measurement: is an LMDB get + blosc2 decompress cheaper than the forward? Sources token ids from the precomputed encodings HDF5 rather than the corpus text, so the input is byte-identical to what the training path feeds the base model. Also sizes the store: the 112 GiB train figure below is *uncompressed*, and the ...
e6a754e6b68203e5b9033fe11632a3f9b193cc29defda368a5351b3cc4c5c6aa
Python
5,541
142
# Version information START -------------------------------------------------- VERSION_INFO = \ """ Author: ZHANG YUBO Version-01: 2019-11-04 calculate mean absolute error between prediction and true value Version-02: 2021-09-23 calculate scaled Euclidean distance between prediction an...
1ce325019f1ca9df925745a1a0ce0b1246b3de0223be5c05ee1659df9b223a24
Python
5,544
176
#!/usr/bin/env python # -*- coding: utf-8 -*- """Saves results of analysis""" import os import csv from typing import Optional from utils.models import Cell class SaveCounts(object): """saves cell counts""" fname = "counts" extension = "csv" encoding = "utf-8" delimiter = "," lineterminato...
c1d3501ea6a05b17cfde1666e714cd0dbbcec7710ceac43430474cc666170f42
Python
5,545
123
from multiprocessing import Pool from typing import Union, Tuple import numpy as np from batchgenerators.utilities.file_and_folder_operations import * from nnunetv2.configuration import default_num_processes from nnunetv2.paths import nnUNet_results from nnunetv2.utilities.dataset_name_id_conversion import maybe_conve...
194f789eb1ca3bddb2bbb085c00c1cfd2199d51b0d7a102cd6780b374551197c
Python
5,547
143
#!/usr/bin/env python # ENCODE DCC Naive overlap wrapper # Author: Jin Lee (leepc12@gmail.com) import sys import os import argparse from encode_common import * from encode_common_genomic import peak_to_bigbed, peak_to_hammock from encode_blacklist_filter import blacklist_filter from encode_frip import frip, frip_shif...
8ed7b53042678fec9ffb6d04ce97566bef1dfd66805429aba35af3fd2438fe22
Python
5,547
158
import torch import neurovfm.systems.classification as cls_mod import neurovfm.models.mil as mil_mod class _LinearDense(torch.nn.Module): """CPU-friendly stand-in for flash_attn FusedDense used in MIL modules.""" def __init__(self, in_features: int, out_features: int, bias: bool = True, **_): super(...
fe510581560a8e7130f645d868551d078d475b9ea2a2b32cc0c6dc70f6b5a06a
Python
5,548
176
import torch import numpy as np import unittest from fairseq.modules import ( ESPNETMultiHeadedAttention, RelPositionMultiHeadedAttention, RotaryPositionMultiHeadedAttention, ) torch.use_deterministic_algorithms(True) class TestESPNETMultiHeadedAttention(unittest.TestCase): def setUp(self) -> None: ...
3ed6c7957b9200b1191d12d8f3480456fba7b797180c4581f7ac127942f5eb28
Python
5,555
172
# 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 fairseq.models.transformer import ( TransformerDecoder, TransformerEncoder, TransformerModel, ) fro...
4128e3e707cb17e5dcc7b030fe0fd09002c4af02b73973f5b0a39d3db40ecf37
Python
5,556
128
# RNAlysis-owned PyInstaller hook for the pure-Python ``graphviz`` package. # # RNAlysis depends on ``graphviz`` (NOT ``pygraphviz``); it shells out to the ``dot`` executable to # render ontology DAGs. To keep the frozen app self-contained we bundle the graphviz program # executables and their plugins/shared libraries....
f20eeb79c735f2ae82b295b27ffa65d4f3c19e62c12107895efaadcf61a830c1
Python
5,556
98
import re import slicer from DICOMLib import DICOMUtils import numpy as np import StereotacticPlan from .importerBase import ImporterDialogBase class ImporterDialog(ImporterDialogBase): def __init__(self): ImporterDialogBase.__init__(self) self.importerName = 'ROSA' self.fileSelectTitle = ...
71046c33fa9dbc80375921c12c36e812251e1c3c7da883c4e1f9c5640a83ce38
Python
5,557
159
"""A bounded Python implementation of the ``msbackadj`` baseline estimator. The DFer option uses the documented quantile-window model with a pchip fit, 10% quantile, and equal window/step sizes. MATLAB is not available in the application test environment, so this module is intentionally described as a compatible esti...
d232079375568cc268c58fbf0fbfc9ba79576769109807faab9e3303937ac956
Python
5,564
136
""" Utility functions to plot data. """ import matplotlib.pyplot as plt import numpy as np def plot_queenframe(queenframe: np.ndarray) -> None: """ Plot the queenframe image. Args: queenframe (np.ndarray): The queenframe image to be plotted. Returns: None This function displays ...
604fa0a00777d13ed362aa7ef2051e6658737db107ab71cb65cd55b97b7c7c31
Python
5,566
164
import pytest from rnalysis.exceptions import ( ExternalServiceError, IDMappingJobFailedError, IDMappingTimeoutError, InternalError, InvalidTypeError, InvalidValueError, RNAlysisError, RNAlysisInputError, ) BUG_REPORT_SUFFIX = ( 'This is likely a bug in RNAlysis - please report it ...
d39b495853b2fb4199c6dfb64b1d41b50dc23a826c4c600aa394e333c90e6d72
Python
5,572
165
import csv import os from collections import defaultdict SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) CSV_FILE = os.path.join(SCRIPT_DIR, "raw_readme.csv") metadata = {} panels = [] with open(CSV_FILE, newline="", encoding="utf-8-sig") as f: reader = csv.reader(f) rows = list(reader) # Metadata r...
4675d52ea8f2e6c67a33c80bade6699d52ca1d6dfd2658c9e49d794509ae843c
Python
5,573
167
"""SIESTA isolated-atom references for the 9 perovskite elements. Each atom is placed alone in a 20-A cubic vacuum box, spin-polarised, with the same SZP basis and MeshCutoff 250 Ry used in the perovskite production run. The unpaired-electron count comes from the GROUND_STATE_UHF dict in oce.atomic_table (xtb-derived...
897a1d01d32ec19b856705e60f2ab8121cdf7c6cc4ecf2b9247e9e9d8712a1a6
Python
5,573
150
import torch from torch import nn from torch.nn import functional as F from rinalmo.model.attention import MultiHeadSelfAttention, FlashMultiHeadSelfAttention import torch.utils.checkpoint as checkpoint class TokenDropout(nn.Module): def __init__( self, active: bool, mask_ratio: float, ...
af56600ca644007acf2b4468ebc01063fdf56eaefecbcd53f66f8c0a2087f20c
Python
5,578
161
import scanpy as sc import sys sys.path.append('./scctools_0.4') from scctools import * # # load data ad = sc.read('./FM27_cell_133454_wk.h5') glut = FM27_cell[FM27_cell.obs['class']=='Exc',:] # # violin plot key = glut matplotlib.rcParams.update({'font.size': 14}) basic_gene = ['SLC17A7','HPCAL1','NPY'] L23NPY_sp...
ea3208d08f637569596b995e99f4d897a40d99b740ee9e5e00ccfcbdeb722b30
Python
5,578
145
import h5py import numpy as np import tensortools as tt import matplotlib.pyplot as plt from scipy.stats import sem, t from collections import defaultdict import os import pickle num_animals = 12 replicates = 30 num_components = 31 output_dir = "performance_metrics" os.makedirs(output_dir, exist_ok=True) def compute...