sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
70cdb31208645ea9345a1eafe759c9a9d74ba1273c9928b1b69e83d75b1cb3b9
Python
1,744
54
from sklearn.datasets import make_regression from sklearn.ensemble import RandomForestRegressor from siapy.optimizers.configs import OptimizeStudyConfig, TabularOptimizerConfig from siapy.optimizers.optimizers import TabularOptimizer from siapy.optimizers.parameters import TrialParameters from siapy.optimizers.scorers...
48fa578cf39d50d4ae95e3fe985f26d519480fc6536285a31e2bfb9f221ab097
Python
1,745
54
""" Provides the Augmentations and Transforms used by the :class:`rising.loading.DataLoader`. Implementations include: * Transformation Base Classes * Composed Transforms * Affine Transforms * Channel Transforms * Cropping Transforms * Device Transforms * Format Transforms * Intensity Transforms * Kernel Transforms *...
4f0a8fe515b24b774580abfed9fab6f5374de5f3abb53bae9e588d916eb082a1
Python
1,745
48
import rdkit from rdkit import Chem from rdkit.Chem import rdMolDescriptors from rdkit.Chem import AllChem from rdkit.Chem import rdFingerprintGenerator import copy import pandas as pd import numpy as np from cddd.inference import InferenceModel from cddd.preprocessing import preprocess_smiles size=512 apgen = rdFinge...
a19ca09f1bfa728b730c88df951bfa2336fb9d9c126dca7cdda299399cdc6df6
Python
1,745
72
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This code checks the total number of detected UMIs and CBCs in a tagged bam file. The expected format of the tags is a sfollows: XM: UMI XC: cell barcode (CBC), a concatenation of the three splitseq barcodes gn: gene symbol, as attached by the Dropseqtools TagReadWithI...
fd6fd1d8ec46c125d0ed7f00ad9eba04a462c5b90a3add94dacb1d6b8292f8ed
Python
1,745
41
r"""Bonsai integration — driver only, no upstream source. Bonsai reconstructs a maximum-likelihood *tree* over cells instead of a 2-D embedding: cells are leaves, internal vertices are inferred ancestral states, and branch lengths are distances in expression space. It consumes the measurement error on each feature, so...
0eb1da5c3d84106a6358afd0b19ea6a3d416a32fade40687684a91438a4a5273
Python
1,746
45
import logging from datetime import datetime from agent.data.entities.config import ROOT_LOGGER_ID from agent.classifiers.data.liwc_management import export_item_data_for_liwc_features, get_item_liwc_features from agent.classifiers.tree_classifiers import tree_classifier logging.basicConfig(format='%(levelname)s : %...
ad8e023933c085b145c73dc1b67f37d3f3d9320f3ad569bd4dcf692a20867956
Python
1,746
56
from torch.nn.utils.clip_grad import clip_grad_norm_ from auxilearn.implicit_diff import Hypergrad class MetaOptimizer: def __init__(self, meta_optimizer, hpo_lr, truncate_iter=3, max_grad_norm=10): """Auxiliary parameters optimizer wrapper :param meta_optimizer: optimizer for auxiliary paramet...
b9fbd1581c8b67c7142058f64a233e1f6588a8bb70b436429ec671a5cf53b367
Python
1,749
43
import csv import os import re DATADIR='../data' PARSER = '^page (?P<page>[0-9]+) has (?P<pixels>[0-9]+) pixels that differ$' PARSED_LIST = [ ['Page', 'Pixels Differ [N]', 'Differing Pixels Proportion', 'Date', 'Environment'], ] # This should be dynamically/empirically determined, perhaps with a blank page o...
0d91e6208fe52d15971cf1b6cb38ce6adbe57c3bb9d4216f5045305806f31b82
Python
1,750
48
import torch from .augmentations.leads import derive_limb_leads # P, Q, R, S, T waves: (offset from R peak in s, amplitude, width in s) WAVES = ( (-0.2, 0.15, 0.025), (-0.03, -0.15, 0.01), (0.0, 1.0, 0.012), (0.03, -0.25, 0.01), (0.3, 0.3, 0.05), ) def synthetic_ecg( duration=10.0, fs=500, h...
cb2ab0a038c39a3c5d2802946a882f1e74b0c68fb4e7cea2846ed2eac61cda8b
Python
1,750
68
# %% a script for summarizing fit_result3 data # the data structure is # solutions['G' or 'H'][0-50] (each 10 of them have different value of penalty) # the penalty values are 1 to 100 in log space import numpy as np import pickle import pandas as pd from numba import njit # penalties = np.logspace(0, 2, 5) this is ...
2f2b434bfb37542a06848893b130d5a80b12dc3e5ddfe15858d401ec5228f326
Python
1,753
70
import numpy as np import matplotlib.pyplot as plt from spinnaker2 import snn, hardware, brian2_sim n_stim = 10 n_nrns = 20 neuron_params = { "threshold":2., "alpha_decay":0.9, } neuron_params2 = { "threshold": [2.+0.001*i for i in range(n_nrns)], "alpha_decay": [0.9+0.001*i f...
59222387686503b1819d2635fd37d26c440e2eccc6fdc8297c2400555422628d
Python
1,755
55
# -*- coding: utf-8 -*- """ Created on Wed Sep 14 12:18:00 2022 @author: ju-bar TTX file I/O This code is part of the 'emilys' repository https://github.com/ju-bar/emilys published under the GNU General Publishing License, version 3 """ def write_table_txt(str_filename, tab, header, str_sep = ' ', str_fmt = '{:12....
2ca46b057b261449b03870fcea90b1232422e7795d871d3c5e9774619a67e816
Python
1,756
50
#!/usr/bin/env python from __future__ import print_function import argparse import glob import gzip import math import numpy as np import os def parse_args(): parser = argparse.ArgumentParser("Analyzes chunks from curated marginPhase output and logfiles") parser.add_argument('--log_dir', '-l', dest='log_dir', ...
4f60103057ce18c0942c0a91004f337f5544e63ec6171c6ced27c4ba14d8e250
Python
1,756
47
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
d1ec3f7f6d1fa434852f9dca4708df272bdc4789dbc4bf02d240d9e070b4e5c0
Python
1,756
49
from typing import List import torch from tqdm import tqdm from GR_pKa.data import MoleculeDataLoader, MoleculeDataset, StandardScaler from GR_pKa.models import MoleculeModel def predict(model: MoleculeModel, data_loader: MoleculeDataLoader, disable_progress_bar: bool = False, sc...
edaba626add988ac12b36dd670c40ca4ab5b94b45813a52dd085acc42fd93165
Python
1,756
61
# -*- coding: utf-8 -*- # (C) Copyright 2026 IBM. All Rights Reserved. # # Licensed under the MIT license. See LICENSE file in the project root for details. """Base drift compensation for inference.""" from typing import Tuple, TYPE_CHECKING from torch import Tensor from torch.autograd import no_grad if TYPE_CHECK...
78d320f0a0b58cfc638ef1f3066b01ec5e9c5bbb6b223227b6d33d6686cde7e5
Python
1,758
61
#!/usr/bin/env python3 import argparse from pathlib import Path if __name__ == "__main__": parser = argparse.ArgumentParser( description="Extract Resnet18 imagenet features from slide." ) parser.add_argument( "slide_tile_paths", metavar="SLIDE_TILE_DIR", type=Path, n...
8d5a419dd2e1790e36b5fb5ced27373c0c283924929d43d51edcf703524ce017
Python
1,758
58
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys reload(sys) sys.setdefaultencoding('utf-8') import pandas as pd from behaviopy.plotting import qualitative_times from behaviopy.utils import full_subsets from os import path import matplotlib.pyplot as plt data_dir = path.abspath(path.expanduser('~/ni_data/ofM...
e575fcc61407b2ced36a03bd330f22869a6c87da269be5a8cab154297cbfdbf5
Python
1,758
78
# -*- coding: utf-8 -*- """ """ import time import numpy as np import pytest import vtkplotlib as vpl pytestmark = pytest.mark.order(11) def test_qfigure(): vpl.QtFigure._abc_assert_no_abstract_methods() self = vpl.QtFigure("a Qt widget figure") assert self is vpl.gcf() dir...
0ea4d7027122b590dc4fa64dd593106dc5472a69726008266b560927672d1066
Python
1,759
39
from tests.objects import test_node, test_tree from neuron_morphology.validation import resample_validation as rev from neuron_morphology.validation.result import InvalidMorphology from tests.validation.validation_test_case import ValidationTestCase from neuron_morphology.constants import * import unittest from mock im...
bd294b3f72b5d14694a53ade645484bbd1ee117ac31603ea0acf3236c7dd32a9
Python
1,759
58
import random import string import ray def random_text(length: int) -> str: """Generate random text of specified length.""" if length <= 0: return "" if length <= 3: return "".join(random.choices(string.ascii_lowercase, k=length)) words = [] current_length = 0 while current_l...
9fb275e57cd189c97aa5672aba14fcb6a2baebce34cccd39af3e8ee209548d15
Python
1,760
50
import torch from ..utils import loss_and_miner_utils as lmu from ..miners.base_miner import BaseTupleMiner class PairMarginMiner(BaseTupleMiner): """ Returns positive pairs that have distance greater than a margin and negative pairs that have distance less than a margin """ def __init__(self, p...
f57480456b74713cd9e06d3d0ad3903df685a6ff4dbbfcef18be26c7e06bd542
Python
1,760
58
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys reload(sys) sys.setdefaultencoding('utf-8') import pandas as pd from behaviopy.plotting import qualitative_times from behaviopy.utils import full_subsets from os import path import matplotlib.pyplot as plt data_dir = path.abspath(path.expanduser('~/ni_data/ofM...
20f4a01e15f559c954204b021fede69d283cded5c4cd2509a3c1a4da4274bd61
Python
1,762
35
from typing import Union import pandas as pd from numpy import log2 from scipy.stats import entropy def column_imbalance_score( value_counts: pd.Series, n_classes: int ) -> Union[float, int]: """column_imbalance_score The class balance score for categorical and boolean variables uses entropy to calculat...
5a53eda3e1938dcb785cbf6fb2bf22f96102c07f0633a9e52af49b3d394474c7
Python
1,762
64
"""Deprecated plotting compatibility wrappers for ``omicverse.utils._scatterplot``.""" from __future__ import annotations import importlib import warnings _REMOVAL_VERSION = "2.2" _MESSAGE = ( "`ov.utils.{old_name}` is deprecated and will be removed in omicverse " "{version}. Use `{replacement}` instead." ) ...
9b83fa667dbead4240121dad4b94c023c5e099c7e6ae077f0a7fd299bd746c22
Python
1,762
75
import os import torch import numpy as np from scipy.linalg import qr ID2CHAPTER = dict({ '1' : 'breakfast', '2' : 'exercising', '3' : 'cleaning', '4' : 'bathroom' }) def split_video_id(video_id, to_int=False): actor_id, chapter_id, run_id = video_id.split('.') if to_int: return int(a...
f26bc3ad412da1a508125101f7b95ee66992f315c275799150299a699e84fe8f
Python
1,763
66
""" Copyright (c) Meta Platforms, Inc. and affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ import glob import multiprocessing import os import shutil import sys import zipfile from datetime import datetime import ase.io def extr...
3aebb8b22132ee291bec9d0c6daef987680629186c8e31988a5f16d18789a196
Python
1,764
52
import os import subprocess import sys from importlib import resources from flyvis.network.directories import NetworkDir TRAIN_SINGLE = str(resources.files("flyvis_cli") / "training" / "train_single.py") def train_single(root_dir, sintel_path, *overrides): return subprocess.run( [ sys.execut...
494099e88718cdae6f3a6cb5b3921601308b7f4d7a4f2bfec194900222fa8fdb
Python
1,765
54
import os import os.path as osp import numpy as np import torch from torch_geometric.data import InMemoryDataset from torch_geometric.data import Data from tqdm import tqdm """ Code to load in the processed InteractionGraphs to pytorch geometric. """ # TODO: Convert to work with args object class FingerprintDataset(...
d9fd927d8f0c79cb207b6321d5c4accc4123bd9e2fc07b09ac91117c32c06b65
Python
1,765
67
import os import sys import tempfile import pytest import ray def test_basic_dag_with_names_plot(): @ray.remote def a(*args, **kwargs): pass tmp1 = a.options(name="tmp1").bind() tmp2 = a.options(name="tmp2").bind() tmp3 = a.options(name="tmp3").bind(tmp1, tmp2) tmp4 = a.options(name...
30390cadd986e17231b37d2c91a501790b6fd8d687bd8b4c22aadd7083170ce5
Python
1,767
48
import torch from Config import class_number SEED = 1234 torch.manual_seed(SEED) torch.backends.cudnn.deterministic = True import DataSet import torch.nn as nn import torch.nn.functional as F class TextRNN_Attention(nn.Module): def __init__(self): super(TextRNN_Attention, self).__init__() Vocab =...
96adfa5beb88c4db38a2d8b92b51a8c6aa872e93395f7f0319d7729e6bb60545
Python
1,767
72
""" Example for running multiple experiments with same snn.Network using reset mechanism. """ import time import numpy as np import matplotlib.pyplot as plt from spinnaker2 import snn, hardware # track execution time excluding plotting t_start = time.time() neuron_params = { "threshold":1.5, "alpha_de...
cf9c30bced5d35669fd03ef5485aa8fa16ba8865d3458b89c42262bf6632a8b6
Python
1,767
63
from django.urls import path from django.conf import settings from django.conf.urls.static import static from django.shortcuts import redirect from . import views def redirect_result(request, result_id): return redirect("proteome_report", result_id=result_id) urlpatterns = [ path("", views.infer_index, nam...
f06e1d2c5b5b24046b02f7c98469d86a842a3b26e1426c64ddd8671f1e8b52de
Python
1,767
62
# -*- coding: utf-8 -*- """ """ from vtkplotlib.interactive import pick, call_super_callback from vtkplotlib.figures.QtFigure import QtWidgets class CursorTracker(object): def __init__(self, fig): self.fig = fig self.init_labels() self.fig.style.AddObserver("MouseMoveEvent",...
34bd12d6141f4c9ac77540130757d70ae20f97423de390ee9ea825a06c170bec
Python
1,768
78
import numpy, random import json, os from gym_sted.utils import BleachSampler ROUTINES = { "high-signal_low-bleach" : { "bleach" : { "p_ex" : 10e-6, "p_sted" : 150e-3, "pdt" : 30.0e-6, "target" : 0.2 }, "signal" : { "p_ex" : 10.0...
91984a9d4816135f833c1bfd8c943b6ec2fd11f376243646c6a4b890facac94f
Python
1,769
49
#!/usr/bin/env python2 # This script shows boxes in the stimulus locations for the conflict task # Press "q" to exit # This can be put on the screen while putting the subject in the scanner # in order to make sure the relevant locations are visible and centered. from __future__ import division # so that 1/3=0.333 in...
3b311333a4f1b32282e7d47e2fec5a10f1f25172ad7502e1486858671e0cdf16
Python
1,770
55
"""Create design files for analysis in FSL""" import pandas as pd import subprocess import os import numpy as np import glob # define ROOT dir ROOT = '/Users/sebastiandresbach/data/neurovascularCouplingVASO/Nifti' subs = ['sub-06'] for sub in subs: # make folder to dump statistocal maps designFolder = f'{ROO...
4603a3795619fd13772ec3fca1c697583022824be68592e260d44ed413479de6
Python
1,770
43
# -*- coding: utf-8 -*- # (C) Copyright 2020, 2021, 2022, 2023, 2024 IBM. All Rights Reserved. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. #...
586b91fbd1f788a3fda8175e14169a586229534c9347d4e050b58738799c6e1d
Python
1,771
40
import torch from torch.utils.data import BatchSampler class MultiEpochsDataLoader(torch.utils.data.DataLoader): """ The MultiEpochsDataLoader is a PyTorch dataloader that re-uses worker processes rather than re-initializing the every epoch (see https://github.com/pytorch/pytorch/issues/15849#issuecomment-5181...
ba1cc42e2081fa8303b9a66a26e621c4ded09cc0920de5f919022b96d959f27b
Python
1,771
45
import pandas as pd import scanpy as sc import numpy as np def spatial_plot(adata, info, color_by="type", size=None, mode=1, palette=None, save_path=None, figsize=None): """ Plots original/mapped spatial coordinates. Args: adata: Spatial dataset to be plotted. info: A DataFrame containing ...
40aec84eddff392b1c438946e7bc5f5220e9b110641f12d23a1e0de1a8b96cb3
Python
1,772
57
import argparse from lisa.core.data_interface import DataInterface import numpy as np import pandas as pd import os def main(args): cistrome_metadata = pd.read_csv(args.cistrome_metadata, sep = '\t').set_index('DCid') cistrome_metadata.index = cistrome_metadata.index.astype(str) data = DataInterface(arg...
aed73dc19c24a5b267d252214cae272328122be39e6faa58ba40c807a0c14252
Python
1,772
39
import matplotlib.pyplot as plt import numpy as np def plotcluster2(X, lab): """ This function plots the embedding. Parameters are: 'X' - N by D matrix. Each row in X represents an observation. 'lab' - True annotations of data X. """ if np.all(lab >= 0) and n...
b7cfa29fec673751e36d7808b7aca35695e1d6f98ac5baa94d3978f714544b18
Python
1,772
67
import os import requests import numpy as np import pickle import shutil import tarfile def load_batch(file_path): with open(file_path, 'rb') as f: dict = pickle.load(f, encoding='bytes') x = dict[b"data"] y = dict[b"labels"] # Reshape and invert channel dimension x = x.reshape(x.shape[0],...
13e63c194f2e62da816a99a6c1199c9a57ca39f02323e95b187ef6bb0ae07e48
Python
1,773
50
""" This module contains tests that run mozaik models and compare their output to a saved reference. """ import numpy as np import os from mozaik.storage.queries import * from mozaik.storage.datastore import PickledDataStore from mozaik.tools.distribution_parametrization import PyNNDistribution from parameters import ...
180888c435cd4ada4380bd00bd31d96418cc10347ad4fec315f69e8ff2f73662
Python
1,773
48
""" Copyright (c) Meta Platforms, Inc. and affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ from __future__ import annotations import torch from torch.nn import functional as F def linear_with_folded_batch( x: torch.Tensor, ...
f9a956e813878838baffa0f3c75522be34076c410eb7e3e26be17480d3c8b6d6
Python
1,773
50
#!/usr/bin/python # Create bitmaps to check defacing of all NIFTI images # python bids_deface_bitmaps.py from pathlib import Path import os import os.path import glob import sys import shutil import fnmatch def remove_after_final_underscore(input_string): # Find the last underscore index last_underscore_ind...
4f0b0a1d191210eb2d5715fee223ac2f9e4a7983f2a73c224b9882484928ac53
Python
1,774
62
from numbers import Number import torch from torch.distributions import Distribution, constraints class Delta(Distribution): """Delta distribution. This is used Args: loc (float or Tensor): location of the distribution. """ arg_constraints = {"loc": constraints.real} # mypy complai...
e819df628d1b6782bcbb589ce2de1c461324285e3c2003fadf5178139e5621d3
Python
1,774
28
class parameter: def __init__(self): self.paradic = None def para_load(self, zone): if zone == 'Single': para = {"type": "Single", "Task":"loadpred", "encoLen": 8, "decoLen": 96, "encoder_pHVAC_in": 6, "encoder_pHVAC_h": 20, "encoder_pHVAC_out": 4, ...
3d356f397ecfcd13f8e2b3d50dfe2b619543f8c95f8cdecd2d31c4dbb74e47aa
Python
1,775
62
import numpy as np import re from rdkit import Chem def clear_map_number(smi): """Clear the atom mapping number of a SMILES sequence""" mol = Chem.MolFromSmiles(smi) for atom in mol.GetAtoms(): if atom.HasProp('molAtomMapNumber'): atom.ClearProp('molAtomMapNumber') return canonical...
8b9f02168d3f15fae714cb953a0a8115471db3a8e81be0039f7681590fda4bcb
Python
1,775
61
import tensorflow as tf # from tensorflow.keras import backend as K import os, sys import h5py import matplotlib.pyplot as plt from utils import * import gc sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import matplotlib.pyplot as plt; plt.rcdefaults() from tqdm import tqdm import warni...
334f629b53de37d267943cff985e236386433a6978f1e17fe3b56d0bfdce4285
Python
1,776
43
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jun 29 11:13:29 2022 @author: Yao Meng """ # import numpy as np import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from brainsmash.mapgen.stats import spearmanr # import matplotlib.pyplot as plt sns.set_theme(s...
92d5a1a170d5fa10e9a4156f31735f0f25e99de4c9c8a212b6ff7b7ca76bf69b
Python
1,776
56
from setuptools import setup, Extension from Cython.Build import cythonize import numpy import os import sys # 查找是否存在.pyx文件而不是.py文件 force_dir = os.path.dirname(os.path.abspath(__file__)) has_pyx = os.path.exists(os.path.join(force_dir, "fa2util.pyx")) source_file = "fa2util.pyx" if has_pyx else "fa2util.py" # 定义编译参数 ...
56807414b06407e0467e441295f494c2db6bdca672227bf2c824606f2460765b
Python
1,779
58
""" Copyright (c) Meta Platforms, Inc. and affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ from __future__ import annotations import tempfile from pathlib import Path import pytest from tests.core.testing_utils import launch_ma...
ffef98be1967ee18e02682888dc6de9a4572bd170df83021d29e982d02f3fa13
Python
1,781
56
import math import torch from pfrl.testing import torch_assert_allclose from pfrl.utils.mode_of_distribution import mode_of_distribution def test_transform(): base_dist = torch.distributions.Normal(loc=2, scale=1) dist = torch.distributions.TransformedDistribution( base_dist, [torch.distributions.tr...
1d25525897743a240e528c86a200e05daaccf27118154eacbd4beff3b1a5cbfd
Python
1,782
60
import os import numpy as np import torch from tqdm import trange from solver import Solver torch.set_default_tensor_type(torch.cuda.FloatTensor if torch.cuda.is_available() else torch.FloatTensor) os.makedirs('results', exist_ok=True) ...
0f39696b7ab73a946ef0292154fd87b04ee8e95c77951d8cd4942881242fc072
Python
1,783
59
import os import torch def save_checkpoint(path, epoch, model, optimizer, params=None): """ Save a PyTorch checkpoint. Args: path (str): path where the checkpoint will be saved. epoch (int): current epoch. model (torch.nn.Module): model whose parameters will be saved. opti...
7241b95083cc3c9e36ab187aed818fc9afe023a5d73840c80cf7fab9368cad6c
Python
1,783
53
"""Maximum intensity projection over one dimension for a window.""" import os import numpy as np from nibabel import load, Nifti1Image, save nii = load('/Users/sebastiandresbach/data/neurovascularCouplingVASO/Nifti/derivatives/sub-06/ses-04/anat/megre/11_T2star/sub-06_ses-T2s_part-mag_MEGRE_crop_ups2X_prepped_avg_com...
849701035146e49d518d5221ecf35fb0cd42e0753d71f394758ce405029af60b
Python
1,784
44
#################################################################################################### # Copyright (c) 2016 - 2024, EPFL / Blue Brain Project # Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch> # # This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis> # # This program is fre...
8e61937bd7215129353fbf75ebf013f3571ba240a432b846a61845734c2d2822
Python
1,784
56
#!/usr/bin/python # -*- encoding: utf-8 -*- import torch import torch.nn as nn import torch.nn.functional as F import numpy as np class MixSoftmaxCrossEntropyLoss(nn.CrossEntropyLoss): def __init__(self, ignore_index=-1, **kwargs): super(MixSoftmaxCrossEntropyLoss, self).__init__() self.ignore_...
cfce00aabacee4d3f3646aefcc7b5006d3ffeea13bf6f4d125442f721248404a
Python
1,785
63
import numpy as np from keras.models import Sequential from keras.layers import LSTM, Dense import matplotlib.pyplot as plt from matplotlib.ticker import FormatStrFormatter, MaxNLocator import time plt.rc('font',size=15) start = time.time() x = np.load('data.npy') data = np.zeros((10000,1)) data[:,0] = x[0,...
ebbe2bee59d949a13341a2cba218423afdddf65751723f59f91fdee343af7a37
Python
1,785
69
# Copyright 2023 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
564893f4ad5cf8d1e6739f6025217cdda6e628333f909c1d048b38265f9e5161
Python
1,786
56
import argparse import functools as ft import swap_errors.analysis as swan def create_parser(): parser = argparse.ArgumentParser(description="fit several autoencoders") parser.add_argument( "data_file", type=str, ) parser.add_argument( "-o", "--output_folder", ...
633a721f3fa8196346f7291a054b4733fde1a6e238671dee19b5f7bfd3afe2ef
Python
1,786
46
import torch from ..distances import CosineSimilarity from ..utils import common_functions as c_f from ..losses.generic_pair_loss import GenericPairLoss class NTXentLoss(GenericPairLoss): def __init__(self, temperature=0.07, **kwargs): super().__init__(mat_based_loss=False, **kwargs) self.tempera...
ecefae5d0120dd2ac770c8e9d853011d20d77917124f3092c38bb1f333a4a93d
Python
1,786
60
import logging from pprint import pprint import pandas as pd import yaml import pytest from click.testing import CliRunner from pathlib import Path from deeprvat.deeprvat.config import cli as config_cli from deeprvat.deeprvat.config import create_main_config, load_yaml script_dir = Path(__file__).resolve().parent tes...
73160c12f5980791ebe112fcbb0a8dceceaf885c80cfe6527be4a57de15f24bb
Python
1,787
58
import numpy as np import matplotlib.pyplot as plt from math import sqrt import matplotlib as mpl def generate_parameter_sensitivity_plot( final_performances=None, param_axis_1=[], colors=None, yticks=[], xticks=[], labels=None, xlabel='', ylabel='', ): ...
9eab0f9d36ebac96d6df8e29e4450eb9e1297868a3ca3ca24ce1f7fa29856b53
Python
1,787
53
# Copyright 2023 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
e08209a5674654d4b9392f46869b6e605b2b00f9cb629f687f55f030f9f0abb5
Python
1,787
64
import pdb import numpy as np import torch import torch.optim as optim class Optimizer(): def __init__( self, model: torch.nn.Module, args: dict, ) -> None: self.model = model self.args = args if self.args['weight_decay'] is None: self.optimi...
4434f4813bbadbd29ae0d6bc7ad2cc1c87a997ca966704e4d528e1426039f800
Python
1,788
56
import pytest import os import boto3 import zipfile from moto import mock_aws import unittest from neuron_morphology.pipeline.post_data_to_s3 import post_object_to_s3, zip_files path_to_current_file = os.path.realpath(__file__) current_directory = os.path.split(path_to_current_file)[0] file_name1 = "test_post_data_t...
e6bde3e6e384c85033e9b9c59a426d9f65a570a0aca268dfac187143246342b0
Python
1,788
45
"""Lightweight CLI output helpers for cluster launcher context notes. These functions produce informational output that disambiguates head-node commands from local-machine commands. They have NO dependency on the ``ray`` C++ runtime and accept ``cli_logger`` / ``cf`` as explicit parameters so they can be tested in is...
00fa1751b48d2bb6fc7101b286463e8c502ed1e51c5ec83c364aec761a570dc6
Python
1,790
63
import time import tensorflow as tf class PerformanceProfiler(tf.keras.callbacks.Callback): def __init__(self): super(PerformanceProfiler, self).__init__() self.epochs_wall_clock_time_sec = list() self.batches_wall_clock_time_sec = list() self._epoch_start_wt = None self....
5cbf55d0287a6b7398983ac47ec4cb29e96f0d5b56d3edeb1b2c50c65fe378a9
Python
1,791
68
import cc3d from tqdm import tqdm import scipy.ndimage.measurements import numpy as np import time import fastremap def cc3d_test_multilabel(labels): labels, remap = fastremap.renumber(labels) res = cc3d.connected_components(labels) N = np.max(labels) for segid in tqdm(range(1, N+1)): extracted = (res == s...
03d707cf26776a5e80579cd5d142190f7319b38380f5090558554f7efbb5324b
Python
1,792
61
import numpy as np import scipy.sparse as sparse from hic3defdr.util.clusters import find_clusters def threshold_and_cluster(qvalues, row, col, fdr): """ Thresholds pixels by comparing their q-values to a target FDR and clusters the significant and insignificant pixels. Parameters ---------- ...
4e5f3d12ae566e28d4ae54505d47750727987690d5f317d87d2539be21103ff4
Python
1,792
60
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys reload(sys) sys.setdefaultencoding('utf-8') import pandas as pd from behaviopy.plotting import qualitative_times from behaviopy.utils import full_subsets from os import path import matplotlib.pyplot as plt data_dir = path.abspath(path.expanduser('~/ni_data/ofM...
6457523827314befd1452c8b4330c447a3916b452a0b8c0f5cd0e8d664e465e0
Python
1,792
60
import json import os import click from ci.ray_ci.bisect.bisector import Bisector from ci.ray_ci.bisect.generic_validator import GenericValidator from ci.ray_ci.bisect.macos_validator import MacOSValidator from ci.ray_ci.utils import ci_init, logger from ray_release.test import ( Test, TestType, ) from ray_r...
96c942cf19d1d446eb5a88c69a00f17fa0a7beef0b9d29d8aa9084cdec9577df
Python
1,792
41
import torch import torch.nn as nn class LSTM(nn.Module): def __init__(self, input_size, hidden_size, output_size, num_layers=1): super(LSTM, self).__init__() self.input_size = input_size self.output_size = output_size self.hidden_size = hidden_size self.num_layers = num_la...
dd95620004a5e9d1e54a65e705abcac8ca9ae7b8f0d5304fb335f1a0e6f1d3dc
Python
1,792
59
import itertools import pytest class TestAllCallbacks: @pytest.fixture def callbacks(self): """Return all callbacks""" import skorch.callbacks callbacks = [] for name in dir(skorch.callbacks): attr = getattr(skorch.callbacks, name) # pylint: disable=un...
f44bedf7a80860f2e8f46567d3bb156539dbc30115946ed0f8a2002c91c8bb43
Python
1,793
77
import numpy as np class Histogram: def __init__(self, _min = 0, _max = 0.1, bins = 10000): self.min = _min self.max = _max self.bins = bins self.data = [] self.dx = (self.max - self.min) / self.bins self.norm = 0 self.act_min = self.max self.act_max...
31417987cd40271b704e8a190d37ab906f3884af85e3be56d6ffc8e00499bd85
Python
1,794
57
from typing import TYPE_CHECKING, List import pyarrow from packaging.version import parse as parse_version if TYPE_CHECKING: from ray.data._internal.planner.exchange.sort_task_spec import SortKey pl = None # Polars 0.16.8 introduced the `descending` parameter for the `sort` method, # replacing `reverse`. # See ...
2ae200465d26e1091a1cd91853dc45e7ddb5dba2f9962c444f4b837bba56d35b
Python
1,799
56
from __future__ import annotations """ Minimal GitHub repository content extractor using PyGithub if available. Collects README (if present) and basic repo metadata into markdown files. """ from typing import List, Tuple def extract(repo_slug: str) -> List[Tuple[str, str]]: """Extracts README and metadata for ...
cf2874860bff0f5ba8164bfe4ceb95ae0f0dd8e5274b39ed0fdf8a99011cdbba
Python
1,799
24
import matplotlib; matplotlib.use("Agg"); import matplotlib.pyplot as plt from matplotlib.patches import FancyBboxPatch, FancyArrowPatch plt.rcParams.update({"font.family":"DejaVu Serif"}) fig,ax=plt.subplots(figsize=(9,4.8)); ax.set_xlim(-0.4,10); ax.set_ylim(-1.3,4.6); ax.axis("off") def box(x,y,w,h,t,c): ax.add_...
493ae78efd5e63e080bcd1aa430788620f4fc1727b843cd1050b92d3e15222bb
Python
1,801
59
import importlib import os import torch import torch.nn as nn from pytorch3dunet.datasets.utils import get_test_loaders from pytorch3dunet.unet3d import utils from pytorch3dunet.unet3d.config import load_config from pytorch3dunet.unet3d.model import get_model logger = utils.get_logger('UNet3DPredict') def _get_pre...
7ab942b8bf74e55d5904ad46d45a43a7cff7f0adce8502228284c6bf810ba11c
Python
1,801
58
import os from functools import lru_cache from typing import Dict, List, Optional, Tuple _NAMESPACE_CACHE_SIZE = int(os.environ.get("LANCE_RAY_NAMESPACE_CACHE_SIZE", "16")) def _has_namespace_params( namespace_impl: Optional[str], table_id: Optional[List[str]], ) -> bool: return namespace_impl is not Non...
aea219a5e7fe78d4eba07f8a5c9f08abfcba3ad235bcca943dd08af803ab9e3a
Python
1,801
76
import os from datetime import datetime from pathlib import Path from importlib import resources import dotenv import torch from pytz import timezone from flyvis.version import __version__ device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") torch.set_default_device(device) del torch ...
95b099d9a9b1dae906d8980e70455d233197fdace1304951055ddacd04eb2478
Python
1,802
61
import sys from parameters import ParameterSet from mozaik.models import Model from mozaik.connectors.modular import ModularSamplingProbabilisticConnector from mozaik import load_component from mozaik.space import VisualRegion import mozaik class ModelMapDependentModularConnectorFunction(Model): required_paramete...
5d30f8df4ad682d6c5fffb67f62fc253e857544c20dd24d3d9cb1e19fac171f5
Python
1,803
82
import numpy as np def make_rendered(env, *render_args, **render_kwargs): base_step = env.step base_close = env.close def step(action): ret = base_step(action) env.render(*render_args, **render_kwargs) return ret def close(): env.render(*render_args, close=True, **ren...
73e536b26ec7c4f063ba456bb91ab4c495f236dd20b7b6cdd501ee0bcda8d80d
Python
1,803
64
# -*- coding: utf-8 -*- """ Created on Fri Feb 02 15:08:00 2024 @author: ju-bar data alignment This code is part of the 'emilys' repository https://github.com/ju-bar/emilys published under the GNU General Publishing License, version 3 """ import numpy as np def get_row_align(a, ref_row=0): """ Calculates s...
ad1b64b5803a530da5605fc42e2d20daf95f1496e79a12fd5bc68d7388ea1b8e
Python
1,803
45
import numpy as np import pickle import pandas as pd import sklearn.model_selection as md import matplotlib.pyplot as plt import os import seaborn as sb # Load and separate the dataset with open('./model_optimisation/balanced_epochs.pickle', 'rb') as handle: balanced = pickle.load(handle) trainset = balanced[balan...
6375ef11f3ef78b3ab082fd97e225c32b1651e5c4b5f72b7ee5ad7c84c32f05f
Python
1,804
53
# Copyright 2023 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
855d07d4610d21d03259fae5bcafd86140661e84d75e1fd2b1a3e2b16ca7dff5
Python
1,804
62
#!/usr/bin/env python import sys import os import argparse import gzip import vamb parser = argparse.ArgumentParser( description="""Creates the input FASTA file for Vamb. Input should be one or more FASTA files, each from a sample-specific assembly. If keepnames is False, resulting FASTA can be binsplit with sepa...
86f31ff39847ebcac1c0fb66d25d2680bb78c6fdf6883b138836b8d9cee30c65
Python
1,804
67
import numpy as np import torch from accelerate import Accelerator from sklearn.datasets import make_classification from sklearn.model_selection import cross_validate from torch import nn from torch.distributed import TCPStore from skorch import NeuralNetClassifier from skorch.hf import AccelerateMixin from skorch.his...
25a93c40834e30971ffe5a01be185514fb34f83e6c5647f1c04bceb0c4dc3904
Python
1,805
63
""" Documentation example and test for embedding model batch inference. """ import subprocess import sys subprocess.check_call([sys.executable, "-m", "pip", "install", "--upgrade", "ray[llm]"]) subprocess.check_call([sys.executable, "-m", "pip", "install", "numpy==1.26.4"]) def run_embedding_example(): # __emb...
8711e10285c6f5ca1e4b1223b58472906e38346b30cf44939a54875da7e018ec
Python
1,806
57
"""Script to validate a single network across all its checkpoints.""" import argparse from flyvis import NetworkView from flyvis.analysis.validation import validate_all_checkpoints from flyvis.utils.config_utils import HybridArgumentParser def main(): parser = HybridArgumentParser( hybrid_args={ ...
b14b1b57b90178763274b5c7ae601a22aff99706b44ebdf91a7e1f1dd82d4246
Python
1,806
52
# -*- coding: utf-8 -*- import numpy as np from vtkplotlib.plots.BasePlot import ConstructedPlot class Polygon(ConstructedPlot): """Creates a filled polygon(s) with **vertices** as it's corners. For a 3 dimensional **vertices** array, each 2d array within **vertices** is a separate polygon. :param ...
d9fa1c8c8e0a1cee5cb02ac78437587a9065171d9ab1e2960df06c81c7a3f1bb
Python
1,806
50
# @String(value="This script converts all .traces files in a directory into SWC. Conversion log will be shown in Console.", visibility="MESSAGE") msg # @File(label="Directory of .traces files:", style="directory") input_dir # @Boolean(label="Open Console", value=false) open_console # @LogService log # @StatusService st...
daf664ac879ad99bd706f72742eec3bbf886ab3df1ec064015355ceaa56360e5
Python
1,806
42
# Copyright 2021 Division of Medical Image Computing, German Cancer Research Center (DKFZ) # and Applied Computer Vision Lab, Helmholtz Imaging Platform # # 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 L...
86fcae8681c8905046c666238daf00d1af4920221a6a1cd6128181b6ebb3b977
Python
1,807
57
import logging class FileLogger: def __init__(self, is_master=False, is_rank0=False, output_dir=None, logger_name='training'): # only call by master # checked outside the class self.output_dir = output_dir if is_rank0: self.logger_name = logger_name self.lo...
1b4b01e861358be196aaa4a193286b6332318f0f4fea5bed02662c417fe3e587
Python
1,808
49
#!/usr/bin/env python from __future__ import print_function import argparse import glob import sys import numpy as np import pysam MISSING_QUAL_CHAR = '"' # got from calling 'samtools bam2fq' on bam w/o qualities def parse_args(): parser = argparse.ArgumentParser("Produce FASTQ file from soft-clipped reads") ...
47d35089a7eff7848efa9741a8252557c99f0d3a025a852c006d88d29b2b6f91
Python
1,808
69
import os import pickle from typing import Tuple, Union import numpy as np import yaml def load_yaml(path): with open(path) as file: content = yaml.load(file, Loader=yaml.FullLoader) return content def dump_config(args, path): with open(os.path.join(path, "args.yaml"), "w") as outfile: ...
8a8f5cdee04217648e17f6bc264688935f78134d68e93b0e74cb725c9ad9dbf4
Python
1,808
49
from __future__ import annotations import logging from pathlib import Path from ._config import GenerateLdscoreConfig from ._style import Colors, EMOJI logger = logging.getLogger(__name__) def _ensure_symlink(link_path: Path, target_path: Path) -> None: """Create a symlink when missing and validate existing li...
b322ed93a8c23d0464e3a945e91a718cf199277f4b714b278bc20ad57e9bd2cb
Python
1,808
50
# -*- coding: utf-8 -*- """ This script will calculate the Bayes Factor for the null behavioural and RIFT restuls from the perceptual_load project. the input is the Pearson rs from MATLAB the output is bayes factor. @author: GhafariT """ import pingouin as pg import numpy as np import pandas as pd imp...