sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
b0f596d057b7ae186c9c61d8687a1deda49680a33152cc2e37edce45d6067db3
Python
3,067
98
import numpy as np import torch from torch import nn from torch.nn import functional as F class DNN(nn.Module): ''' Autoencoder for dimensional reduction''' def __init__(self, cdim, chid1, gdim, ghid1, hid2): super(DNN, self).__init__() #self.qc = qc self.cdim = cdim ...
167cf9e0805d6d9afd807395972f55bd1af6e4114588ca61381eac82285abd34
Python
3,068
74
import glob import sys import pandas as pd from nilearn.glm.second_level import SecondLevelModel def group_onesample(fixed_files,group_out,contrast,smoothing=None): """ This function takes in a list of fixed effect files for a select contrast and calculated a group (secondlevel) model by fitting an interc...
b7f4489b0df21499c7c55f57f33364f4c2b7b1f685b741268edd470bd1618711
Python
3,068
59
#==============================================================================# # Author: Dominik Müller # # Copyright: 2024 IT-Infrastructure for Translational Medical Research, # # University of Augsburg ...
05988813ecbfe0bb80d8a373148a1fdf1b960fc97a86c5db32852c51e6169423
Python
3,069
85
import torch import sys import numpy as np from sklearn.manifold import TSNE import matplotlib.pyplot as plt from utils_ensemble import list_of_result_to_dico sys.path.append("../") sys.path.append("../models_architectures/") prefix = "../data/models/fine_tune_models/result_previous_may_2021/" # Which model I want to ...
0c4c9f1f310a72c4fff7eadc81d4399117c35360ba34569f9489331a3a232a68
Python
3,069
74
import glob import sys import pandas as pd from nilearn.glm.second_level import SecondLevelModel def group_onesample(fixed_files,group_out,contrast,smoothing=None): """ This function takes in a list of fixed effect files for a select contrast and calculated a group (secondlevel) model by fitting an interc...
1158a731a47b942ec61239393a42ffa4a8a5ed8eec4a383e1c3d659108c548ef
Python
3,070
79
from typing import Tuple import pytest import torch from pytorch_lightning import LightningModule, Trainer from torch import Tensor, nn from torch.optim import SGD from torch.utils.data import DataLoader from torchvision.datasets import FakeData from lightly.transforms.torchvision_v2_compatibility import torchvision_...
53ab084daeabb3bab75dadc50d2252f376eebbd264982132dac358e7ae97f629
Python
3,070
89
'''Script for experimenting with the RNN component of the model without the RL component.''' # © Thomas Akam, 2023, released under the GPLv3 licence. #%% Imports. import numpy as np from tensorflow import keras from tensorflow.keras import layers import pylab as plt from sklearn.decomposition import PCA import two_s...
bb1217d6d9abb6f1b672c3d118482384056ec84716805518b0c8365303201157
Python
3,070
109
"""Append rerun regression tests for active streaming traces.""" from __future__ import annotations from pathlib import Path import pytest import torch from torch import nn import torchlens as tl from torchlens.intervention.errors import AppendStreamingNotSupportedError from torchlens.options import CaptureOptions,...
16856782ce4725250ea62c2f291a52b32e875de2b2e6306d7720b0a02579041b
Python
3,071
88
import torch import torch.nn as nn import torch.nn.functional as F from torch.nn import Sequential, Linear, ReLU from torch_geometric.nn import GINConv, global_add_pool from torch_geometric.nn import global_mean_pool as gap, global_max_pool as gmp # GINConv model class GINConvNet(torch.nn.Module): def __init__(sel...
5122cd077fb87793061a26571937986b956c3eec72ca725186b2692548fe3bc2
Python
3,071
93
import numpy from skimage.metrics import structural_similarity as ssim import model from propagation_ASM import * import tools from scipy import io def psnr(img1, img2): mse = numpy.mean((img1 - img2) ** 2 ) if mse < 1.0e-10: return 100 PIXEL_MAX = 1.0 return 20 * math.log10(PIXEL_MAX...
a5c72b1aa79c62d6340facf3c9e648fff36c0d20aa124db4247239775c8231d2
Python
3,071
90
# --- THIS FILE IS AUTO-GENERATED --- # Modifications will be overwitten the next time code generation run. from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType import copy as _copy class Textfont(_BaseTraceHierarchyType): _parent_path_str = "scattercarpet.unselect...
2aad9d2e74ed29998d85ec8a94af4af8fff20736bbad33156098758d437fb0ef
Python
3,072
58
#==============================================================================# # Author: Dominik Müller # # Copyright: 2024 IT-Infrastructure for Translational Medical Research, # # University of Augsburg ...
c3440a1a75564a29800a6948a1f1be077b8039ae00f8f0f08ca167a7c395c7a4
Python
3,072
99
# -*- coding: UTF-8 -*- import numpy as np from sklearn import svm import math import random import operator import csv from sklearn.cluster import KMeans from sklearn.metrics import adjusted_rand_score ''' @author:hunter @time:2017.03.31 ''' class kmeans(object): def __init__(self): pass def load...
e9b7a90a719c34f552942378835179a3529ba4b282d5dbe9823dd95640d66882
Python
3,072
103
from functools import lru_cache import os import pandas as pd from .data_directory import DATA_DIRECTORY from .rbns import read_rbns_motifs from .rbns_v2 import read_rbns_v2p1_motifs RBNS_MOTIF_FUNCTIONS = os.path.join(DATA_DIRECTORY, "motif_functions") RBNS_MOTIF_FUNCTIONS_v1p0 = os.path.join(RBNS_MOTIF_FUNCTIONS, ...
697c4f6090c274da62fe8228689aaf3367f07e13b64021bf8c147844381af65c
Python
3,073
85
import time import copy from docking.pdbbind_docking import PDBbindDocking from data.split import RandomSplit, ScaffoldSplit from conf_ensemble import ConfEnsembleLibrary from rankers import (NoRankingRanker, RandomRanker, EnergyRanker, ModelRanker, ...
a93878759be6b605c63a95cde8d2dd0105bf907f6926da4b3e69415d84800294
Python
3,074
93
import numpy as np from neurogym.core import TrialEnv from neurogym.utils import spaces from neurogym.utils.logging import logger class MatchingPenny(TrialEnv): """Matching penny task. The agent is rewarded when it selects the same target as the computer. opponent_type: Type of opponent. (def: 'mean_act...
da42cb9f28d000a0f67ab62b51a69aec2255eb234433ef918fb64867c1d9dfc0
Python
3,074
73
import glob import sys import pandas as pd from nilearn.glm.second_level import SecondLevelModel def group_onesample(fixed_files,group_out,contrast,smoothing=None): """ This function takes in a list of fixed effect files for a select contrast and calculated a group (secondlevel) model by fitting an interc...
791e74f9860e2224f27ff2b9a8d4c72c6cded4e211fa41cff91ceb5be724d68f
Python
3,075
78
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations import json from pathlib import Path from ultralytics.utils import LOGGER, YAML from ultralytics.utils.checks import check_requirements, parse_requirements def onnx2deepx( onnx_file: str | Path, imgsz: tu...
91d2d817fe2a83623ac078ef1d07d53cc00b73bd684978b9a77a7a7abae4ef33
Python
3,075
97
# LICENSE # # _This file is Copyright 2018 by the Image Processing and Analysis Group (BioImage Suite Team). Dept. of Radiology & Biomedical Imaging, Yale School of Medicine._ # # BioImage Suite Web is licensed under the Apache License, Version 2.0 (the "License"); # # - you may not use this software except in complian...
0f3a9a4030539ee95645c89dcf364d25beb69d6880e687e4df016579dd3be752
Python
3,076
95
import matplotlib.pyplot as plt import re import os def read_roc(path): acc_dict = dict() threshold_list = list() non_bind_acc_list = list() bind_acc_list = list() with open(path, 'r') as f: i = 0 for line in f: if i % 2 == 0: # print(line) ...
cc3b3bb8b243e6e5be0c81935d1abf1e5a391d05b2c114a9e2ef99fa2b025301
Python
3,076
90
# --- THIS FILE IS AUTO-GENERATED --- # Modifications will be overwitten the next time code generation run. from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType import copy as _copy class Textfont(_BaseTraceHierarchyType): _parent_path_str = "scatterternary.unselec...
d38ec012775435d140e1324e98091595dba11c2ffd8b5060c8fd0333f1821440
Python
3,076
90
# --- THIS FILE IS AUTO-GENERATED --- # Modifications will be overwitten the next time code generation run. from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType import copy as _copy class Textfont(_BaseTraceHierarchyType): _parent_path_str = "scatterpolargl.unselec...
0344e1bd29c4b1d01a463d307885b626db2b25e2d6d5d9bbbf1c4390f96b7055
Python
3,077
106
import configparser from pathlib import Path from typing import Optional import typer from rich.prompt import Confirm from codecarbon.core.config import get_hierarchical_config def get_config(path: Optional[Path] = None): p = path or Path.cwd().resolve() / ".codecarbon.config" if p.exists(): config...
582aacb276a43caa2bc75254ae5ec0e5cf4c75eb58973f6baa71735f7bc8a703
Python
3,077
94
# 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...
e86af9ddf92d59bfdda47b73373751ef1aec82512458e28ca332ee446637b84d
Python
3,077
92
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Import raw (MaxFiltered) MEG data to remove metadata then save in same format for further BIDSifying. For passive movements task. @author: mikkel For information about NatMEG-PD please refer to the data descriptor: Vinding, M. C., Eriksson, A., Comarovschii, I., Wal...
e8dfec0cecc424217ca498007d5dc4d7c9ba92db11a7085c7a87a3186796c3d5
Python
3,077
113
import os import random as python_random import numpy as np import tensorflow as tf import tensorflow_datasets as tfds from tensorflow.keras.models import load_model from gradient_accumulator import GradientAccumulateOptimizer from .utils import get_opt from .utils import normalize_img from .utils import reset tf_v...
410ab6602afa697a7ae14517ef5349f165f5b6b9cb0387752e24bb371c812940
Python
3,078
78
import torch from config_manager.config_manager import ConfigManager from dataset_manager.training_dataset_manager import TrainingDatasetManager # pylint: disable=no-member class GenerateEmbeddingProt: def __init__(self, path_folder_xp): self.save_path = "data/embeddings_of_prots/" self.xp_name =...
ca63fad377786fe187519e613915226ecf76d2612c93abee9dad652295edf93c
Python
3,078
98
from abc import ABC, abstractmethod import numpy as np class Motif(ABC): @abstractmethod def score(self, rna, pad=True): """ Score the given RNA sequence. If pad is True, then the score is padded with zeros on the left and right. """ pass def width(self): ...
cb2efca65bfbb8e970d4e0f64c1475515aa1a963df0397deab6a29e9e3ff3a5a
Python
3,078
83
import numpy as np import requests import json import zlib import sys import os # Add src to path sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) from src.neuron_morphology import NeuronMorphology from src.synthetic_morphology import MorphologyInterpolator def load_neuron_from_web(neu...
5c61de409fe52511064f15e36c1e06c7e8d5d74e1badb22302502b882cda0314
Python
3,079
86
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If ex...
e399b64d8443385cc2f11aaedf1e5dd637682da4d36fd019253becf26e1f9deb
Python
3,080
84
#!/usr/bin/env python3 import predict import sklearn.metrics import argparse, sys import os import numpy as np import glob import re import matplotlib.pyplot as plt def calc_auc(predictions): y_true =[] y_score=[] for line in predictions: values= line.split(" ") y_true.append(float(values[1])) y_score.append...
0f93a6fcf4da607ef4551791ce66e733153e8cc46831d78c949195f839cad549
Python
3,082
104
# --- THIS FILE IS AUTO-GENERATED --- # Modifications will be overwitten the next time code generation run. from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType import copy as _copy class Marker(_BaseTraceHierarchyType): _parent_path_str = "choroplethmap" _path...
09f24f51c28964742fa549600bb7b55c1b7c24de9d6b505df5157d2e157a3cbe
Python
3,088
90
#!/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://...
34d8e9022e94f4e0ef51d2decb06957e77f086c0d8a17ed2387fc859810cc4a9
Python
3,088
112
# coding=utf-8 # Copyright 2022 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...
e445bf0385d1c847b71e8b3e07a7209366579963748d20ea1cd9f7d290fc730c
Python
3,088
100
"""Entry-point wiring tests for grouped option classes. The flat option kwargs were removed by the 2026-08-19 shim-removal lane, so the grouped objects are the ONE spelling: these tests pin that the grouped door works warning-free and that the removed flat spellings refuse as unknown keywords instead of silently doing...
e64c80021f2fa6f167954c5c5566cbbbf6ce1b42d6570607dd34a9d4663e002b
Python
3,089
92
from pathlib import Path import h5py import numpy as np import scanpy as sc from mudata import MuData from muon.atac.tl import initialise_default_files # # Reading data # def read_10x_h5(filename: str | Path, extended: bool = True, *args, **kwargs) -> MuData: """Read data from 10X Genomics-formatted HDF5 file....
e73854b22e9c9641312e6eae3ae160ae8a5b1a2ae0c3c0e7225fdeeae147be8f
Python
3,089
99
# -*- coding: UTF-8 -*- import numpy as np from sklearn import svm import math import random import operator import csv from sklearn.cluster import KMeans from sklearn.metrics import adjusted_rand_score ''' @author:hunter @time:2017.03.31 ''' class kmeans(object): def __init__(self): pass def load...
8228ae1838f9498cb125a51669e21f8d9b23d16f5c75762cafeea22aa854b449
Python
3,090
83
import numpy as np from keras.src import backend from keras.src import ops from keras.src import testing from keras.src.optimizers.adadelta import Adadelta class AdadeltaTest(testing.TestCase): def test_config(self): optimizer = Adadelta( learning_rate=0.5, rho=0.9, ep...
ce340f37ec3a87aef857ef4b8cc6d567e952a2be9c4cb2ae3d01aed3b66f23dd
Python
3,090
81
import unittest import h5py import numpy as np import tqdm.auto as tqdm from modular_splicing.dataset.dataset_aligner import ( DatasetAligner, bin_starts, split_bin, to_absolute_index, ) from modular_splicing.utils.sequence_utils import draw_bases class DatasetAlignerTest(unittest.TestCase): def...
db6c979d9d23612218746d16b547bd0e42ba197403a278cd3e232cddf00d259e
Python
3,090
81
"""Tests for the xcp_d.utils.concatenation module.""" import os import nibabel as nb import numpy as np import pandas as pd from xcp_d.utils import concatenation def test_concatenate_tsvs(ds001419_data, tmp_path_factory): """Test xcp_d.utils.concatenation.concatenate_tsvs.""" tmpdir = tmp_path_factory.mkte...
1ce69c8a0b8cbde928127992d0a1a5e17479ef2c3e2848cd976d6201c76245f0
Python
3,091
95
""" Plot beta weights of M1 beta lateralization vs. single-trial bias during baseline """ import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from stats import permutation_test_two_tailed from stats.stars import stars ############ Load data from baseline regression model #####...
45102ce6223708825b5b216be01ee6a6fedb9eb67a1afd8d490ff97d82208de0
Python
3,091
110
# %% ''' Generates fc matrices from rest. Can be run on Lucky as it is fast. ''' import h5py import sys import os from sklearn.linear_model import LinearRegression import numpy as np from time import time from nilearn.signal import clean sys.path.insert(0, '..') from functions.data_helpers import get_computer # globa...
2c081d52997b74bce6274d9de5b25bc9366b5cf3b743a812e166954a8c91d2b3
Python
3,092
128
"""Functionality to compute model error.""" from inspect import isfunction import numpy as np ################################################################################################### ################################################################################################### def compute_mean_abs_e...
c2198c3d1edab4479dd09d99f214f5f34d738f89ffe695acfce4c067c146a91b
Python
3,092
96
"""Intervention honesty: a failed ``do()`` detaches the hooks it attached (WT A-II item 11 -- the contamination defect). A hook that raises at fire time used to stay in the sticky spec after the failed ``do()``, so every LATER push (including unrelated edits) re-fired it. ``do()`` is transactional about its own attach...
d23301efd7e9878e4018fef50610d547d261a30b878bf2a1cb3b7dbf7f861fbc
Python
3,093
89
""" core.roc — ROC curve helpers and operating-point selection. """ from __future__ import annotations import numpy as np def roc_curve_sens_spec(scores, labels): """Sweep thresholds; return (thresholds, sens, spec) sorted ascending.""" scores = np.asarray(scores, float) labels = np.asarray(labels, int) ...
bd471aba70b20bf7a879e01989f7fd0250551fa869b7a0b6dab6d389f2b0b389
Python
3,094
89
"""Behavioral tests for the gated (Llama-style) MLP recipe.""" from __future__ import annotations import torch import torch.nn.functional as F from torch import nn import torchlens as tl class LlamaMLP(nn.Module): """Tiny Llama-style gated MLP surrogate matching the recipe class name.""" def __init__(self...
22079f5bf4f74eae23c4a82e9d50eede8232fb7cbc40babc4d95c3b5d4919ea5
Python
3,095
78
from math import exp import torch.nn.functional as F import torch.nn as nn import torch class LpLssimLoss(nn.Module): def __init__(self, window_size=5, size_average=True): """ Constructor """ super().__init__() self.window_size = window_size self.size_average = ...
bef5693dadc89fec1718c1094dc3455625bd21d26922d5c2eafb87434792081c
Python
3,095
97
#!/usr/bin/env python # coding: utf-8 # for each hla, whether the TCRs from all positive pairs appears in # at least two subjects with known exist or not status for that hla import os import sys import math import random import argparse import numpy as np import pandas as pd from collections import defaultdict ...
a2ef45ac56b2d8e38b8ce04dcd678f982ebb38c71cb6b22d920adad1ac9fb659
Python
3,096
129
from typing import Literal import pandas as pd import numpy as np def ffill( x: np.ndarray ) -> np.ndarray: """ Forward fill time series. Parameters ---------- x(np.ndarray): Time series to be filled. Shape(n_times, n_features). Returns ------- Filled time serie...
b0717f2d5cb89821c9f67e2de142f2ddee9d8dba44eba9e4eb71a79101ad193c
Python
3,096
90
"""The ``celery upgrade`` command, used to upgrade from previous versions.""" import sys import click from celery.app import defaults from celery.bin.base import CeleryCommand, CeleryOption, handle_preload_options from celery.utils.functional import pass1 @click.group() @click.pass_context @handle_preload_options d...
044aa4cd49858cb69eb85d7d13361698168efc888d6ba8141a752e53e96385ec
Python
3,097
106
import sys sys.path.extend(["../TDNODE", "src"]) from torch.utils.data import DataLoader from data.dataset import TGIData from data.collate import make_batch import src.utils import warnings from prodict import Prodict warnings.filterwarnings("ignore") def prepare_TGI( data_root_path: str, augment: bool = ...
0bf790f246c11344c35b5a692bfdb9d3c76b46a64fbc196d0809aad75d100bdf
Python
3,097
66
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"read_file": "Importing.ipynb", "extract_rawfile_unique_values": "Importing.ipynb", "import_spectronaut_data": "Importing.ipynb", "import_maxquant_data": "Importing.ipynb", ...
417078e94305a126ed1bd1641e1e261ed25e337c97691dc5d84a8643faafb89e
Python
3,097
118
# -*- coding: utf-8 -*- """ Various methods of drawing scrolling plots. """ #import initExample ## Add path to library (just for examples; you do not need this) import pyqtgraph as pg from pyqtgraph.Qt import QtCore, QtGui import numpy as np win = pg.GraphicsWindow() win.setWindowTitle('pyqtgraph example: Scrolling P...
ac51c6780a5e06928d0378b9b6d0f125ce3f573621b8b9959be5a9a9cd96a052
Python
3,097
108
"""Benchmark ``tl.trace`` capture overhead on a 20-layer MLP.""" import argparse import os import statistics import sys import time from collections.abc import Sequence import torch from torch import nn PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) if PROJECT_ROOT not in sys.path: sy...
bd99bfe385c7db668ad433cdeb3c8ecf0d7f912f5eeee3a86c4c91a6fe73bd0a
Python
3,097
93
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: Pramod Bharadwaj Chandrashekar @email: pchandrashe3@wisc.edu """ import sys from collections import Counter import pandas as pd import numpy as np import scipy as sp from sklearn import preprocessing from imblearn.over_sampling import SMOTE def perform_overs...
ceb22bdcf6c54e28ea58878f467b6ea0fed97757ea7c8be98c2c50deb5d1e29d
Python
3,097
99
# -*- coding: UTF-8 -*- import numpy as np from sklearn import svm import math import random import operator import csv from sklearn.cluster import KMeans from sklearn.metrics import adjusted_rand_score ''' @author:hunter @time:2017.03.31 ''' class kmeans(object): def __init__(self): pass def load...
e72d0e9f8491d5346176383ccf9cc5a9a73fb928eafe1167c1cca70949822e49
Python
3,097
109
from rectipy import Network, random_connectivity, input_connections, wta_score import numpy as np import matplotlib.pyplot as plt # preparations ############## # network parameters N = 100 p = 0.1 Delta_in = 2.0 J = 2.0 # input parameters m = 5 p_in = 0.5 s1 = [0, 2, 1] s2 = [4, 2, 3] s3 = [3, 2, 0] signals = [s1, ...
adb49d0bd0e778b8aba5ec183830e0e19178678fcab23e6d3f7fc798a850094e
Python
3,099
110
import sys import copy import argparse import logging import pathlib import numpy as np import joblib as jb import mudcod.sutils as sutils import mudcod.community_detection as community_detection logging.captureWarnings(True) parser = argparse.ArgumentParser( description="Cell-type-specific subject split experime...
00fb4dfaa64f98fe32f69e514e70137cacedfc48d95ec0cba3e1d28d6dc281f0
Python
3,100
94
#!/usr/bin/env python3 """Helper script to adapt datavzrd report configuration files for Galaxy. Subcommands: rewrite: rewrite the dataset paths of a config file to point to the Galaxy input files. Datasets are matched to the input files in the order in which they appear in the config fil...
1c47f57b1051638621aead4803a54dc458e26a33658fa603d684a06eb1dc1c17
Python
3,100
90
import json import os import struct import sys import traceback import urllib.request from packaging.version import parse as parse_version from PyQt5 import QtCore class UpdateWorker(QtCore.QObject): finished = QtCore.pyqtSignal() data_ready = QtCore.pyqtSignal(dict) @QtCore.pyqtSlot(str, str) def p...
8b1190471ac40b5c2f31382bf30c9a206b5abacf5b1fe1139a576a26ead4a5c1
Python
3,100
133
import pytest import numpy as np from functools import partial from pyriemann.datasets import make_matrices, make_masks def requires_module(function, name, call=None): """Skip a test if package is not available (decorator).""" call = ("import %s" % name) if call is None else call reason = "Test %s skippe...
c7fbbf4c0ff9e85127498569e138685c420cdacb0cc6a650b0fa72f48fe8493c
Python
3,100
99
from keras.losses import binary_crossentropy import keras.backend as K import tensorflow as tf epsilon = 1e-5 smooth = 1 def dsc(y_true, y_pred): smooth = 1. y_true_f = K.flatten(y_true) y_pred_f = K.flatten(y_pred) intersection = K.sum(y_true_f * y_pred_f) score = (2. * intersection + smooth) / ...
d86f157e3e9d3caf095e8d4ba980d002b8e45e2c75c57bcb4e3fc827e5cb91ac
Python
3,100
82
"""Wrapper for rescaling actions to within a max and min action.""" from typing import Union import numpy as np import gym from gym import spaces class RescaleAction(gym.ActionWrapper): """Affinely rescales the continuous action space of the environment to the range [min_action, max_action]. The base envir...
621161e94b595fa3dab071aad01a361a0010e6840d20c87cbb3c4d793c5a7ffa
Python
3,101
90
"""Define model components object.""" from specparam.utils.array import unlog from specparam.modutils.errors import NoModelError ################################################################################################### #########################################################################################...
7c880e22676871123dbca683f396cddee11e6108802d8a21b58715eb74180e8d
Python
3,101
99
""" modif_analysis_plots.py This script is used to modify plot designs on the fly for ROI and running analyses from dictionaries, e.g. for presentations or papers. Authors: Colleen Gillon Date: October, 2018 Note: this code uses python 3.7. """ from pathlib import Path import warnings from matplotlib import pyp...
06ebb7843ee3715aedcd927b3d43f9c10163602a43c876d4140c4fbd9e7b1c7e
Python
3,102
102
"""CRFasRNN, 2015, Shuai Zheng et al. Paper: Conditional Random Fields as Recurrent Neural Networks. Dense-CRF mean-field inference is unrolled as recurrent softmax, Gaussian message passing, learned compatibility, and unary re-injection. """ from __future__ import annotations import torch from torch import Tensor, ...
50d9f746c1b273bc8584a4f20efbee09076742c474677ef84a75c45a3b85f6e1
Python
3,102
63
#==============================================================================# # Author: Dominik Müller # # Copyright: 2024 IT-Infrastructure for Translational Medical Research, # # University of Augsburg ...
543bde516e5bd66680ffe77b8c5929cd3c19f78927177914450a78dfb17a2a62
Python
3,102
97
from . import lack # Lazy loading for MERFISHVI to avoid importing scvi unless actually needed class _MERFISHVILazyLoader: """Lazy loader for MERFISHVI module to make scvi-tools optional.""" def __init__(self): self._module = None self._import_attempted = False self._import_error = No...
cf47cdd6ffec5c0f52fcf0764ed2dc36099be8a493810e6d5138b30341482a60
Python
3,102
113
import numpy as np import pandas as pd import scipy.sparse as sp import torch import torch.backends.cudnn as cudnn from tqdm import tqdm from .STAGATE import STAGATE from .utils import Transfer_pytorch_Data cudnn.deterministic = True cudnn.benchmark = True import torch.nn.functional as F def train_ST...
f53c2417cabb1a7fcc925ac8737e85078b65799083cd88f8e0d79e5694a84ace
Python
3,102
77
# visualisation related functions import matplotlib.colors as colors import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import torch from matplotlib.lines import Line2D #from umap import UMAP import warnings from numba.core.errors import NumbaPerformanceWarning warnings.filte...
6322496315851504639ab29c86d5237224213b80434113a3f48b70946a8b0828
Python
3,103
114
import multiprocessing as mp def run_experiment(): import os import tensorflow as tf import tensorflow_datasets as tfds from tensorflow.keras import mixed_precision from gradient_accumulator import GradientAccumulateModel from .utils import normalize_img # disable GPU os.environ["C...
aabc005db47a16f2155346338fdeab18867af3fc87687e472636f693e64e524e
Python
3,103
70
#!/usr/bin/env python3 import argparse from tabulate import tabulate parser = argparse.ArgumentParser() parser.add_argument('-p', help="Pairtools stat output") parser.add_argument('-d', help="preseq report output") args = parser.parse_args() output_dict = {} with open(args.p,'r') as f: for line in f: at...
1125d01319225a36fd5cd3ba1b8072d0e07558630508487412fd4f13aad3d316
Python
3,104
107
#!/usr/bin/env python3 """ Authentication System Test Runner This script runs all authentication-related tests and provides a comprehensive report on the authentication system's functionality. """ import os import subprocess import sys from pathlib import Path def run_test_suite(test_path, description): """Run ...
15336f642ce4a8ba422d482287a0c22532715b6effdefa48e403637b7390fc3e
Python
3,104
106
from modular_splicing.utils.construct import construct import numpy as np class InSilicoDeltaPsiAnnotator: """ Annotates the results of a knockdown analysis with a delta psi value. """ def __init__(self, *, filter_spec=dict(type="DoNotFilter"), agg_spec): self.filter = construct( ...
cf6c7c3ef4d2635f0fb338008a3f694510c582fba21ec89343436b6c574c085a
Python
3,104
91
# --- THIS FILE IS AUTO-GENERATED --- # Modifications will be overwitten the next time code generation run. from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType import copy as _copy class Fill(_BaseTraceHierarchyType): _parent_path_str = "table.cells" _path_str...
0dc092ae80fe047e7b084e93cae6ce3ec9e163648c1b95ff0dcde25966192ece
Python
3,105
102
""" GPU-agnostic helper fuctions go here. """ import inspect, functools, logging import numpy as np try: import cupy as cp import cupy as xp using_cupy = True from rmm.allocators.cupy import rmm_cupy_allocator cp.cuda.set_allocator(rmm_cupy_allocator) from cupyx.scipy import ndimage except Imp...
76a583ebcf0cf61dac7d0aebefa08c3fbf47c53474c4120d9aa99af98b9bff7b
Python
3,105
110
import numpy as np import matplotlib.pyplot as plt import SimpleITK as sitk import cv2 from medcam.medcam_utils import interpolate from collections import OrderedDict def NormalizeData(data): return (data - np.min(data)) / (np.max(data) - np.min(data)) num_dict=OrderedDict({'435':25,'412':24,'474':20,'501':20...
80742b3b65af33a2e0e332d14decfc23aafc716c841c358cac10e502de2cc1a8
Python
3,105
94
# This example requires the following dependencies to be installed: # pip install lightly # Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import pytorch_lightning as p...
2086134d9aabfb0f185d955cac798ec9eaecfcc046536b1cb3198708c4301f4b
Python
3,106
104
import numpy as np import torch from torch import nn from torch.nn import functional as F class DNN(nn.Module): ''' Autoencoder for dimensional reduction''' def __init__(self, cdim, chid1, gdim, ghid1, hid2): super(DNN, self).__init__() #self.qc = qc self.cdim = cdim ...
3732613f4ab643e1e85067ae04e368ecb31795a9495bffac9ab5c7989c8903dd
Python
3,106
101
"""grind-p3 T11.9: registered-container aux is type-strict, subclasses refuse. ``_safe_aux`` admitted ``list``/``tuple`` SUBCLASSES through ``isinstance`` and encoded them as their plain base kind -- erasing the exact class and any instance state (a namedtuple aux flattened to a bare ``tuple`` row), so two registratio...
3bd4845b9b2f6cc94950f95d148d51b81a38cbe95f7229d5f461de2e63ba7370
Python
3,106
103
#!/usr/bin/env python """ Add and update the "itk_module" and "itk_group" fields in the SimpleITK json file based on ITK source directory. """ import os, sys import re import json, collections def IncludesToPaths(path): """Build a dict that maps include files to paths""" includeToPath = dict() prog = re.compi...
80ef5d3cc79025f14c7cb668e9f5783f6bf3bce8367a540949c9e181b4acf0da
Python
3,107
79
#!/usr/bin/env python # -*- coding: utf-8 -*- # # check_h264_md5.py # # Copyright 2020 Giorgio Gilestro <giorgio@gilest.ro> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version ...
8d2c0a76e83a215591ee2cbcd06071ff0d21eb7baf0916a159916ba1f4d189dd
Python
3,107
86
#!/usr/bin/env python # Created on: August 20, 2013 __author__ = "Sven Kreiss, Kyle Cranmer" __version__ = "0.1" import effectiveModel import optparse parser = optparse.OptionParser(version=__version__) parser.add_option("-i", "--input", dest="input", default="inputs/atlas_prodModes_hists_and_response_functions.ro...
9064d896c42589431e2ca77dcc3828d0118728996538dd261778a3ddab4a872d
Python
3,107
80
""" Tests for backward compatibility with deprecated parameter names. """ import unittest from unittest.mock import patch from codecarbon.core.emissions import Emissions from codecarbon.emissions_tracker import EmissionsTracker from codecarbon.input import DataSource class TestElectricityMapsBackwardCompatibility(u...
f812c11786a4fe92ffd8e756f6629d14d02edbfef37a4885808da5a3cd23a1f2
Python
3,107
63
p_apical1 = [[734.0, 692.0, 0.0, 0.0, 2.0943951023931953, 0.0], [747.0, 695.0, 0.0, 0.0, 1.5707963267948966, 0.0], [710.0, 684.0, 0.0, 0.0, 1.3962634015954636, 0.0], [728.0, 719.0, 0.0, 0.0, 1.3089969389957472, 0.0], [219.0, 192.0, 0.0, 0.0, 1.2566370614359172, 0.0], [125.0, 150.0, 0.0, 0.0, 1.2217304763960308, 0....
4083ad7864550033a5946601b5ec8ca0c4b5765ab3d4aa86df83883aea113b14
Python
3,108
91
# 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 of conditions and the f...
8d5e419c4b5b853b3fbee9197e3998cb5785c495a11ef0bf49bc7dd971e7d62e
Python
3,109
91
# --- THIS FILE IS AUTO-GENERATED --- # Modifications will be overwitten the next time code generation run. from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType import copy as _copy class Fill(_BaseTraceHierarchyType): _parent_path_str = "table.header" _path_st...
45b3474f836fa2e02f4857dc3308036a52a7a5e25c66bca222ea8501fe8e55f3
Python
3,111
110
from rectipy import Network import numpy as np import matplotlib.pyplot as plt import torch # preparations ############## # check CUDA devices print(f"CUDA available: {torch.cuda.is_available()}") dev_id = torch.cuda.current_device() dev_name = torch.cuda.get_device_name(dev_id) print(f"CUDA device: {dev_name}, ID: ...
5d200476fd90fc81d5cc9584e27121f435300223d3bc29af6a733834972599a0
Python
3,111
71
import os, sys, pkg_resources, subprocess from time import sleep import yaml def are_python_requirements_installed(requirements_file): with open(requirements_file, 'r') as f: requirements = f.read().splitlines() for requirement in requirements: try: dist = pkg_resources.get_distribu...
73ca3d3ef356a259fae1422254624585cafd821994c61fe96ad8a7d76c5dff17
Python
3,111
91
from ._RL_agent import * from numba import njit @njit def mf_session_value(choices, second_steps, outcomes, n_trials, transition_type, params): # Unpack parameters. alpha, weight_mf, lbd = params[:3] # Variables. Q_c = np.zeros((n_trials, 2)) # Value of the choice. V_s = np.zeros((n_trials, 2)) # Value of...
0c5712729f9a54e5d5c6187c01f1e1f91d30e9a44df69ca8ba56c8970e9d76d3
Python
3,112
124
"""Shared fixture builders for the F29 agent-surface suites (no tests here). Every builder is DETERMINISTIC (explicit seeds, eval mode) so the determinism and transcript suites can assert byte-identical output across processes. """ from __future__ import annotations from pathlib import Path import torch from torch ...
694351fcb3ea38b80e93ed696585be2a53088fac42954a8532ceb14fb5d77fe0
Python
3,112
63
# skip test: data unavailable from eelbrain.pipeline import * class Mouse(MneExperiment): # Name of the experimental session(s), used to locate *-raw.fif files sessions = 'CAT' # Pre-processing pipeline: each entry in `raw` specifies one processing step. The first parameter # of each entry specifies...
4c518d1e864eb2d36b8313e3a73a83feca6b9e16b6434dc1014113ce584e1c84
Python
3,113
71
import os, sys, pkg_resources, subprocess from time import sleep import yaml def are_python_requirements_installed(requirements_file): with open(requirements_file, 'r') as f: requirements = f.read().splitlines() for requirement in requirements: try: dist = pkg_resources.get_distribu...
06a581a91ede92f0abab93d7707fbbf3f7fbca257c2cb06ff179cca4fd92e26b
Python
3,114
86
"""Test is based on a metadata JSON file generated from running atac-seq-pipeline v1.8.0 with the following input JSON. gs://encode-pipeline-test-samples/encode-atac-seq-pipeline/ENCSR356KRQ_subsampled_caper.json """ import pytest from caper.resource_analysis import LinearResourceAnalysis, ResourceAnalysis def test...
ac3b0f12bf2a89e10c6b8f04d142b6103f9f1495030b8ff2c559d9952e060a00
Python
3,114
87
from __future__ import annotations import collections.abc as cabc import typing as t if t.TYPE_CHECKING: # pragma: no cover from _typeshed.wsgi import WSGIApplication # noqa: F401 from werkzeug.datastructures import Headers # noqa: F401 from werkzeug.sansio.response import Response # noqa: F401 # The...
c0d9dd81a119927d25b35bcf0788d75f3a70ea7a294d3edf61230745a0f1b04c
Python
3,114
101
import logging from typing import List, Dict, Any import os from pymatgen.core.structure import Molecule from pymatgen.analysis.graphs import MoleculeGraph from pymatgen.analysis.local_env import OpenBabelNN from pymatgen.io.ase import AseAtomsAdaptor from ase import io as ase_io from instance_mongodb import insta...
d79a2867067a73c866a00c607bbbec27705e8cab09e5998f7ab8888c983c2f90
Python
3,114
81
# coding=utf-8 # Copyright 2024 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...
f63194beb0908fcc8d32a4374b264a8a11744205a4ea3c0261b90095c65e9963
Python
3,114
92
"""The RNG channel monitor warms torch's lazy dynamo import OUTSIDE its window. The first wrapped op of a capture can trigger torch's own lazy ``import torch._dynamo`` (``torch/_compile.py``), whose import cascade draws host entropy at module-exec time (``uuid.uuid4()`` in ``torch.distributed._composable.contract``, p...
4b13873a07805c3a9faaf1e72c4c54c122969963a80dbf1b48c5e8a07244384e
Python
3,115
91
"""IO functions for 10x Visium technology. """ import os from typing import List, NamedTuple, Optional, Union import numpy as np import pandas as pd import scipy.io from anndata import AnnData from typing_extensions import Literal from ..configuration import SKM from ..logging import logger_manager as lm from .utils ...
9c34525e526a6cfbd5ab53703017128b61955cbc555dc122eccda86adc257667
Python
3,115
92
# --- THIS FILE IS AUTO-GENERATED --- # Modifications will be overwitten the next time code generation run. from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType import copy as _copy class Root(_BaseTraceHierarchyType): _parent_path_str = "icicle" _path_str = "i...