sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
e4e5c8f78bb480be250845b0168cd7cab0c481882fdae88aa04f4b1911f75c13
Python
2,113
45
import os import ntpath from . import util, utilBitDepth def save_images(opt, webpage, visuals, image_path, aspect_ratio=1.0, width=256): """Save images to the disk. Parameters: opt -- stores all the experiment flags; need to be subclass of BaseOptions webpage (the HTML cl...
dfc3f74cfdb3ed478095102c0ba3592383b4eac7946b6bd11fa5a9c02d0e45f3
Python
2,114
63
import os import SimpleITK as sitk import numpy as np from torchio.data.image import ScalarImage from .base import TemplateNormalizeBase class HistogramMatching(TemplateNormalizeBase): """ This class performs histogram matching. Args: TemplateNormalizeBase (object): Base class """ def _...
2de62ba4285666cf9fbf1b8b3d44e027323a0328398d146529a0f26265579440
Python
2,115
60
import torch from torch.autograd import Variable from torch.utils.data import DataLoader from DCiPatho_config import Config config = Config() class Trainer(object): def __init__(self, model): self._model = model self._optimizer = torch.optim.Adam(self._model.parameters(), lr=config.lr, ...
2b5140c0bcdccf801c6d058f682684c95992652280c4a6f4ce5122c3c299a678
Python
2,116
60
# 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...
484078d96a28a7a74484b2c2aa551d0a4b3de2151516ef285da3991db6c12815
Python
2,119
66
import h5py import numpy as np import pandas as pd import pytest from ptsa.io import hdf5 @pytest.fixture def hfilename(tmpdir): return str(tmpdir.join("test.h5")) class TestHDF5IO: def test_maxlen(self): array = ["a", "bb", "ccc", "dddd"] assert hdf5.maxlen(array) == 4 array = ["",...
a3c9a9117d4e987925274ce534a86bb1b017a74677c91138a8047531c023c200
Python
2,119
58
"""Predictions module for SVAE model Author: Hikari Sorensen - Vector Engineering Team (hsorense@broadinstitute.org) Notes: """ import pandas as pd import tensorflow as tf mse = tf.keras.losses.MeanSquaredError() """ # -- predict -- Description: given a trained (supervised) VAE model and (one-hot encoded) inputs X...
752bb0e915334b132a4b7ea8619c71e9525be6b38c4ead3dffd3ebbb9aaba1cd
Python
2,123
69
import tempfile from pathlib import Path import pytest from ..convertutils import normalize_condition from ..redcap2reproschema import process_csv def test_process_csv(): csv_data = """Form Name,Variable / Field Name,Field Type,Field Label,Field Annotation,"Choices, Calculations, OR Slider Labels" form1,field1,...
09fb257ea024d9aab1a65959c598c44eaa93708362b826ac184c6aceab70ef5d
Python
2,124
55
import torch class EventRepresentation: def convert(self, x: torch.Tensor, y: torch.Tensor, pol: torch.Tensor, time: torch.Tensor): raise NotImplementedError class VoxelGrid(EventRepresentation): def __init__(self, channels: int, height: int, width: int, normalize: bool): self.voxel_grid = t...
a241ee16b2e56e087024b29c587e5a0a67539b6f82ba84720529fac288dff7d7
Python
2,126
45
import pytest import requests import shutil from pathlib import Path def _download_and_extract_asset(tmp_dir_path: Path, asset_url: str): asset_file_path = tmp_dir_path / 'asset.tar.gz' response = requests.get(asset_url, stream=True) if response.status_code == 200: with asset_file_path.open(mode='...
40b709c4135c70b5b1d6ce13fd1acdc45e21ae824279e46ffafc5b22c318bea4
Python
2,127
46
# Author: Mingjian He <mh1@stanford.edu> from somata.oscillator_search import IterativeOscillatorModel as IterOsc from somata.oscillator_search.helper_functions import innovations_wrapper from somata import OscillatorModel as Osc import numpy as np # Simulate 10-s data with two oscillators, one slow and one alpha freq...
8e69b072fdae311cb7d9d3aa8f8131fb742f88469c3ff919038fcfce0ed3bce7
Python
2,127
60
# 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...
a5c7431e3e42df95333631c3c469701a0ca28819f070b7aaaf11912da34cad98
Python
2,127
58
# /// script # requires-python = ">=3.11" # dependencies = ["openpyxl==3.1.5"] # /// """Independently compare every CSV cell with the workbook using openpyxl.""" import argparse import csv import gzip import hashlib import struct from pathlib import Path from openpyxl import load_workbook def verify(source: Path, d...
125d568a4b4e2f782ec29589ef89f7b1bf4e0abe1510ae47357b0e2237cc9ac5
Python
2,128
59
"""Delimited-text version 1 decoding through datamonger-core.""" from __future__ import annotations from collections.abc import Mapping from pathlib import Path from typing import Any, cast import numpy.typing as npt import pandas as pd from datamonger import _native from datamonger._decoder_options import delimite...
ea609232d37ea502d72ca09f04bc357bb45bac4eb08981a09d182f1594d8dbdb
Python
2,128
79
from scipy.ndimage.filters import gaussian_filter1d from scipy import stats df = pd.read_csv(os.path.join(os.getcwd(), 'data', 'unit_table.csv'), low_memory=False) # %% areas = ('VISp','VISl','VISrl','VISal','VISpm','VISam','LGd', 'LP', 'HPC') color_palette= 'seaborn' key = 'specimen_id' mice = df[key].unique() ...
9c7baaae9f30f833fb16a9f19c486aa113c4834698d391f0f8e0838f419af5ec
Python
2,129
44
from src.models.tabular.widedeep.base import WDBaseModel from pytorch_widedeep.models import TabPerceiver class WDTabPerceiverModel(WDBaseModel): def __init__(self, **kwargs): super().__init__(**kwargs) def build_network(self): self.model = TabPerceiver( column_idx=self.hparams.c...
4ffc02acf8aa0050aa74aa3da482fd6434c502911bda96bf16aa5bc78428fdb6
Python
2,130
85
"""NiMARE: Neuroimaging Meta-Analysis Research Environment.""" import logging import warnings import lazy_loader as lazy import numpy as np from ._version import get_versions logging.basicConfig(level=logging.INFO) # Ask for float64's machine limits before anything can ask for long double's. NumPy caches # finfo b...
b930ea2d025a1dec164a1e501b077055594a884a65e7db1eb0b9dc214b96e50f
Python
2,135
62
from __future__ import absolute_import import unittest import numpy as np from centriole.rankorder import rank_order class TestRankOrder(unittest.TestCase): def test_00_zeros(self): """Test rank_order on a matrix of all zeros""" x = np.zeros((5, 5)) output = rank_order(x)[0] self.a...
9bf32ba0ac0c865eef304858a80087433f048c69a9b927ebb69f36b899fb8d20
Python
2,136
99
#!/usr/bin/env python2 import sys,os sys.path.append('/home/xzhou/subtleKnife/script/genescript') import parseUcscgenestruct if len(sys.argv)!=3: print '<ucsc gene file> <tkname>' sys.exit() ucsc,tkname=sys.argv[1:] symbol={} desc={} i=0 if os.path.exists('refLink.txt'): ''' 0 symbol 1 desc 2 name 3 name '...
f4136a95e63b5ca88823553a0ce7ed3dc714a82ac440c7f3b4fbbe71fed4dcbc
Python
2,136
64
# 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...
0fb9017712256e55b4eb4dc8abd953e50bbc0368d67c83040c650fd4f7f56d8e
Python
2,138
41
################################################################################## # Date created : 10/21/2022 # Date modified: 10/21/2022 # Purpose : Generate intermediate features from sequences and structures ################################################################################## import optparse...
36418dd44e2b23b4b7208e6c114eeb4b97e8f0b351ba2cf808b36e0e8c912e7d
Python
2,138
60
import nibabel as nib import numpy as np from traitlets import Bool, Dict from mrHARDI.base.application import (mrHARDIBaseApplication, output_prefix_argument, required_file) from mrHARDI.compute.utils import validate_affine _aliases = { ...
5de4910070eeecaf1798eadbaf71b647feddc85395ac50820f512ca3b5633fc3
Python
2,138
49
from torch.nn import init def init_weights(net, init_type='normal', init_gain=0.02): ''' Initialize network weights. Parameters: net (network) -- network to be initialized init_type (str) -- the name of an initialization method: normal | xavier | kaiming | orthogonal init_...
71ec30b79de05569244408873026102ec7f4d849774c960724b5a717911da5aa
Python
2,139
72
import numpy as np def coincident_trues(mask1, mask2, max_shift): """ Given two n-dimensional masks returns an (n-1)-dimensional array with the number of coincident Trues arg apart on axis 0. Used to calculate distances between Spike Trains Parameters ---------- mask1: array_like mask2: a...
a18ce8774d70485b79d5e9183801d22fedb17615e038aa837608d5b7b813ac23
Python
2,139
56
import pandas as pd import numpy as np from sklearn.model_selection import KFold kf = KFold(n_splits=5) df = pd.read_csv('split.txt') print(df.describe()) TRAIN_LEN=65 VAL_LEN = 6 TEST_LEN = 23 print(df['fold_1']) print(df['CASES']) fold_1 = df['fold_1'] train_val_indices = [ i for i, f in enumerate(df['fold_1']) if...
6a859fe1318d02691bd40a7317b7eb6b904e8535401d31b6097b18ca2dbeda85
Python
2,142
67
from traitlets import Bool, Integer, List, Float, default from mrHARDI.base.application import mrHARDIConfigurable, BoundedInt _aliases = dict( seed="N4BiasCorrectionConfiguration.seed" ) _flags = { "rescale": ( {"N4BiasCorrectionConfiguration": {"rescale": False}}, "Rescale images to initia...
59e0dd2f32a80def0970ead9d677c72481e49e211a8940acd2cdf28267dbd424
Python
2,146
76
import os from itertools import product import numpy as np import pandas as pd import pkg_resources def load_subject_list(dataset): path = os.path.join("..", "etspredict", "data", f"{dataset}_subjects.txt") stream = pkg_resources.resource_stream(__name__, path) return list(np.loadtxt(stream, dtype=str)...
66c848feecf9ddd8a219744aaade37fe5f78bb642f53bc83fbb375e5603422f7
Python
2,146
92
import os from . import FASTQ_File class Library(object): def __init__(self, name, id=0): from . import Database as db self._fastq_files = [] self._name = str(name) self._metadata = {} if id == 0: db.add_library(self) else: self._id = id ...
bd2169641a79f2fb9d112bb20db142b1b765a014d1348c83cace330c04de6f37
Python
2,149
63
import os import subprocess from os.path import join as pjoin from tqdm import tqdm #%% ncpu = input('Cpu num:') # input path includes all subject folds prj_dir = 'PATHtoDataset' input_path = pjoin(prj_dir, 'derivatives/fmriprep') # flags for selection # set subjects, sessions, files that waiting for ci...
47999d17ad56fcb7935432a45df468078cefcf787f4d7b4da9ee771104dfe960
Python
2,150
76
from __future__ import annotations from typing import TYPE_CHECKING, Sequence import traits.api from ptsa.filt import buttfilt from ptsa.data.common import get_axis_index from ptsa.data.filters import BaseFilter if TYPE_CHECKING: from ptsa.data.timeseries import TimeSeries __all__ = ['ButterworthFilter'] cla...
713e5a634b75c9cb5862d8467b11c691fd848a2dc37eaadaa20ba485f5164507
Python
2,150
56
""" Move sliding window across images, get expression values in each window, expression values are arcsinh normalized Author: Candace Liu Date: 4/11/21 """ import os import numpy as np from PIL import Image import scipy.ndimage as ndimage import pandas as pd points = list(range(1,13)) step_size = 3 window_size = 6 m...
91ace16a11e78cc4842804ec3ec0b6b5cc98bd54d957c07f6fb9535b4267df8e
Python
2,152
61
import numpy as np import torch import torchvision class ClassifierOutputTarget: def __init__(self, category): self.category = category def __call__(self, model_output): if len(model_output.shape) == 1: return model_output[self.category] return model_output[:, self.category]...
056555aa209f3add7bf4194692fd755a1b585462465f8a44d89584d0b25db529
Python
2,156
55
# 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...
6dbfad421f06f72b558e15349f9cab7bd1e2da6393268c96cbe8b9c0302caca3
Python
2,156
68
""" PyTorch Mixed Convolution Paper: MixConv: Mixed Depthwise Convolutional Kernels (https://arxiv.org/abs/1907.09595) Hacked together by / Copyright 2020 Ross Wightman """ from typing import List, Union import torch from torch import nn as nn from .conv2d_same import create_conv2d_pad def _split_channels(num_cha...
d03409bffc9a8e27c21b0645b1639cf581862212d3ff3ae3d57153b727fc3a1c
Python
2,156
96
#!/usr/bin/env python2 import sys,os sys.path.append('/home/xzhou/subtleKnife/script/genescript') import parseUcscgenestruct if len(sys.argv)!=3: print '<ensGene.txt file> <tkname> knownToEnsembl.txt and kgXref.txt must be under current dir' sys.exit() aa={} with open('knownToEnsembl.txt') as fin: for line in fi...
4fc9ead46c551c6cef648a94d3faadd447a8fb16f4231e266393e669ab900e23
Python
2,158
43
"""Transforms for classification targets.""" import torch class MultiLabelTarget: """Encode a multi-label target as a float32 multi-hot tensor of length num_classes. By default the target is a sequence of positive class indices: an empty sequence means no positive labels, repeats are allowed, and negativ...
f2247d4b9f2420c046207cde1acf6aba3d1c7f527be86d0f86af12d236dbce26
Python
2,158
71
""" Create an RGB image with color-coded labels overlaid on a grayscale image. """ from cellprofiler_core.module import ImageProcessing from cellprofiler_core.setting.subscriber import LabelSubscriber from cellprofiler_core.setting.text import Float from cellprofiler_library.modules import overlayobjects from cellprof...
90991c78308926d224986de932367ffddd5480d660e06798dea98423687b7557
Python
2,161
66
''' adapted from: https://github.com/letiantian/kmedoids ''' import numpy as np import random def kMedoids(D, k, tmax=100): # determine dimensions of distance matrix D m, n = D.shape if k > n: raise Exception('too many medoids') # find a set of valid initial cluster medoid indices since we ...
6b5c95e36e380463b9829e0eb8020a254660476d54d4e3dda2f2799c7d6e52bb
Python
2,162
70
import logging import yaml from pathlib import Path from importlib import resources import tempfile from GANDLF.utils import get_unique_timestamp import sys def _create_tmp_log_file(): tmp_dir = Path(Path.home()) log_dir = Path.joinpath(tmp_dir, ".gandlf") log_dir.mkdir(parents=True, exist_ok=True) lo...
9b9560d8a6d9012e1d0e65d350415511415e04c66a317591093476ebf6d7d42b
Python
2,171
60
import numpy from numpy.typing import NDArray import skimage.segmentation from typing import Annotated, Tuple, Union, List, Any from pydantic import Field, validate_call, ConfigDict, BaseModel from cellprofiler_library.types import ImageGrayscale from cellprofiler_library.opts.measureimageskeleton import TemplateMeasur...
c7e2a186e90569aac87bd4685febcb902a3611e17f23c9cf70c6f57ced35e4bd
Python
2,172
72
# -*- coding: utf-8 -*- import os import numpy as np import pytest from numpy.testing import assert_array_almost_equal import pysteps from pysteps import nowcasts from pysteps.cascade.bandpass_filters import filter_gaussian from pysteps.cascade.bandpass_filters import filter_uniform from pysteps.cascade.decompositio...
17e3fe0bf6df05b23f2e86dc5cb655527d12a993877e87bd95e7ef75669d51b3
Python
2,173
78
""" CUDA / AMP utils Hacked together by / Copyright 2020 Ross Wightman """ import torch try: from apex import amp has_apex = True except ImportError: amp = None has_apex = False from .clip_grad import dispatch_clip_grad class ApexScaler: state_dict_key = "amp" def __call__( sel...
690142cf64100bea69f18dde20658151048deea23a1387e023c61db78c0e2a31
Python
2,177
74
#!/usr/bin/env python3 import os import pandas as pd def configure_output_name(target, sampling_strat, sc_free): if target in ["sex", "Gender"]: name = f"sex_predictions_{sampling_strat}" elif target in ["age", "Age_in_Yrs"]: name = f"age_predictions_{sampling_strat}" else: name ...
26c874bb19254e93f8b48b08bedbc78acbd7ef533e443e698b75868b94fdbf29
Python
2,179
57
from cellprofiler_core.utilities.zmq.communicable._communicable import Communicable from cellprofiler_core.utilities.zmq.communicable.reply._reply import Reply class Request(Communicable): """A class for making requests and receiving replies across a zmq REQ socket. When communicated through a socket, the cl...
850ea9635d7dc58498df550a8219c8dd02b898e8234c23b9996a9cd2732eddf3
Python
2,179
59
import torch.nn as nn class IncDropout(nn.Module): def __init__( self, input_channels: int, output_channels: int, Conv: nn.Module = nn.Conv2d, Dropout: nn.Module = nn.Dropout2d, InstanceNorm: nn.Module = nn.InstanceNorm2d, dropout_p: float = 0.3, lea...
d186f5e656901a36d7ff0581ef777aab8e611bc1152a5f2aa38c07c7e3971442
Python
2,179
73
import numpy as np import torch import torch.nn as nn from tests.utils import reset_seed, reset_layers, run_forward_pass from networks.dfc_network_utils import get_layer_sparsity, sparsifier torch.set_default_dtype(torch.float64) def test_get_layer_sparsity(): # test that layer sparsity is 0 at the start ass...
a67f298ea3825a5b4abca6581a4561256188fad1e22fe4864301177c30dc806e
Python
2,180
58
from __future__ import annotations import copy import json from pathlib import Path from typing import Any import pytest from test_dm_index import dm_index, manifest_template from datamonger import Registry, _api, data_info, list_data from datamonger.errors import UnsupportedRegistryError CASES = json.loads( (P...
64515f02b80d93f36070df916e33ee01f0f272a99eaa9720975f044e0a6f43a0
Python
2,183
60
#!/usr/bin/env python3 # Copyright 2021 Alexander Meulemans, Matilde Tristany, Maria Cervera # # 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 ...
6eaf1ef46e506ede66c5d415870a9abe43700359bb4e5c6b92df26bc6809e3b7
Python
2,183
76
import numpy as np import scipy.sparse as sp import numpy_groupies as npg def perm_adj(adj, perm): """Permute an adjacency matrix given a permutation. The permutation must contain all existing nodes in an arbitrary order and can contain fake nodes.""" n = perm.shape[0] sorted_perm = np.argsort(pe...
d3321688c9be79402097fc7a8de42da573c843cbddb732330ec460974971d6cd
Python
2,190
83
''' Based on gen_gerber_and_drill_files_board.py in kicad/demos directory. ''' import sys from pcbnew import * filename=sys.argv[1] board = LoadBoard(filename) plotDir = "plot/" pctl = PLOT_CONTROLLER(board) popt = pctl.GetPlotOptions() popt.SetOutputDirectory(plotDir) # Set some important plot options: pop...
9c2bd832f38ddc9501abe5258632a4e4cfedbcf405a1d9458f1689a1b253cf7d
Python
2,191
49
# -*- coding: utf-8 -*- import torch from torch.autograd import Function from numpy import prod import utils class HookFunction(Function): @staticmethod def forward(ctx, input, labels, y, fixed_fb_weights, input_, train_mode): if train_mode in ["DFA", "sDFA", "DRTP", "BRP"]: ctx...
a1368617c73b1d60f59b688ade7e100c11fb00e6392b0dbd4182d181b4ad93fb
Python
2,191
76
# -*- coding: utf-8 -*- import os import pytest import pysteps from pysteps.tests.helpers import smart_assert pytest.importorskip("PIL") root_path = pysteps.rcparams.data_sources["mch"]["root_path"] filename = os.path.join(root_path, "20170131", "AQC170310945F_00005.801.gif") precip, _, metadata = pysteps.io.impor...
01de29b9858d323fedbda453ddb331acaaa5ab98d2c58dcd5ee69761f209dafe
Python
2,200
65
# 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: # http://www.sphinx-doc.org/en/master/config # -- Path setup -------------------------------------------------------------- # If extensions (or module...
3a2a51a5069d6046af2390090dbabe376ef42bf10366503f8d2a672087541895
Python
2,200
84
# Basic Habituation state where hole 2 and 4 illuminated and poke will leads to reward and non illuminated hole poke does nothing from pyControl.utility import * import hardware_definition as hw import random states = ['choice', 'reward'] events = ['poke_1', 'poke_2', 'p...
f8a54fba80cac2650f2eab1acca7f34731e760506cef49c2267bd2735e0a61bf
Python
2,200
103
import numpy import numpy.testing import pytest import cellprofiler_core.image import cellprofiler_core.measurement import cellprofiler.modules.shrinktoobjectcenters import cellprofiler_core.object instance = cellprofiler.modules.shrinktoobjectcenters.ShrinkToObjectCenters() @pytest.fixture(scope="module") def imag...
13aa862c777d8daec2c89f1d018335b4c3f49a6e436fc63c233393748e78f9e6
Python
2,202
58
""" JIT scripting/tracing utils Hacked together by / Copyright 2020 Ross Wightman """ import os import torch def set_jit_legacy(): """ Set JIT executor to legacy w/ support for op fusion This is hopefully a temporary need in 1.5/1.5.1/1.6 to restore performance due to changes in the JIT executor. These ...
31735509e455a005c58cfc005ff92f02fd223b137644bb6a77b9f28f2ebf44c1
Python
2,204
132
class TestWorkspace: def test_refresh(self): pass def test_get_windows_used(self): pass def test_get_pipeline(self): pass def test_get_image_set(self): pass def test_set_image_set_for_testing_only(self): pass def test_get_image_set_list(self): ...
741b69cfaf43f00ca62cc264c1ef3c5a0f3e79392a2c9a228e14470908d38f75
Python
2,205
73
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Nov 30 14:24:44 2017 @author: Nikolai M Chapochnikov """ file_L = 'data/Berck_2016/elife-14859-supp1-v2_no_blanks.xlsx' file_R = 'data/Berck_2016/elife-14859-supp2-v2_no_blanks.xlsx' # this is some information from the excel sheet # not sure if it is ...
4c04f36609f2b7f176c97685aef14e690ef558c76c244c4ec1f11ab868b45e95
Python
2,207
84
""" Merge content of multiple hdf5 files. Usage: {0} t01.hdf5 t02.hdf5 out.hdf5 Author: {1} """ import sys import h5py import numpy as np __author__ = 'CunliangGeng' USAGE = __doc__.format(sys.argv[0], __author__) def check_input(args): if len(args) <= 3: sys.exit(USAGE) def merge_hdf5(h5ins, h5out): ...
e5eabf8fc05981c6eff442df9f4ce11dd7e31c5f79ab8155a7c40c011affaec5
Python
2,207
59
import os.path as osp import unittest import numpy as np import pytest from ptsa.data.readers import BaseEventReader from ptsa.data.filters.morlet import MorletWaveletFilter from ptsa.data.readers.tal import TalReader from ptsa.data.readers import EEGReader from ptsa.data.filters import MonopolarToBipolarMapper from t...
7cb244adda39f0d7f61101bafcb5c4478bca062f9b7d8cf39db847702f2f5bae
Python
2,209
71
import argparse import os import sklearn.model_selection as model_selection import xlrd import config import utils if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--class_num", default=3, type=int, help...
9434f6853b5c4504f6f40f5ac220bbd07476e13a0b370fbe83c1178c7ebb01e3
Python
2,209
43
from monai.networks.nets.resnet import resnet50, resnet34, resnet18 from ptflops import get_model_complexity_info res503d = resnet50(spatial_dims=3) res343d = resnet34(spatial_dims=3) res183d = resnet18(spatial_dims=3) macs, params = get_model_complexity_info(res503d, (3, 224, 224, 224), as_strings=True, ...
b802bf64362ad9d8bf3c62b23190435f8fb6b6476d9131e9fbd7da07e9708d66
Python
2,210
73
from pynq import PL from pynq import Overlay from pynq import allocate from pynq import MMIO import numpy as np import time from firefly_utils import * ol = Overlay('accel/sys_wrapper.bit') input_channels = 32 output_channels = 64 time_step = 4 kernel_size = 3 parallel_channel = 16 width = 16 height = 16 threshold = ...
255757b68af697a92fa1794025d55c6a009d76b10799baa57473f53455c88617
Python
2,216
46
import torch from asteroid.engine.system import System from asteroid.losses import PITLossWrapper, pairwise_neg_sisdr class GeneralSystem(System): def __init__( self, model, optimizer, loss_func, train_loader=None, val_loader=None, scheduler=None, co...
2ff05c4f464a1ed8169f260fa681fe294e70da1b218f09ecd0f857dc37184b08
Python
2,218
88
# -*- coding: utf-8 -*- # # ioutil.py # """ Results handling utility functions for model comparison experiments. """ import csv import os import shutil from collections import OrderedDict import numpy as np import pandas as pd def load_target_to_ndarray(path_to_file, index_col=0, classification=True): """Load ...
a01f4689ab47c3c0f980ee5692c634c3a0da0be475c8f0bbc854bf0f77f29528
Python
2,218
70
# written by Nathan Boley, from https://github.com/nboley/GGR_code import sys import gzip VERBOSE = False adapters = { 'Illumina': b'AGATCGGAAGAGC', 'Nextera ': b'CTGTCTCTTATA', 'smallRNA': b'TGGAATTCTCGG' } def detect_adapters_and_cnts(fname, max_n_lines=1000000): adapter_cnts = { 'Illumina...
42364afe4a31f1c30e38e84f4499277b7b60f3a8364cc9b19cfca83163b95598
Python
2,219
50
import os import numpy as np import pytest from numpy.testing import assert_allclose, assert_array_equal from s2cloudless import S2PixelCloudDetector DATA = np.load(os.path.join(os.path.dirname(__file__), "TestInputs", "input_arrays.npz")) @pytest.fixture(name="cloud_detector") def cloud_detector_fixture() -> S2Pi...
234f6b7faf759c0c30e2e84483b20c358c1cc4c6f3c34af221f10b17c957ab8c
Python
2,220
81
from typing import Callable, Dict, List, Optional, Union, Tuple, Type import torch from torch import nn try: # NOTE we wrap torchvision fns to use timm leaf / no trace definitions from torchvision.models.feature_extraction import create_feature_extractor as _create_feature_extractor from torchvision.model...
dc298483d4a48c980e154fa0a6f501eb67b49df4c93ba3c0f9fc518a62d35272
Python
2,223
73
# -*- coding: utf-8 -*- import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) # To update the package version number, edit deeprank/__version__.py version = {} with open(os.path.join(here, 'deeprank', '__version__.py')) as f: exec(f.read(), version) with open('R...
286619d368b9e427aa16a4feb15f4413841e98b0607811e20bb64f2a59edef81
Python
2,228
58
# This file is part of pyunicorn. # Copyright (C) 2008--2026 Jonathan F. Donges and pyunicorn authors # URL: <https://www.pik-potsdam.de/members/donges/software-2/software> # License: BSD (3-clause) # # Please acknowledge and cite the use of this software and its authors # when results are used in publications or publi...
9f8300c8d9b685184c01636019d3105aac5286ab3bb3fe32420d81b0bfd6dd6b
Python
2,230
56
#!/usr/bin/env python """Script to auto-generate our API docs. """ import os import sys pjoin = os.path.join here = os.path.abspath(os.path.dirname(__file__)) sys.path.append(pjoin(os.path.abspath(here), 'sphinxext')) from apigen import ApiDocWriter source = pjoin(here, 'source') #********************************...
aa96f41b9be73db07de7ef48f9a70f7baf8bf3f7780f10babdf54133de288fd9
Python
2,231
64
import prov.model as pm from .Core import Core, getUUID from ..core import Constants class DerivativeObject(pm.ProvEntity, Core): """Class for NIDM-Experimenent DerivativeObject-Level Objects. Default constructor uses empty graph with namespaces added from NIDM/Scripts/Constants.py. Additional alternate ...
59c549433cd1fe720b8cdc30fea8c665f1bcf00d4d874f32e7c31459787f65ec
Python
2,235
69
#emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- #ex: set sts=4 ts=4 sw=4 et: ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See the COPYING file distributed along with the PTSA package for the # copyright and license terms. # ### ### ### ### ### ### ### #...
f941cdf5610a165b861e564500d197484484527394e58a0c15a7fae3fd160abc
Python
2,243
53
import numpy as np from matplotlib import pyplot as plt import pandas as pd import seaborn as sns import matplotlib.cm as cm linewidth = 4 fontsize = 15 font = {'family' : 'monospace', 'weight' : 'bold', 'size' : fontsize } plt.rc('font', **font) # pass in the font dict as kwargs Scs = np.arra...
84462c891127dc461c9e86109851f9d3be3cb55bde8ef557d762654302323a2f
Python
2,247
68
import os from tempfile import mkdtemp from shutil import rmtree import h5py from nose.tools import ok_, eq_ from deeprank.features.neighbour_profile import (__compute_feature__, get_pssm_paths, IC_FEATURE_NAME, WT_FEATURE_NAME, VAR_FEATURE_NAME, PSSM_FEATURE_NAME) fro...
f85f9d1d42929692ee5a5455e6e5213118f81102b56f8170c1331543591725f7
Python
2,247
68
from typing import Dict from deeprank.models.residue import Residue from deeprank.models.secondary_structure import SecondaryStructure from deeprank.domain.amino_acid import amino_acids, cysteine def _is_dssp_header(line: str) -> bool: # RESIDUE AA STRUCTURE BP1 BP2 ACC N-H-->O O-->H-N N-H-->O O--...
9ca38197d654d0ed736a4316530bb96501a2556cfad34366a283e725057afad4
Python
2,254
62
import numpy as np import pickle import matplotlib.pyplot as plt from matplotlib.ticker import FormatStrFormatter,ScalarFormatter ''' This script generates the average over 10 initial conditions GCG 8.11.23 ''' seed_number = 10 #number of seeds nv = 30 npoints = int(300000)#int(1e5) #time points available arr = np.ze...
7f29497e18beb6b04cb2d19372f9306034facc1557ae46a86cd236d48b5a8865
Python
2,255
79
from warnings import warn from typing import List, Union, Dict, Callable from .wrap_torchio import ( mri_artifact, motion, affine, elastic, swap, bias, blur, noise, noise_var, gamma, flip, anisotropy, ) from .rotations import rotate_90, rotate_180 from .rgb_augs import ...
8201d98ef0633b768afa8c0229db9d7237368fd5cf834997c6010b0a768c1018
Python
2,256
45
"""Regression test documenting a known bug: RveInfo doesn't fully reset between Run() calls. dragen/run.py's Run.__init__ only reassigns RveInfo.n_pts_y/n_pts_z *conditionally* (inside `if box_size_y:` / `if box_size_z:`), while RveInfo.box_size_y/box_size_z themselves are always reset unconditionally. So a Run() with...
3ac96fb8062dc0f844f81266df5d5ebda39ce953f791f152d5b903622d22d553
Python
2,266
51
""" @author: Johanna Rahm Research group Heilemann Institute for Physical and Theoretical Chemistry, Goethe University Frankfurt a.M. Save binned image results as localization file .csv in DeepSTORM2D format & tif. """ import pandas as pd import tifffile def merge_random_locs(random_locs): """ Convert into...
5a10fdb4cdb049d182a90821306245f88eeb6e3b17afece5ba9a59ce317459ab
Python
2,269
65
import numpy as np def sample_scale(a=1, b=25, rng=None): """Generates a single random draw from a beta prior over the scale of the random walk. The artificial bounds are for comparability with bayesloop. Parameters: ----------- a : float, optional, default: 1 The first parameter of the...
d001eb318a19fa51f983360d96b9d8ad049619e5ed3a614563cf9e2d44ceeb72
Python
2,271
67
import os import numpy as np import caffe import cv2 from caffe.proto import caffe_pb2 # config ROOT = os.path.dirname(__file__) ARCHITECTURE = os.path.join(ROOT, 'model', 'initModel.prototxt') WEIGHTS = os.path.join(ROOT, 'model', 'initModel.caffemodel') IMAGE_MEAN = os.path.join(ROOT, 'model', 'mean_AADB_regressio...
3cc6231ffa6b04a99ae0b360531980e46cc5edf43a928d3d5eccca6ad4ee941e
Python
2,274
45
import numpy from typing import Annotated, Optional, Tuple, Callable, Dict, Union from pydantic import Field, validate_call, ConfigDict from cellprofiler_library.opts.convertobjectstoimage import ImageMode from cellprofiler_library.types import ImageBinary, ImageColor, ImageGrayscale, ObjectLabelSet, ImageAny, ImageInt...
cd68bda3dcf94b5ddf39839192f96e5cec26ac60856303fd2091d66e14f6c7a1
Python
2,277
71
from unittest import TestCase import numpy as np import torch from .gsvessel import GSVESSEL data = GSVESSEL() class SVESSELTest(TestCase): def test_init(self): self.assertEqual(4040, data.train.num_examples) self.assertEqual(1010, data.val.num_examples) self.assertEqual(1010, data.tes...
6e0b5c5d4567d97ac55ee69543ca885dddadf87edc9109262851ad91263fe13c
Python
2,279
56
""" Two-way Multi-Label Loss Paper: `Two-way Multi-Label Loss` - Takumi Kobayashi, CVPR 2023 https://staff.aist.go.jp/takumi.kobayashi/publication/2023/CVPR2023.pdf Implemented from the paper formulation, numerically matching the official (unlicensed) reference at https://github.com/tk1980/TwoWayMultiLabelLoss """ im...
a33da0f56551f439d4fd04474f769d65ef52859a55a5e24b7f5d8eda6b870797
Python
2,279
46
import torch import torch.nn as nn import torch.nn.functional as F from .layer import GradientLayer, BoundaryGradientLayer class PINN(nn.Module): def __init__(self, network, RADIALDIFFUSION, NO_FLUX_BND): super(PINN, self).__init__() self.network = network self.grads = GradientLayer(networ...
36f3fd28734a34351194b2a1f49d56c576b1f769da04cbd3b44f048d4c1340c2
Python
2,280
51
##################################################################################################################### # Date created : 10/21/2022 # Date modified: 10/21/2022 # Purpose : To generate (full) node feature set from temporary features ##################################################################...
f8ce0478e4f3c5def8b5ce27e82be0dafdb6841d3c0da987254110de3cbbc8e1
Python
2,281
67
#!/usr/bin/env python # coding: utf-8 """Code for Figure 3""" # In[ ]: import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler, RobustScaler, QuantileTransformer from sklearn.model_selection import train_test_split, KFold from statistics import mean, stdev from sklearn.linear_model impo...
00f6295057d95757ebbc52443257e7168328ee9423807911f5015292a10f0afd
Python
2,287
68
import logging import os import tempfile import h5py import cellprofiler_core.measurement import cellprofiler_core.pipeline import cellprofiler_core.utilities.core.workspace import cellprofiler_core.workspace from cellprofiler_core.utilities.hdf5_dict import FILE_LIST_GROUP, TOP_LEVEL_GROUP_NAME LOGGER = logging.ge...
fa291a164c0ccc8ebbfded64e9efb33221766e319bfb2f2155778d94f58aade2
Python
2,292
82
from torch.utils.data import DataLoader from .ImagesFromDataFrame import ImagesFromDataFrame from GANDLF.utils.write_parse import get_dataframe from GANDLF.utils import populate_channel_keys_in_params def get_train_loader(params): """ Get the training data loader. Args: params (dict): Dictionary...
436a76d2b2a0e3eadffa7a7f132bc07d829140cc92815dcfdf83f8f2559e4ef1
Python
2,293
58
import tensorflow as tf from io import BytesIO from zipfile import ZipFile from sklearn.utils import shuffle class DataLoader(): def __init__(self, csv_file='data/nyu2_train.csv', DEBUG=False): self.shape_rgb = (480, 640, 3) self.shape_depth = (240, 320, 1) self.read_nyu_data(csv_file, DEB...
4e6938388de66b399e4f8a89fa9b8e3111c2b8ccb1ebf9e57d4ec325674d760d
Python
2,293
75
# TODO SEP 08 version """A modified image folder class We modify the official PyTorch image folder (https://github.com/pytorch/vision/blob/master/torchvision/datasets/folder.py) so that this class can load images from both current directory and its subdirectories. """ import torch.utils.data as data from PIL import ...
896b6e0b8cbffd1af542970289fe328e9f2e6ae71f2b6ce402dd1ef52ece6f7c
Python
2,293
94
from typing import Dict import torch import torch.nn as nn import torch.nn.functional as F ACTIVATION_LAYERS = { 'ReLU':nn.ReLU, 'LeakyReLU':nn.LeakyReLU, 'PReLU':nn.PReLU, 'RReLU':nn.RReLU, 'ReLU6':nn.ReLU6, 'ELU':nn.ELU, 'Sigmoid':nn.Sigmoid, 'Tanh':nn.Tanh, } class Clamp(nn.Mo...
c5140ddcf8a86cc70134c24b105c5e3e36826c96d7580eaa0265f10cfdcb1a1a
Python
2,298
57
import os import numpy as np from glob import glob from PIL import Image import imageio import time from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau class U_Net(): def __init__(self): self.height = 256 self.width = 256 self.channels = 3 ...
f80f998842888a407a1b5efc12acc25414b85d8f9f87af19be403bba1048b2f4
Python
2,300
58
import torch import numpy as np from argparse import Namespace from datahandlers.data_utils import generate_task from networks.net_utils import generate_network from utils.optimizer_utils import get_optimizers from utils import math_utils as mutils from utils import sim_utils def reset_seed(seed=10): torch.manual...
7c7dc2393ca97ac612f2f35f3cba943284e5a89b40442c3093e4c92dfe25c18b
Python
2,304
64
import numpy as np import matplotlib.pyplot as plt import pandas as pd plt.rcParams.update({'font.size': 12}) def get_shot_res(drp, data): path = f'../results/chemformer_snn/dropout{str(drp)}/{data}/tables/' df = pd.read_csv(path + 'avg_res.csv') df = df[df['cutoff'] == 0][1:] return list(df['rmse']), ...
fabb9e97b8d88f2a7f78e2065d08c8fde5d7b20f64d28871884dab0709599f1b
Python
2,304
46
import os import shutil import pytest from dragen.utilities.InputInfo import RveInfo REPO_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')) OUTPUT_DATA_DIR = os.path.join(REPO_ROOT, 'OutputData') @pytest.fixture(autouse=True) def _cleanup_output_dir(): """Delete whatever OutputData/<d...
7095ba60f86d2c97c983ccad27497b70d733f6dfd0a7550153e6f2561f45d330
Python
2,308
91
# -*- coding: utf-8 -*- import numpy as np import pytest from numpy.testing import assert_array_almost_equal from pysteps.postprocessing.ensemblestats import excprob, mean, banddepth # CREATE DATASETS TO TEST a = np.arange(9, dtype=float).reshape(3, 3) b = np.tile(a, (4, 1, 1)) b1 = b.copy() b1[3] = np.nan a1 = a.c...
ff764db3e83213d5e6e2c959a152692fdde9147353d2c8f1d2e398e326d7fc6b
Python
2,308
74
import os import timm import torch import torch.nn as nn from mmcv.runner import load_state_dict def load_checkpoint(args, checkpoint_path: str, model: nn.Module) -> None: """ Input args: args checkpoint_path: str, path of saved model parameters model: nn.Module optimizer: tor...
d5bbac22ed5d2cbccf0615dd5268db6f408d97d252c8c44cf54c257395e57e6b
Python
2,309
68
import numpy as np import matplotlib.pyplot as plt from ..utils.time import get_dt def plot_mask(t, mask_spikes, ax, t0, tf, offset, lw, delta, color): for sw in range(mask_spikes.shape[1]): t_spikes_ = t[mask_spikes[:, sw]] t_spikes_ = t_spikes_[(t_spikes_ >= t0) & (t_spikes_ < tf)] t_s...
2bdf961cc5075843e229849bbfa26b58ccd66d85a1267e54b3c3ee683d0ac664
Python
2,312
68
import numpy as np import matplotlib.pyplot as plt from ..utils.time import get_dt def plot_mask(t, mask_spikes, ax, t0, tf, offset, lw, delta, color): for sw in range(mask_spikes.shape[1]): t_spikes_ = t[mask_spikes[:, sw]] t_spikes_ = t_spikes_[(t_spikes_ >= t0) & (t_spikes_ < tf)] t_s...