sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
0f114a5d8c2d36207462f4417b27e74308da897f9b7c28737381c36c9010604d
Python
5,565
158
""" End-to-end auth flow against a running API using Fief. Required environment variables (test is skipped if any is missing): CODECARBON_API_URL Base API URL (e.g. https://api.dev/codecarbon/api) FIEF_TEST_USER_EMAIL Login email for the test user FIEF_TEST_USER_PASSWORD Login password for th...
2889cecf003a30685a265556aec6f3e0a17cd0d994f154f72e97ce22f238da6e
Python
5,565
112
#==============================================================================# # Author: Dominik Müller # # Copyright: 2024 IT-Infrastructure for Translational Medical Research, # # University of Augsburg ...
7a98f9b7988886b8eb93dc179dc265e4e85c099e8763958031c52cbe260aa261
Python
5,565
105
import numpy as np from rdkit import Chem from rdkit.Chem import AllChem import torch import pandas as pd from torch_geometric.data import Data class MolecularGraphData: def __init__(self): self.permitted_list_of_atoms = ['C', 'N', 'O', 'S', 'F', 'Si', 'P', 'Cl', 'Br', 'Mg', 'Na', 'Ca', 'Fe', 'As', 'Al', '...
b9e1b994e4f30cbf5efbdef5daad72ccaecbcc53d7191ef03d7e5de008700f9b
Python
5,567
150
# ------------------------------------------------------------------------------ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. # ------------------------------------------------------------------------------ from __future__ import absolute_import from __future__ import d...
3356dfebf3da599005a095347aa371beb3ef214b1093275d2d01667d90c86d91
Python
5,568
145
import os,pickle import numpy as np from args import * from model import * from trainer import Trainer from dataset import load_dataset_random from utils import * import warnings from argparse import Namespace from BatmanNet.util.utils import get_model_args warnings.filterwarnings("ignore") def load_args(p...
9e62c679e094728184807cd2a59d1b97db81899e8b967a57dd39ac0c56b94692
Python
5,568
164
from keras.src import backend from keras.src.api_export import keras_export from keras.src.optimizers import optimizer @keras_export("keras.optimizers.Lamb") class Lamb(optimizer.Optimizer): """Optimizer that implements the Lamb algorithm. Lamb is a stochastic gradient descent method that uses layer-wise...
d0303acbe09d0ee1f63e3343decadd496ddb570bf5db9b82cb677dc669d12922
Python
5,568
183
model = dict( type='SwAV', backbone=dict( type='ResNet', depth=50, in_channels=3, out_indices=[4], norm_cfg=dict(type='SyncBN'), zero_init_residual=True, init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet50')), neck=dict( type='S...
d8d4827e80300811e38102822fb0302c00f78374b88cfde15c69943a3daff134
Python
5,568
184
from __future__ import print_function, division, absolute_import import math import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.model_zoo as model_zoo pretrained_settings = { 'cafferesnet101': { 'imagenet': { 'url': 'http://data.lip6.fr/cadene/pretrainedmodels...
3f88ea6bb585a81365b43bd2138975162721215613e1e8115f10ba1891523523
Python
5,569
159
"""Utilities for data.""" from copy import deepcopy from typing import Any import gymnasium as gym import numpy as np from neurogym.envs.registration import make class Dataset: """Make an environment into an iterable dataset for supervised learning. Create an iterator that at each call returns inp...
442698b0a9d622541a278909e43c972ddfbd6f63af8aef6644e765199116026d
Python
5,570
147
"""F03 ledger memo item 5: bundle.vary — one explicit edit or identity per member. Pins: complete coverage by default (typed preflight refusals BEFORE any mutation), explicit None identity distinguishable from unmentioned, sugar normalization, whole-mapping donor-group normalization (one reused SamplingPlan = one dono...
bd0f94543173d47db2d2a8ddbcf7593fb381c55dbb49a186b7987ca2f596eaf4
Python
5,571
175
import numpy as np import os from sklearn.metrics import mean_squared_error import matplotlib.pyplot as plt import h5py import tensorflow as tf plt.switch_backend('agg') def rev_comp(x): return np.flip(x, 1)[:, :, [1, 0, 3, 2]] def apply_rev_comp(X_train, alpha=0.5): X = X_train.copy() np.random.see...
0fe897d095b4302e59593f376a3edb54ccdc58a9106eb0f8f0d9c5167f5f5b1c
Python
5,573
167
"""Paddle object-module hierarchy tests.""" from __future__ import annotations import pytest paddle = pytest.importorskip("paddle") import torchlens as tl # noqa: E402 from torchlens.validation.invariants import check_metadata_invariants # noqa: E402 pytestmark = pytest.mark.backend_paddle class PaddleScale(pa...
6a1f2a81e12cc6e2e5d7829343a8fcb2a7b5a4894a9fc0a7e76998aa9ea57c8f
Python
5,573
144
# -*- coding: utf-8 -*- # @Time : 2021/11/18 22:40 # @Author : zhao pengfei # @Email : zsonghuan@gmail.com # @File : run_mae_vis.py # -------------------------------------------------------- # Based on BEiT, timm, DINO and DeiT code bases # https://github.com/microsoft/unilm/tree/master/beit # https://github.c...
3952e3b311883fc2d94b7088a5decf70552d23d97aafe0f4b65171d534e78c90
Python
5,575
145
import os,pickle import numpy as np from elegans_args import * from model import * from trainer import Trainer from dataset import load_dataset_random from utils import * import warnings from argparse import Namespace from BatmanNet.util.utils import get_model_args warnings.filterwarnings("ignore") def loa...
840b67bba979b55b7637bd24a2713f0f03918ba4d71f0e69d5f1401e552a0c57
Python
5,575
168
"""Observe-kit items 2-3: execution-order compare() + the isolated-rerun harness. Pins the two shipped-surface repairs the observe memo sequenced FIRST: ``compare()`` rows follow execution order (never alphabetical), and the shared double-run harness releases each fresh model copy so double-run tools work on an alread...
c3d39f2955b7aad0b62cffa3b7c39b77b18fb42968466cf9c217a9fd2fb9801f
Python
5,575
159
import pytest import torch from lightly.models import utils from lightly.utils import dependency if not dependency.timm_vit_available(): # We do not use pytest.importorskip on module level because it makes mypy unhappy. pytest.skip("TIMM vision transformer is not available", allow_module_level=True) from li...
9989fc13ae4e05c4afdc63c1f9c37bef692da3cc5e1758cd79e50d226aa991fa
Python
5,578
141
"""CI gate for the stage-1 mode-vs-wrapper differential harness. Runs ``tools/differential_capture.py`` cross-process (the mode side must observe PRISTINE torch, which this pytest process — with torchlens wrapped — cannot provide) and asserts an op-for-op aligned verdict for every corpus model. Also unit-tests the ali...
59c9f047e3f8878b3356dd56f557a32fb72f77c15cfaf866cc8cd28a736d235e
Python
5,579
146
"""Anti-recurrence test for cert10 ``tl.swap_with`` string-label honesty fix. ``tl.swap_with(<string label>)`` was publicly documented as working (README, docs/for-ai-agents.md, docs/intervention_api.md) but was dead code: the only resolution path depended on ``hook.run_ctx["swap_sources"]``, a dict that no execution ...
71b3be049b95cf7a2fbd9ab03074e2017b73f9cf7353b01c562a1fd1a4f27228
Python
5,579
174
from itertools import chain import pytest from eelbrain import datasets, plot from eelbrain.plot import _base from eelbrain.plot._base import Layout, ImLayout from eelbrain.testing import skip_on_windows from eelbrain.testing import hide_plots def assert_layout_consistent(layout): if layout.margins is None: ...
2ea3075ff80869cf8c3e9be32a24a8306b6f285363fafb52767caa36eef539c3
Python
5,580
175
import os import sys import numpy as np import torch import torch.nn.functional as F import torchvision.models as models from stack import train as stack_train class StackModel: def __init__(self, root, loss, lam, output_stack, detach=False): assert output_stack in [1, 2, 3, 4] self._output_stac...
e86e4bd84e72502bff98883446bc388fd2f97967d2193d8d0fd62ddc80841f84
Python
5,580
183
import attr from matplotlib import pyplot as plt from permacache import permacache import numpy as np import scipy.special from modular_splicing.utils.plots.plot_psam import render_psams from .motif import Motif @attr.s class PSAMMotif(Motif): log_psams = attr.ib() # log-affinities; (num_motifs, width, 4) ...
c55830aa80bb335f62dbc238946144e81f5d349c130cf9ddcd584c2176677fe9
Python
5,581
167
import threading import random import sys import torch import torch.multiprocessing as multiprocessing from torch.utils.data import DataLoader from torch.utils.data import SequentialSampler from torch.utils.data import RandomSampler from torch.utils.data import BatchSampler from torch.utils.data import _utils # from t...
0dbb2451ebd8d2939e2efd09c12d3e558f7e71070b5e5e54034ed4a0ce55277d
Python
5,582
143
"""Bounding box visualization functions.""" from __future__ import absolute_import, division import numpy as np import mxnet as mx from . import plot_bbox, cv_plot_bbox def plot_keypoints(img, coords, confidence, class_ids, bboxes, scores, box_thresh=0.5, keypoint_thresh=0.2, **kwargs): """Vis...
2b81faf09a9d8568db7c5608982a5ba6cd22173eb3f265d11e32489633966126
Python
5,582
157
# Author: Christian Brodbeck <christianbrodbeck@nyu.edu> import numpy as np from numpy import newaxis from scipy.ndimage import generate_binary_structure from .._data_obj import Dimension class Connectivity: """N-dimensional connectivity""" __slots__ = ('struct', 'custom', 'vector') def __init__(self, d...
8e92bc617396910106650494b15da477c276b77c4b17917308f15d01b69a7e96
Python
5,583
144
''' Copyright 2021 Twente Medical Systems international B.V., Oldenzaal The Netherlands 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 requir...
b402bd0b89b87250f932bf4b8e2bec7af7130a8ebdc3ff5a0bba3865e9984173
Python
5,583
170
from __future__ import annotations import json as _json import typing as t from ..globals import current_app from .provider import _default if t.TYPE_CHECKING: # pragma: no cover from ..wrappers import Response def dumps(obj: t.Any, **kwargs: t.Any) -> str: """Serialize data as JSON. If :data:`~flask...
d9542de468a5b144f8a8a39960a0067aeab374a3a4fbe7bb09ff23ae73e24843
Python
5,584
146
''' Copyright 2021 John Veillette (https://gitlab.com/john-veillette) Copyright 2021 Twente Medical Systems international B.V., Oldenzaal The Netherlands 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...
3009378bcc14dea1d053246eea9a8493ce9417ef81d5bd3efbac07ebac186806
Python
5,586
150
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np import tensorflow as tf import pandas as pd import argparse import os import time import sys import pwd import csv import re import deepchem import pic...
3cbae75c33a8a3e1b8070c979140ea1c023fb0ec924b2991578213cf646abce1
Python
5,586
164
"""Device-time consumers (torchnative W2.3): hot_path, color_by, size_by. The joined table feeds the shipped surfaces as COLUMNS, never schemas: the session-time join registry serves ``hot_path(by="device_time")`` and ``draw(color_by=/size_by="device_time")``; a trace with no joined session refuses typed (``device_tim...
caa2a8a650a41df0a62f457616206d53928e3200479a75388263ca5fa2dcb769
Python
5,586
150
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np import tensorflow as tf import pandas as pd import argparse import os import time import sys import pwd import csv import re import deepchem import pic...
01ecc3df990c3978364df35b9127751740f247a6c38f51048e510fe4f1dd26dd
Python
5,587
150
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jul 5 19:22:06 2021 @author: Audrey Mazancieux This script performes several "event-related" analyses for one subject using LC time serie that have been extracted from ROI delineated in native space and then translated in this space. This script nee...
70f5450418ca006a9400e85183de6cd086271f8f3029ef44568d05992bc173e4
Python
5,587
167
import sys import math import json import numpy as np CMAP = [ [244, 109, 67], [253, 174, 97], [254, 224, 139], [217, 239, 139], [166, 217, 106], [102, 189, 99], ] # out of range colors CMAP_OOR = [ [215, 48, 39], [26, 152, 80], ] SKELETON = """ %s \\begingroup \\renewcommand{\\arra...
b3ab4617dcc981cede3724d4c99b92158811e3dc5811b323c87c4230dec90bef
Python
5,587
186
"""Workflows for generating plots from imaging data.""" from nipype.interfaces import fsl from nipype.interfaces import utility as niu from nipype.pipeline import engine as pe from niworkflows.engine.workflows import LiterateWorkflow as Workflow from xcp_d import config from xcp_d.config import dismiss_hash from xcp_...
b7a402377626ae6de5087640b7ae8f0e76040ce1837ca91c9868845916e17535
Python
5,587
193
import os import re import inflect from tqdm import tqdm import numpy as np import scipy.io.wavfile as wave from nltk.tokenize import sent_tokenize from nltk.tokenize import word_tokenize special_words = { "english": { "grown-ups": "grownups", "grown-up": "grownup", "hasn't": "hasnt", ...
c2d65666145c4e27aaa383063ca0d4ce40271760c902382b080aa775c63d5d38
Python
5,587
172
# --- THIS FILE IS AUTO-GENERATED --- # Modifications will be overwitten the next time code generation run. from plotly.basedatatypes import BaseLayoutHierarchyType as _BaseLayoutHierarchyType import copy as _copy class Smith(_BaseLayoutHierarchyType): _parent_path_str = "layout" _path_str ...
e111ad6029bea7978aa8553fdc1dd78e73c08c6dde879c1112cd68d5f52a879d
Python
5,587
172
import copy import json import pandas as pd import sys import torch import pytorch_lightning as pl import numpy as np from monai.metrics import DiceMetric from pathlib import Path from torch.utils.data import DataLoader from argparse import ArgumentParser from survival_plus_x.data.dataset import GensheimerDatasetInM...
e6934af51f7628c64a9dad19d197828d4ebe329f2579d028acf5fb564f6a113d
Python
5,587
184
import sys import argparse import logging import time def pase_info(seq): info = {'SVLEN': 0, 'END': 0, "SVTYPE": '', "RE": 0, "CHR2": ''} for i in seq.split(';'): if i.split('=')[0] in ["SVLEN", "END", "RE"]: try: info[i.split('=')[0]] = abs(int(float(i.split('=')[1]))) except: pass i...
fd096af1dd229c8e0cbde3dc8897217bbae3f9b2e377d4cef6c2de6486735ab2
Python
5,590
146
from typing import List from uuid import UUID from carbonserver.api.errors import ( NotAllowedError, NotAllowedErrorEnum, NotFoundError, NotFoundErrorEnum, UserException, ) from carbonserver.api.infra.repositories.repository_organizations import ( SqlAlchemyRepository as OrganizationRepository,...
bbb658accce48079af3d9f326cfc8743c0d03e421137e6d851969391b92f2a2a
Python
5,591
191
#!/usr/bin/env python #========================================================================= # # Copyright NumFOCUS # # 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://...
8d7b643dd6353b3c58c6364baa7426280eae596f96d72747994577bf7019c10b
Python
5,592
181
# Read package version in pyproject.toml # Also provides version coherence checking across multiple files import argparse import logging import re import sys import tomllib logging.basicConfig(level=logging.INFO, format="%(message)s") PACKAGE_VERSION = "X.X.X" def get_version_from_file(filepath: str, pattern: str) ...
a80f477d531978ef634fde3d4b37c5695874efa116adf0b814729d1c30a6a831
Python
5,592
173
"""Utilities related to importing modules and symbols by name.""" import os import sys import warnings from contextlib import contextmanager from functools import lru_cache from importlib import import_module, reload from importlib.metadata import entry_points from kombu.utils.imports import symbol_by_name #: Billiar...
26899ca6a16480a8b7f117b3137a058a213a98ae0e5b736fe7c4e4c101753429
Python
5,593
150
import argparse import glob import os from collections import defaultdict import mne import numpy as np import pandas as pd import seaborn from mne.datasets import fetch_fsaverage from tqdm import tqdm import pylab as pb def main(): np.set_printoptions(precision=3) np.set_printoptions(suppress=True) np.s...
acf15d7e9e1bc9ab3692f2b8b02bf6eb24dc90ee4129bf94c0d0ebe5f207160d
Python
5,593
151
import argparse import matplotlib.pyplot as plt import pandas as pd import plotly import plotly.graph_objs as go from galaxy_ml.model_persist import load_model_from_h5 from galaxy_ml.utils import clean_params from sklearn.metrics import ( auc, confusion_matrix, precision_recall_fscore_support, roc_curv...
0c336ccc1e51a27ff66d0db63ad4782b6abaa96643297c255e7e56704f2191d0
Python
5,595
110
#==============================================================================# # Author: Dominik Müller # # Copyright: 2024 IT-Infrastructure for Translational Medical Research, # # University of Augsburg ...
b2c36d9e8093bdd6921e88ffe894e0275b52f75d3d82bc503a312d3574557b37
Python
5,595
165
# Copyright 2023 Blue Brain Project, EPFL. # See the top-level LICENSE file for details. # # SPDX-License-Identifier: Apache-2.0 """Define node and data types used in parser and ast generator While generating ast and visitors we need to lookup for base data types, nmodl blocks defining variables, nmodl constructs tha...
e5720ea309db6b6a4012a33d9128907a6b0947a16cf0f139ca4e13ed7bbd4e1c
Python
5,595
154
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np import tensorflow as tf import pandas as pd import argparse import os import time import sys import pwd import csv import re import deepchem import pic...
67f01f8d590daab1eed79a03c4518780f46ad0180a31d98d4c4593cf3bf0c2a7
Python
5,596
150
"""F10 lovely item 8/9: edge semantics (D28) + stats_table polish laws. The two axes are independent: ``expand``/``split`` are VIEWS that change the multiset; ``clone``/``contiguous`` copy/re-layout the SAME one. Every uncertain case is fail-closed -- an absent mark is honest, a wrong mark is not; ``data_ptr`` never p...
81f3ad38575526d3d7889c6ee7b5ba93135ea7e9b1b0fafc8a67f3434682abe5
Python
5,596
145
"""r55 hon_2 + hon_1-consumer immunizers -- the load-side taint classifier (W2 lane). hon_2 (MED, unsound sanitizer): the r53 ``out=`` taint sanitizer dropped the destination's uninitialized-memory taint at ANY ``out=`` write, on the false assumption of exact value semantics. ``torch.add(a, x, out=a)`` computes ``a + ...
ef13a6236e439f68d71d20f8b69859a81ae8edd5d88343db16af9a010b072f5d
Python
5,596
157
""" The evaluation function. """ from argparse import Namespace from logging import Logger from typing import List import numpy as np import torch import torch.utils.data.distributed from BatmanNet.data.scaler import StandardScaler from BatmanNet.util.utils import get_class_sizes, get_data, split_data, get_task_names...
1ab806f260b161cfc7e75cf88ca8f3a5db20670c64a3a9a1daa2eeb871074790
Python
5,597
212
import numpy as np import logging try: from picamera.array import PiRGBArray from picamera import PiCamera except: logging.warning("Could not load picamera module") import multiprocessing from ethoscope.tracking.cameras import BaseCamera from ethoscope.utils.debug import EthoscopeException import time ...
df99d5ffc6f11bc65503cdfba09f17be6d386c767bdea60158d4fefa8d8a2e37
Python
5,597
168
#!/usr/bin/env python """ detector.py is an out-of-the-box windowed detector callable from the command line. By default it configures and runs the Caffe reference ImageNet model. Note that this model was trained for image classification and not detection, and finetuning for detection can be expected to improve results...
9cb88471186c96c66e1881b1c0ab14fcf4177ef1aac803ebae3cef9da813f1a1
Python
5,598
159
# coding=utf-8 # Copyright 2025 The Google Research Authors. # # 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 applicab...
c917d8e188cb98a63d61896c5a04d0b73ca959b7e0754953a6235d43cbb550b9
Python
5,601
136
import os import re import glob import torch import random import datetime import numpy as np from transformers import GPT2LMHeadModel, WEIGHTS_NAME, CONFIG_NAME from irnlm.models.gpt2.modeling_hacked_gpt2_integral import GPT2LMHeadModel from irnlm.models.gpt2.modeling_hacked_gpt2_semantic import GPT2LMHeadModel as G...
6edbfb3e47798f97584fc4a48ed4c08fa733820216ab4d5bae767174cdb3606f
Python
5,602
191
"""Tests for fastlog predicate normalization and RecordContext construction.""" from __future__ import annotations from dataclasses import asdict import pytest import torch from torchlens.capture.predicates import ( _evaluate_keep_op, _module_capture_spec, _normalize_capture_decision, ) from torchlens.c...
7a0ed064a8febd43f8ffd580680463f350eb7d44e859b31521f1953a9ce19e33
Python
5,602
137
from __future__ import print_function from typing import Tuple import numpy as np import pandas as pd def GetSimISyntheticData(NG: int = 15, G: int = 1000, N: int = 100, noiseLevel: int = 0, ngroups: int = 3) \ -> Tuple[pd.DataFrame, np.ndarray, np.ndarray]: ''' Generate synthetic data. :param ...
d772d8aee0d2a7fd3c2eeddcd9ac1071cfe26e53d67909be8603f2ba6388a971
Python
5,602
165
# SOURCE: vendored from xianchaoxiu/SPCA-Net @ d8364f530908c20e0327be64378a8ac0923bf52e # https://raw.githubusercontent.com/xianchaoxiu/SPCA-Net/main/SPCA-Net/demo.py # # SPCA-Net ("Tuning-Free Structured Sparse PCA via Deep Unfolding Networks", # L. Chen & X. Xiu, 2025 44th Chinese Control Conference (CCC 2025)). The ...
738c74d1efd0a1557455da649b81a375203870995f7a10fdabae1ab8f12fdc34
Python
5,603
174
import numpy as np import pandas as pd from anndata import AnnData from scipy.stats import spearmanr from ...utils import _read_graph def detect_transition_markers_clades( adata: AnnData, clade: int, cutoff_spearman: float = 0.4, cutoff_pvalue: float = 0.05, screening_genes: list[str] | None = No...
ca49fb88dd72cf2d13c705d2e463777bbf73b399cc2b2eb9a18de9dfe12654db
Python
5,604
152
#!/usr/bin/env python # ============================================================================= # MODULE DOCSTRING # ============================================================================= """ Quaternion product transformation for autoregressive normalizing flows. """ # ================================...
e2cfe1e5046ebcbace44d897eccd2a43e15cc4262a449ed4cfb513b85a51375d
Python
5,606
131
# 3D DICOM to 2D jpeg File for the LIDC data import glob import pydicom as dicom import cv2 import numpy as np # ============================== Image =========================================== # ------------------- DICOM Image to Numpy Array (+Houndfield) ------------------------------ def get_pixels_hu(scans): ...
7993adceed3ab224c9a36857491e3fc38f49d29fd978444915855c2426fdb4cb
Python
5,609
201
"""Model fixtures for the TorchLens performance benchmark suite.""" from __future__ import annotations import os from pathlib import Path from typing import Any, Literal import torch from torch import nn DeviceName = Literal["cpu", "cuda"] ModelName = Literal["tinynet", "resnet18", "gpt2_hf", "gpt2_hooked", "small_...
2d13a7247aad61e0e798b4c767fb1ddc3adee382bdacc03b8f318a6d82afcb7c
Python
5,610
117
from typing import Optional, Union from anndata import AnnData try: from typing import Literal except ImportError: from typing_extensions import Literal def morphopath( adata: AnnData, vf_key: str = "VecFld_morpho", key_added: str = "fate_morpho", layer: str = "X", direction: str = "forw...
6e539f159d607a69fbe76a42b797bc85ca89fea8a811ac8bd59fd3db8934ab60
Python
5,610
151
"""Group Norm implementation""" import torch import torch.nn as nn import torch.nn.functional as F from torch.nn import Module, Parameter from torch.nn import init __all__ = ['GCN', 'NaiveGroupNorm'] class Conv2D(nn.Module): """Inline Conv2D for GroupNorm module""" def __init__(self, in_channels, out_channel...
875b88148932c7c534a983f7cae4c80ba3b3939ccd659d0e9191861562d50c26
Python
5,610
187
from functools import lru_cache import os from types import SimpleNamespace import attr import numpy as np import h5py import tqdm.auto as tqdm from permacache import permacache from .gene_dataset import create_gene_dataset from .hsmm_model import HSMM from .substring import substring_hsmm from .fill_gaps import fill...
39c5b3613a0ad42e35dd51abe98da7883d12dd712e40161a6abf5e8ceaddfa52
Python
5,611
144
import math import warnings from typing import List from torch import nn from torch.optim import Adam, Optimizer from torch.optim.lr_scheduler import _LRScheduler class LinearWarmupCosineAnnealingLR(_LRScheduler): """Sets the learning rate of each parameter group to follow a linear warmup schedule between warmup...
949a4beaff380e4924497cbbec776e66357ae48681a57069a7cd6645b5e93b72
Python
5,612
158
# -*- coding: utf-8 -*- """ Created on Wed Feb 15 20:55:52 2023 @author: longzheng """ import torch import torch.nn as nn from torch.utils.data import DataLoader from torch.optim import Adam from oil.utils.utils import LoaderTo, islice, cosLr, FixedNumpySeed from oil.tuning.args import argupdated_config from oil.tu...
fb1271bade2b5f7ded4f3706a171e8721aca96d4d5dc744a1efd6696682c96b6
Python
5,612
186
from pathlib import Path import matplotlib from matplotlib import pyplot as plt import numpy as np from typing import Optional, Union from anndata import AnnData import os from stlearn._compat import Literal def add_mask( adata: AnnData, imgpath: Union[Path, str], key: str = "mask", copy: bool = False...
bccd559e9559fa9a7cbd453b61af0702ee1560419f70d37fc5a132e03d369072
Python
5,613
177
from permacache import permacache, stable_hash import numpy as np import tqdm.auto as tqdm import scipy.stats from modular_splicing.evaluation.predict_splicing import predict_splicepoints from modular_splicing.data_for_experiments.standardized_sample import ( standardized_sample, ) @permacache( "modular_s...
74c804ee3d272363f74dce4c2762555139fc7cf33a27387c89fd62d8c19bee70
Python
5,614
160
# ------------------------------------------------------------------------------ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. # ------------------------------------------------------------------------------ from __future__ import absolute_import from __future__ import d...
114899d91a1110d65391bdb1558d3af8467cd296a60f51a48ab0fe8a697439bb
Python
5,615
158
# Copyright (c) 2020. Lightly AG and its affiliates. # All Rights Reserved from math import ceil from typing import Any, Dict, Tuple import torch from lightning_utilities.core.imports import RequirementCache from torchvision.transforms.v2 import CenterCrop, ConvertBoundingBoxFormat, Transform from torchvision.tv_tenso...
81bf04b3e2e3ac4c10423e251d3a70581eb2e7b142c34d40c52940cb27189db5
Python
5,615
160
import torch import torch.nn as nn import torch.nn.functional as F from ..base import _layers as layers from ..base import _blocks as blocks from ..base import _towers as towers class Jores21CNN(nn.Module): """ Custom convolutional model used in Jores et al. 2021 paper PyTorch implementation of the Tenso...
23c07adb5cc54744bbec90830b2dfe7610680dcbd3bccf402bbcc489ba104ec3
Python
5,618
165
import argparse import sys import os.path from os.path import dirname, join from os.path import join from tqdm import tqdm import pandas as pd import pickle as pkl import sys import warnings import scipy.stats import numpy as np import joblib import json repo_dir = dirname(dirname(os.path.abspath(__file__))) def get...
be5cd0f83c5e5fce91b0c38ed721f8ce3d0617821c9cf74e60a45567cbfaaa01
Python
5,618
185
""" Simple scikit-learn interface for finetuning a single linear layer on top of LLM embeddings. """ from numpy.typing import ArrayLike import numpy as np from scipy.special import softmax from sklearn.base import BaseEstimator, ClassifierMixin, RegressorMixin from sklearn.linear_model import LogisticRegressionCV, Ridg...
03c7667059fb8ed69d7aa788a5c5de4363a6c33c6eb26d89690a3e592c34659e
Python
5,619
142
""" Python utils intended to correctly format the texts associated with the results shown to the user. The text adapts to the result range and its unit. """ from blueprints.translation.translation_dicts import TRANSLATIONS_DICT def format_energy_text(energy_needed: float): """ Adapt the value and unit of the ...
b922b7a135abe67061779436dfdcd19b4025927679b81e598b09dc1cc9eba3e7
Python
5,620
142
# -*- coding: utf-8 -*- """ Created on Wed May 13 08:41:56 2020 @author: Caterina Brighi """ #%% Import functions import matplotlib.pyplot as plt import matplotlib as mpl import SimpleITK as sitk import numpy as np import pandas as pd import datetime import os import glob import gzip import shutil...
e7079a9b2ed7d3633ce4700900cf810ae8eb62d4b6e05dd7c7d22724c3945b32
Python
5,620
167
#!/usr/bin/env python # coding: utf-8 ### Libraries # conda install -c anaconda pandas # conda install --channel conda-forge --channel bioconda pybedtools # pip install xlrd==1.2.0 import sys import csv import argparse import pandas as pd import numpy as np import pybedtools np.random.seed(5) parser = argparse.Arg...
901c29e7417130a9dfe75a50ba7057c3bba575a233ba9ce55dde03924656f6e5
Python
5,621
159
import torch import torch.nn as nn from typing import Dict import torch.nn.init as init from .._utils import get_layer from motifdata import to_kernel from motifdata import MotifSet from typing import Union, Callable, Optional, Any, Tuple, List, Literal INITIALIZERS_REGISTRY = { "uniform": init.uniform_, "nor...
d7b0b3267b44b500419c7ba7eabc838a24db590274ed4b98688153c40cde24ea
Python
5,622
157
import os import cv2 import glob import shutil import numpy as np import pandas as pd from tqdm.auto import tqdm import torch import torch.nn as nn from torch.utils.data import DataLoader from utils.data_loader import PatchDataset class ListPatchDataset(PatchDataset): def __init__(self, df, transform): ...
fd3735289a221f5aae2cbf1547cb67c759f061e831c02473178a9787636908e9
Python
5,622
185
# we need asyncio, apparently? import asyncio from multiprocessing import Process, Queue, Event import logging import time def handle_data(queue,data): # do the time-stamp thingy + put it into the queue. timestamp=time.time() markertext = data.decode("utf-8") queue.put([timestamp, markertext]) ...
26e408793306a95efb65f1e5f4d34861f170928a675d0f47b23785450af7bc47
Python
5,623
151
"""R11/R32: a FAILED capture's escaping trace drops its capture transients. The success arms pop ``_output_attribution_input_tensors`` (live USER INPUT tensors) and postprocess replaces the mutable ``capture_events`` alias with the payload-free ``_capture_events`` home. The failure/interrupt arms reached neither, so t...
8ece3611ff5a21741592c75c05ef35e3de1a9afbc5261ebba1a721c8595d7638
Python
5,626
214
## some routines for filtering import numpy as np from scipy import signal from scipy import ndimage from numba import jit import itertools as itt from ..core import ifnot from .dctsplines import l1spline,l2spline,sp_decompose from .dctsplines import l2spline_thresholded #from .dctsplines import dct_denoise_img fr...
2f54f153a3aa8ae6ad19c0fe86623544600db520ff6c27668601098b764326e2
Python
5,627
189
# -*- coding: utf-8 -*- import tensorflow as tf from efficient_layers import EmbeddingPostprocessor, ConvertImg_v3 from resnet import ResNet50v2 #データ量等で適切なものを選択 from iv_resnet import ResNet50v2 as iv_ResNet50v2 # 中間ベクトル抽出用 ResNet class IV_model(tf.keras.models.Model): def __init__( self, embedding...
b60e51c961e0b8ec7ef26139f6b6a9b313ca8ac6abb5a36659c961b0a49f8652
Python
5,627
170
from typing import Tuple, Dict import pytorch_lightning as pl import torch import torch.nn as nn from torch.optim import Adam from torch.optim.lr_scheduler import ReduceLROnPlateau from DeepDenoise.src.layer import DoubleConv, Down, Up, OutConv from Metrics.src.image_quality_estimation import check_performance clas...
f29c127f546fd9b23b58e204029082aa8f5fce680f559f9f61ad851f2a56cc96
Python
5,627
195
import pytorch_lightning as pl import torch from abc import abstractmethod, ABC from rdkit.Chem.rdchem import Mol from typing import Dict, Any from torch_geometric.loader import DataLoader from bioconfpred.data.featurizer import MolFeaturizer class ConfPredModel(pl.LightningModule, ABC): """ Base class for m...
721c61e29538bf76d08d9cad95d476d4b31d239c7b64ae05f6fc87d70507f23b
Python
5,628
153
""" Encapsulates external dependencies to retrieve cloud and geographical metadata """ import re from dataclasses import dataclass from typing import Callable, Dict, Optional import pycountry import requests from codecarbon.core.cloud import get_env_cloud_details from codecarbon.external.logger import logger @data...
77772c003bb8f3b6e613bd92eaff5b8fda243f677b716c9fa543926991926b5c
Python
5,628
173
from pathlib import Path from typing import Any, Dict, List, Tuple, Union from pytorch_lightning import Trainer from pytorch_lightning.callbacks import DeviceStatsMonitor, LearningRateMonitor from pytorch_lightning.loggers import TensorBoardLogger from torch.nn import BatchNorm1d, Linear, Module, Sequential from torch...
e54ac011a29e37808eeb4df629435e8c920baa9efd7120273dcc7e459db3f5a1
Python
5,628
173
"""Experimental image transformations.""" from __future__ import division import random import numpy as np import mxnet as mx from mxnet import nd def random_color_distort(src, brightness_delta=32, contrast_low=0.5, contrast_high=1.5, saturation_low=0.5, saturation_high=1.5, hue_delta=18): ...
8fb4da9a23c4fb63662446de4d17a36915d41faa4cb5b574329c91328dc2efb4
Python
5,629
159
from ._permutation import _permutation_1samp, _permutation_ind from ..permutation import permutation_test import numpy as np def _compute_hommel_value(p_vals, alpha): ''' compute all-resolutions inference Hommel value **implementation modified from nilearn.glm.thresholding** ''' p_vals = p_vals.co...
93fa4f4a387372778be7416d912d73196fcf41f90a538a4efad133e5ab8ca62d
Python
5,630
197
import warnings import os import numpy as np import torch from tqdm import tqdm as tqdm_dataloader # tqdm(dataloader) causes an error if tqdm.auto.tqdm is used from tlib import tutils from .data import read_batch class SimpleDataset(torch.utils.data.Dataset): def __init__(self, inputs, function): sel...
dfe2d64b88b7d3ff8ae489abfb3dd9bc23c9a790bed82b7149bfd1a18764298c
Python
5,631
158
from abc import ABC, abstractmethod import itertools from datetime import datetime import numpy as np import torch import tqdm.auto as tqdm from modular_splicing.evaluation.evaluation_criterion import DefaultEvaluationCriterion from modular_splicing.evaluation.run_evaluation import accuracy_from_batches from modular_...
7b6dc182953f93aceb70012bd5a2f218931c767763e94098f930f27c0c01bab9
Python
5,633
154
"""LeWM loss for latent-space world models.""" from __future__ import annotations from torch import Tensor, nn from lightly.loss.latent_distance import latent_distance from lightly.loss.lejepa_loss import SIGReg def latent_prediction_loss( *, predicted: Tensor, target: Tensor, normalize: bool = False ) -> Tens...
80b3ce50b6874885db89382de8ebc15e8284cef30b7f3056696786ecf66d94d6
Python
5,635
117
import os import urllib.request, urllib.error, urllib.parse import urllib.request, urllib.parse, urllib.error import sys import math # # Refer https://wiki.cancerimagingarchive.net/display/Public/REST+API+Usage+Guide for complete list of API # class TCIAClient: """TCIA Client from TCIA REST API SDK GitHub. See ...
efe6bc97d805ba2e6dbea8b87ced45932927ec3a8cad421bedf362e2cfa0ab2e
Python
5,636
148
import os from pathlib import Path import shutil import torch from sklearn.decomposition import IncrementalPCA from src import util class PCBuilder: def __init__(self, root, model_name, layer, dataset_name, ntau, nlat, nspan, scale, n_pca): self._root = root self._model_name = model_name ...
727bd2eb96d609f80752706f6b3969fe91592913e5b8b7109334fe9758746a6c
Python
5,638
119
""" Kristian's original 2-layer VAE. Model diagram with 35 latent dimensions and 100 dense nodes: https://user-images.githubusercontent.com/112708/48358766-4f7a7e00-e650-11e8-9bab-d7a294548100.png """ import numpy as np import keras from keras.models import Model from keras.layers import Activation, Dense, Lambda, I...
ddead7d6a640a7d37c9f9534106ea97835ac554d609e3d7155de9f14611fa289
Python
5,638
135
""" Neo4j Composite Dataset """ import logging from galaxy.datatypes.data import Data from galaxy.datatypes.images import Html from galaxy.datatypes.metadata import MetadataElement from galaxy.datatypes.protocols import ( DatasetProtocol, HasExtraFilesAndMetadata, ) gal_Log = logging.getLogger(__name__) verb...
f3c4347fc102a62cba15ad3ee2d43a723e904ca810692d2f23a089f8f90ed88a
Python
5,638
204
from unittest.mock import Mock, patch from celery.concurrency.gevent import TaskPool, Timer, apply_timeout gevent_modules = ( 'gevent', 'gevent.greenlet', 'gevent.monkey', 'gevent.pool', 'gevent.signal', ) class test_gevent_patch: def test_is_patched(self): self.patching.modules(*ge...
636537e6b943be7e4af916e22cb35b510c958cec38d34fa220db4a16d4a3be9a
Python
5,639
122
from mne.stats.cluster_level import ( _find_clusters, _setup_adjacency, _reshape_clusters, _cluster_indices_to_mask ) import numpy as np from .parametric import ARI from .permutation import pARI def all_resolutions_inference(X, alpha = .05, tail = 0, ari_type = 'parametric', adjacency =...
04a76acd22dac28e328e596a06e63d1e6d313c8e971d4c58ceb374580057e51c
Python
5,641
154
import torch import torch.nn as nn import torch.nn.utils.rnn as rnn_utils from tqdm import trange class Discriminator(nn.Module): def __init__(self, input_size, embed_size, hidden_size,use_cuda=None, dropout=0.2,optimizer_instance=torch.optim.Adadelta, lr=0.001): """ Parameters ---------- ...
057b4230a47a8234ebbcc7cfdcc5b3675638654e2aaa809f6d136a402bac56df
Python
5,642
154
from __future__ import absolute_import import datetime import json import logging import os.path import sys from pip._vendor import lockfile, pkg_resources from pip._vendor.packaging import version as packaging_version from pip._internal.index import PackageFinder from pip._internal.utils.compat import WINDOWS from ...
8ef8d6060f9eb260cffb6d3995994e8714143852d9d576c29b5990808140eccb
Python
5,642
162
import warnings from keras.src import backend from keras.src import tree from keras.src.export.export_utils import convert_spec_to_tensor from keras.src.export.export_utils import get_input_signature from keras.src.export.export_utils import make_tf_tensor_spec from keras.src.export.saved_model import DEFAULT_ENDPOINT...
741f00b16c0dd6ba966e16eeace880bf8885b2bc2e03c858c8718c3fe5b64540
Python
5,643
142
"""The bidirectional call-time deprecation gate + plants (build item 5). Static side (zero emission sites) is owned by tests/test_deprecation_inventory.py and CITED, never duplicated; this gate owns the CALL-TIME behavior root (D6: five of seven shims at the panel's SHA presented the implementation's metadata everywhe...