sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
983e143ed44a6aa5029e225bcb094844b8f89debfb79fbe6d31fcb3759e5e4de
Python
8,513
339
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Oct 27 17:13:07 2020 @author: baris """ gra_spikes = gra_spikes_diff[0] f=10 n_phase_bins=360 dur_ms=2000 dur_s = dur_ms/1000 T = 1/f time_bin_size = T times = np.arange(0, dur_s+time_bin_size, time_bin_size) n_time_bins = int(dur_s/T) def mean_phase(...
b6a0f59322da82d5d456ffe7da1cbaf31c47dbef402f36d1fa94214d63357865
Python
8,514
218
"""Callback classes to control training.""" import logging import numpy as np # to ignore imports for sphix-autoapidoc __all__ = ['BaseCallback', 'EarlyStopping', 'AnnealHparam', 'PseudoLabels'] class BaseCallback(object): """Abstract base class for callbacks.""" def on_epoch_end(self, data_generator, mode...
69517097e6fcfdaeec968021c74f167d9e5a764b443b8f4484d892f2bbd82119
Python
8,515
218
"""Callback classes to control training.""" import logging import numpy as np # to ignore imports for sphix-autoapidoc __all__ = ['BaseCallback', 'EarlyStopping', 'AnnealHparam', 'PseudoLabels', 'UPS'] class BaseCallback(object): """Abstract base class for callbacks.""" def on_epoch_end(self, data_generato...
41e670aca8e493b1937bfb29c274fe5a5fe209adebc9306daff081fb273fb486
Python
8,516
254
# Copyright (c) OpenMMLab. All rights reserved. import argparse import os import os.path as osp import warnings import numpy as np import onnx import torch from mmcv import Config from mmcv.tensorrt import is_tensorrt_plugin_loaded, onnx2trt, save_trt_engine from mmdet.core.export import preprocess_example_input from...
854a8cf67924bd7da038d93388cce9e3a03b7033c12d01734ec8da0c28cac6c4
Python
8,517
254
# Copyright (c) OpenMMLab. All rights reserved. import numpy as np import torch def bbox_flip(bboxes, img_shape, direction='horizontal'): """Flip bboxes horizontally or vertically. Args: bboxes (Tensor): Shape (..., 4*k) img_shape (tuple): Image shape. direction (str): Flip direction,...
3a8a7ce0f8bbe6a4c07994141ed578a81a97913da23aba10768a101248d84254
Python
8,527
193
"""General-purpose test script for image-to-image translation. Once you have trained your model with train.py, you can use this script to test the model. It will load a saved model from --checkpoints_dir and save the results to --results_dir. It first creates model and dataset given the option. It will hard-code some...
369e31e62f61576a147bc09936db1d5ec46e47b8a8fd0c94358f7fdb5c186c3f
Python
8,529
211
import matplotlib.pyplot as plt import numpy as np import grid_model import matplotlib.gridspec as gridspec import matplotlib as mpl import shelve import os from neural_coding import _code_maker, load_spikes, rate_n_phase import math from perceptron import run_perceptron dir_name = os.path.dirname(__file__) # Name of...
be95d9fe523085d15f008ef7eede94d9409455e1d760962792c1db7961e893c8
Python
8,531
227
# Copyright (c) OpenMMLab. All rights reserved. import copy import warnings from typing import Dict, Union import numpy as np from mmcv import Config, is_seq_of from mmpose.core.post_processing.temporal_filters import build_filter class Smoother(): """Smoother to apply temporal smoothing on pose estimation resu...
ab69919cc03f60751826176e0bdc37d73bec8039835cb060094b4a34fe74bc4b
Python
8,535
242
# This file is part of sbi, a toolkit for simulation-based inference. sbi is licensed # under the Apache License Version 2.0, see <https://www.apache.org/licenses/> # code for MMD from: # https://github.com/mackelab/labproject/blob/main/labproject/metrics/MMD_torch.py import warnings from typing import Optional impo...
cc6b8a7a9b7a8639b4999f395770b3f13f68cf8d4bdbe7734de5c49130cf4daa
Python
8,542
205
from __future__ import annotations import re from .consts import CUTOFFS, BCONDS from .tfspline import Bcond from typing import ItemsView, ValuesView, KeysView, Union, Iterable from .util import formatZ, padZ, Z2A import numpy as np import pickle as pkl # TODO: support various types of models (current version only...
83e873f6b942ba4065daf4bd81d909ce83a0dad1cf335078e837b2a4c5f18783
Python
8,556
221
import importlib import os import logging from pathlib import Path from functools import reduce, partial from operator import getitem from datetime import datetime import stringcase from data_loader.my_transforms.compose import Compose from logger import setup_logging from utils import read_json, write_json class C...
d28ac4b50d921c26e09a17c6c49faf729d62b047ef9b1db0de4aeda1153b857d
Python
8,560
256
from neural_coding import load_spikes, rate_n_phase from perceptron_new import run_perceptron import numpy as np import matplotlib.pyplot as plt import pandas as pd import seaborn as sns from sklearn import decomposition from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA import pickle import c...
2520d5746f4b55f1d9f79f41e877f87a5f9c04f7ef042daa1afaab84829ff8e6
Python
8,580
240
import shutil import sys from genomad import database, mmseqs2, prodigal, sequence, taxonomy, utils from genomad._paths import GenomadOutputs def write_genes_output(genes_output, database_obj, prodigal_obj, mmseqs2_obj): marker_annotation_dict = database_obj.get_marker_annotation() gene_match_dict = mmseqs2_...
d1d0b3b1e331a5445332c5d5b7a33bdec604219f35af9d15bdabb2a53478e658
Python
8,584
189
# This file is part of sbi, a toolkit for simulation-based inference. sbi is licensed # under the Apache License Version 2.0, see <https://www.apache.org/licenses/> from typing import Dict, Optional, Union import torch from torch import Tensor, nn, ones from torch.distributions import Distribution from torch.utils.te...
421b67e9edbafce62e1a16fca20a44315c6ae3512432947e809b5a30a6deefc6
Python
8,585
197
"""General-purpose test script for image-to-image translation. Once you have trained your model with train.py, you can use this script to test the model. It will load a saved model from --checkpoints_dir and save the results to --results_dir. It first creates model and dataset given the option. It will hard-code some...
fa0d696123a90b5be4c49b8207dc115ef8ada5609687fb30a66116ff8057deb0
Python
8,585
201
import logging from pprint import pprint import torch from pybrid import utils, datasets, optim from pybrid.models.hybrid import HybridModel def setup(cfg): cfg = utils.setup_experiment(cfg) datasets.download_mnist() train_dataset_1 = datasets.MNIST( train=True, scale=cfg.data.label_scale...
ed74b8d4390753d1e97f15087d7156b0afef03fdef381995471147708f746b93
Python
8,590
252
# Copyright (c) OpenMMLab. All rights reserved. import os.path as osp import tempfile import unittest.mock as mock from collections import OrderedDict from unittest.mock import MagicMock, patch import pytest import torch import torch.nn as nn from mmcv.runner import EpochBasedRunner, build_optimizer from mmcv.utils im...
4837fbee8a80507a647f9c84ab3668fc56c64727320d0baa1691230dac5f84af
Python
8,591
204
import numpy as np from tdt import StructType import pandas as pd import sys from copy import deepcopy import os def find_options_FED3(inputs): # Create a list of system variables to exclude from possible TTLMs. TTLM_exclude = ['PC0_','PC1_','PC2_','PC3_','PC0/','PC1/','PC2/','PC3/', ...
dbd8eda5aaa81daf8fea3161c4b233a1951ec66f4db6c8c8bf7c13713f92699c
Python
8,601
266
# Copyright (c) OpenMMLab. All rights reserved. import numpy as np import pytest import torch from mmpose.models.detectors import CID, AssociativeEmbedding def test_ae_forward(): model_cfg = dict( type='AssociativeEmbedding', pretrained=None, backbone=dict(type='ResNet', depth=18), ...
e9d6bfb76ede7ea4cec3b8f73f139e97b291c0515c5f8fe29730f0dba244a503
Python
8,602
273
"""Evaluation functions for the daart package.""" import itertools import matplotlib.pyplot as plt import numpy as np import os import pandas as pd import seaborn as sns from sklearn.metrics import recall_score, precision_score from typeguard import typechecked from typing import List, Optional, Union from daart.io i...
289371c72ecebdff181125f730027e5061848bdd1418212de468b8069f27d9a5
Python
8,622
256
# Copyright (c) OpenMMLab. All rights reserved. import copy import os.path as osp import pickle from abc import ABCMeta, abstractmethod import json_tricks as json import numpy as np from scipy.io import loadmat from torch.utils.data import Dataset from mmpose.datasets import DatasetInfo from mmpose.datasets.pipelines...
56f55c5c9ca5dc47301b17eed40c846a0a36c33ddb8b3a51ae0598f03ecee759
Python
8,625
206
# Copyright (c) OpenMMLab. All rights reserved. import mmcv import torch from ..builder import BBOX_CODERS from .base_bbox_coder import BaseBBoxCoder @BBOX_CODERS.register_module() class TBLRBBoxCoder(BaseBBoxCoder): """TBLR BBox coder. Following the practice in `FSAF <https://arxiv.org/abs/1903.00621>`_, ...
b6f4bebd2b4ea6f47343ce5125ebe93f70c6303aaebd0db8de9af1340591cd68
Python
8,630
226
# This file is part of sbi, a toolkit for simulation-based inference. sbi is licensed # under the Apache License Version 2.0, see <https://www.apache.org/licenses/> from __future__ import annotations from typing import Optional, Tuple, Union import torch from torch import Tensor, nn from torch.distributions import D...
8b8dc87b356961b02835565df81b94501bf5f94aef2e706f6ad08a4472b618b9
Python
8,631
212
# Copyright (c) OpenMMLab. All rights reserved. # Copyright (c) 2018, Alexander Kirillov # This file supports `file_client` for `panopticapi`, # the source code is copied from `panopticapi`, # only the way to load the gt images is modified. import multiprocessing import os import mmcv import numpy as np try: fro...
b88831ea8c3c9b6991ae26d13369cb89ba5819e075c9d1cc1f7e581c58db41aa
Python
8,633
280
# -*- coding: utf-8 -*- """ Created on Tue Mar 1 13:33:57 2022 @author: oliver braganza """ import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from brian2 import ( NeuronGroup, Synapses, SpikeGeneratorGroup, SpikeMonitor, StateMonitor, Network, start_scope, col...
75a1a5b8cd19aa785cd1e5a2c92be3762652bec996858f05937c463893fe4073
Python
8,651
257
import logging import torch from pybrid import utils from pybrid.models.base import BaseModel from pybrid.layers import FCLayer class HybridModel(BaseModel): def __init__( self, nodes, amort_nodes, act_fn, mu_dt=0.01, use_bias=False, kaiming_init=False, ...
1adc538298ff2c684bfd15bd27eeb1fca1bea8392f1c1665fa8007e70dc69d65
Python
8,658
211
# This file is part of sbi, a toolkit for simulation-based inference. sbi is licensed # under the Apache License Version 2.0, see <https://www.apache.org/licenses/> import warnings from typing import Any, ClassVar, Dict, Literal, Optional, Union from torch.distributions import Distribution from torch.utils.tensorboa...
ce97e1623c4c49de1c77ecd8b4c59efcdd10402449894e45cf582e415c31dfd6
Python
8,664
247
#bamToGFF.py #script to grab reads from a bam that align to a .gff file import sys import re import ROSE_utils from collections import defaultdict import os from string import join,upper,maketrans #===================================================================== #====================MAPPING BAM READS TO ...
993a763bff520c3ff724b1b74c9b3da220f18d2d08cf65bfcf5678ca4bf35c68
Python
8,671
203
# Copyright (c) OpenMMLab. All rights reserved. import torch.nn as nn import torch.nn.functional as F from mmcv.cnn import ConvModule from mmcv.runner import BaseModule, auto_fp16 from ..builder import NECKS @NECKS.register_module() class FPN(BaseModule): r"""Feature Pyramid Network. This is an implementati...
aa35d0705bd5b423b75b508869bfbf6fc51b71b7820a78b3e7b064f1991bbbe7
Python
8,674
233
# Marcus Andersson - Percolator Project # Script that tests the performances of percolator # Parameters: input-data, number of runs, list of process-IDs, flags # psutil is imported in the case that the script should wait for other integration-test scripts to finish. # Note: Relies on the output generated by the C++ so...
d9766013a1f601dcca68e728c148ce4423922b6345f9d08a844ee9b5833ac243
Python
8,676
264
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Oct 25 10:21:07 2021 @author: baris """ from neural_coding import load_spikes, rate_n_phase from perceptron_new import run_perceptron import numpy as np import matplotlib.pyplot as plt import pandas as pd import seaborn as sns from sklearn import decom...
72f6ae53177afaa123d31352efe3b0c1681c30a253f9561eb2ff0ee0f56e21c0
Python
8,679
218
# coding=utf-8 # Copyright 2023 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...
a1e6ba6f2f9462e79e3203081fb005bd77c207ed20d0b72b6ec923635a16db50
Python
8,679
281
import numpy as np from cell import * from neuron import h from commonutils import * import pdb import struct import os import sys h.Random().Random123_globalindex(1234) h.load_file('stdgui.hoc') pc = h.ParallelContext() # set number of threads pc.nthread(1, 0) def save_and_update_weights(network_list, batch_...
b7c11a2f9a2a9bbdfa67c0ce9f498e582ebac7f85757d6b7d458e1d49d7926e0
Python
8,694
241
# Copyright (c) OpenMMLab. All rights reserved. import pytest import torch from mmdet.models import Accuracy, build_loss def test_ce_loss(): # use_mask and use_sigmoid cannot be true at the same time with pytest.raises(AssertionError): loss_cfg = dict( type='CrossEntropyLoss', ...
c6ce77e66bba0f2a21fa0394c2b0e115ea35f7e13df806f1f4b16d2754a093e9
Python
8,698
244
""" Created on Tue Mar 1 13:33:57 2022 @author: oliver braganza """ import pandas as pd import os import shelve import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import pickle from datetime import datetime #from S12_simulate_ca3_fac_case import get_synapses mpl.rcParams['pdf.fonttype'] = ...
a656a9811fb7b20f88f0454a4c0cfc974bb0a865cd4a27bd9c9ce1707bdf83bb
Python
8,701
251
# Copyright (c) OpenMMLab. All rights reserved. import json import os import os.path as osp import tarfile from argparse import ArgumentParser from glob import glob from urllib.request import urlretrieve import cv2 import mmcv import numpy as np import torch from mmcv import Config from mmcv.parallel import collate, s...
b386a4d7ee0f269d0a1de3807f074f709fcac6117445d2591c3e9e14f72841bc
Python
8,702
215
from typing import Any import torch import torch.nn as nn import numpy as np import time from sep.Mic_Array import Mic_Array import sep.helpers.utils as utils from sep.training.base_network import BaseNetwork from sep.training.SpeakerLocalization.network import unnormalize_input, normalize_input def roll_by_gather(ma...
e5f00fda225a23af2f455fffa54b3df5e397c2502ec11c8951864d101c1ec68b
Python
8,704
280
import torch import torch.nn as nn class SEBlock(nn.Module): def __init__(self, in_channels, out_channels, net_mode='2d'): super(SEBlock, self).__init__() if net_mode == '2d': self.gap = nn.AdaptiveAvgPool2d(1) conv = nn.Conv2d elif net_mode == '3d': se...
5da95b5b72553e73a5e61ae68bffcbf6dd855fad6a36834258e6db55c73a54af
Python
8,726
251
import copy import numpy as np import os import pytest import torch from daart.data import split_trials, compute_sequences, compute_sequence_pad, DataGenerator from daart.utils import build_data_generator def test_split_trials(): # return correct number of trials 1 splits = split_trials(100, 0, 8, 1, 1, 0) ...
212a9adc62682b69ed3fa75f84fb3e1de0b06dc928cbea26716a335adcf0cca8
Python
8,732
270
import numpy as np import scipy as sp import trefide.extras.tools as tools_ # cython def kurto_one(x): """ Computer kurtosis of rows of x with 2D (d x T) Outputs: idx of components with kurtosis > population mean + std """ # Compute kurtosis kurt = sp.stats.kurtosis(x, axis=1, fisher=True, b...
7970a6ebd6a9434c43b00ac7d5859b57dd2148f74100946bb3f3f6d5da312d6e
Python
8,743
241
#### ADAPTED FROM https://github.com/githubharald/CTCDecoder/blob/master/src/BeamSearch.py from __future__ import division from __future__ import print_function import numpy as np import pathlib from .lm import LanguageModel from operator import itemgetter class BeamEntry: "information about one single beam at sp...
a7291be4aee8f35fdbab34ce8a3f7be3197f237247d1f816390cdcdf6d25805f
Python
8,748
246
# adapted from https://github.com/Oafish1/WR2MD/blob/main/mmd_wrapper/algs/source/maninetcluster/alignment.py # Align data sets import numpy as np import scipy as sp from scipy.sparse.linalg import eigs, eigsh from .maninetcluster.util import pairwise_error, block_antidiag from .maninetcluster.neighborhood import neig...
82d96f1fd3adc996925f46fbb990e8739d32c7571b2c82c3a582e9b2d4bda46a
Python
8,750
210
from typing import Optional, Type import jax import jax.numpy as jnp import numpy as np from functools import partial, cache import utils from flax import linen as nn import transformer_flax as transformer from transformer_flax import translate_config from einshape import jax_einshape as einshape import jax.tree_util a...
9233a3d8b5dda409097e372f8602e0fc871be64bf94914dc6f90ab0fc458358c
Python
8,756
205
#!/usr/bin/env python from __future__ import division from __future__ import print_function import sys import argparse import vcf FORMAT_FIELDS = ["GT", "AD", "DP"] FORMAT = ":".join(FORMAT_FIELDS) CALL_DATA_FORMAT = vcf.model.make_calldata_tuple(FORMAT_FIELDS) def melt_somatic_vcf(in_vcf_path, remove_filtered, tu...
2f9e78edd3ce8daee8cc327164a715a77875f02cc766c8ba607e6096f87f6478
Python
8,764
222
import numpy as np import os import pickle import json import pandas as pd import matplotlib.pyplot as plt os.chdir('/home/mathilde.lapoix/PycharmProjects/SCAPE/') import utils.import_data as load # %% Initialise def fix_lustre_name(df): return df.replace('iss01', 'iss02', regex=True) def fix_lustre_name_Exp...
9b561ec4bc9e909d40c724c7277cb56cd90a2d8d1c9cf3c7795d34ba882947e2
Python
8,765
246
''' ResNet for CIFAR-10/100 Dataset. Reference: 1. https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py 2. https://github.com/facebook/fb.resnet.torch/blob/master/models/resnet.lua 3. Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun Deep Residual Learning for Image Recognition. https://arxiv.org...
e249c4f24299d985774b029f071974385e08e1fe3621fc8619dbeca5c5b8b302
Python
8,766
188
# -*- coding: utf-8 -*- """ Created on Mon Jun 7 19:00:06 2021 @author: fhu14 """ #%% Imports, definitions from MasterConstants import Model, RawData from typing import List, Dict import numpy as np Array = np.ndarray from Spline import SplineModel, get_dftb_vals, fit_linear_model import torch Tensor = torch.Tensor i...
6353c8ff96d65cdac7b05a18913874f3747e91bc934938659f5f0bb77eaf0271
Python
8,767
198
import torch as th import torch.nn as nn from latentvelo.dataloader import Dataset from latentvelo.utils import normalize, sparse_mx_to_torch_sparse_tensor import os import numpy as np import matplotlib.pyplot as plt from latentvelo.utils import batch_func # setup adjacency matrix def set_adj(adata): import scipy ...
d733de8b29e761ee7b44eb18cc7e820f48e32cb2205bfaa74946a8a59c9762e1
Python
8,772
262
import json import os from collections import OrderedDict from itertools import repeat from pathlib import Path import numpy as np import pandas as pd import re from functools import singledispatch import scipy from scipy.ndimage.filters import gaussian_filter from types import SimpleNamespace from scipy.ndimage impo...
e57d9490664f950ac16fb5628c50a6e292ca5f0eb5d1bfa5659912a2f8477b97
Python
8,778
193
#!/usr/bin/env python3 """ svaba_cloud_serve.py -- tiny local backend for docs/svaba_cloud_launcher.html. Serves the launcher and a few JSON endpoints that shell out to your *existing* gcloud/gsutil auth, turning the static page into a live dashboard: GET / -> the launcher (token injected so it...
15ddc8b61791c1811fe4f74c093442c7b51beca96a5da2caa9c3a3540d2ba0f0
Python
8,784
221
"""Compute statistical analysis from autocorrelation metrics. """ import json import numpy as np import matplotlib.pyplot as plt import os from scipy.optimize import curve_fit import scipy.stats def analyze_autocorrelation(): # First, load relevant data AUTOCORR_RESULTFOLDER = '../results/intermediate/fig6' ...
0abc18890789762921fd2443752e3cb9017ea797366c973d38a27e4821598922
Python
8,787
295
'''Some helper functions for PyTorch, including: - get_mean_and_std: calculate the mean and std value of dataset. - msr_init: net parameter initialization. - progress_bar: progress bar mimic xlua.progress. ''' import os import sys import time import math import torch import torch.nn as nn import torch.nn.i...
9c927b1d97fb43d75d3e1250bb3f800c307b278d43614a780c274368ad4491a9
Python
8,792
207
# Copyright (c) OpenMMLab. All rights reserved. import torch.nn as nn import torch.nn.functional as F from mmcv.cnn import ConvModule, xavier_init from mmcv.runner import auto_fp16 from ..builder import NECKS @NECKS.register_module() class FPN(nn.Module): r"""Feature Pyramid Network. This is an implementati...
ecc8f9559938bd1edc2a33376c64329340d503ed3935e18555b3e814e548515f
Python
8,796
254
import math import numpy as np class Point: """Simple class for representing points in a uniform, image (row, col) manner""" def __init__(self, row, col): self.row = int(row) self.col = int(col) def __eq__(self, other): if isinstance(other, Point): return self.row == ...
57f93b017aefd35a2c6e64d758f2759d298719827f67520e35d610f36cd87829
Python
8,800
235
import torch from torch.nn.functional import multi_head_attention_forward import torch.testing as testing from selbstaufsicht.modules import AxialSelfAttention2d, MultiHeadSelfAttention2d, TiedAxialSelfAttention2d def test_MultiHeadAttention2d(): num_heads = 2 dim_head = 3 bs = 1 embed_dim = num_head...
610b9c4d8f49043a91ac555f2e24be3397797d15509e47dd94747621c7590303
Python
8,803
208
# training surv-based network with pretrained model # Created: 5/21/2021 # Status: OK # Consider merge into 1 main file # CUBLAS_WORKSPACE_CONFIG=:4096:8 python transfer_main.py # import torch.nn as nn import sys import torch import numpy as np import pandas as pd sys.path.insert(1, '../plot/') from networks import CN...
2d758468f2b78ff62018c40737dcd09ead21b2483feb306b7049cf0fcfe44c68
Python
8,805
245
# Copyright (c) OpenMMLab. All rights reserved. import mmcv import torch from mmdet.models.dense_heads import PISARetinaHead, PISASSDHead from mmdet.models.roi_heads import PISARoIHead def test_pisa_retinanet_head_loss(): """Tests pisa retinanet head loss when truth is empty and non-empty.""" s = 256 img...
3624d1ddae901ef748b3c7b2ffd8556c49d1615ac71694917ab37ea226f4efd2
Python
8,808
233
# -*- coding: utf-8 -*- """ Created on Mon Jan 24 20:31:08 2022 @author: Daniel """ import sqlite3 import os import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from scipy.stats import ttest_rel, ttest_ind import numpy as np import scipy.optimize from statsmodels.formula.api import ols from stat...
5e991a4a17ec1391ddaae79c772ed760ef1c5ef377e65b0007d1a05969dd042b
Python
8,808
338
import os import pickle import copy import json from collections import defaultdict import numpy as np import random import torch from rdkit import Chem import networkx as nx import imp import h5py from tqdm import tqdm import hashlib import torch as pt from glob import glob import pandas as pd import ase.units as unit...
795647d961f9e8970f1b46a06aa91db67130d92a2de5f2c6d3b8a3ba093423bc
Python
8,814
217
import numpy as np from nengo.exceptions import ValidationError from nengo.processes import Process from nengo.params import (EnumParam, NdarrayParam, Parameter, TupleParam, Unconfigurable) from nengo.utils.compat import is_iterable, range class ShapeParam(TupleParam): """A parameter wh...
669d6400d3779ac990218638b1117d90c50296b71e5c7531f587c97eab70c7c2
Python
8,821
271
######## # # This code generates a shorter version of figure 8A in Eyal et al 2017 # It simulates synchronous activation of synapses and the probability to spike as function of the number of activated synapses. # Two cases are shown, the case of distributed activation and the case of clustered activation # This is a sh...
0913802af81a19890d2c855ea65e4e3d6c3f03a8f1ce93c17314be29649a0587
Python
8,832
258
# -*- coding: utf-8 -*- """Residual block modules. References: - https://github.com/r9y9/wavenet_vocoder - https://github.com/jik876/hifi-gan """ import math import torch import torch.nn.functional as F from parallel_wavegan.layers.causal_conv import CausalConv1d class Conv1d(torch.nn.Conv1d): """Co...
44b65ae9eaeed4d4ef752d83109711d28f43e9a9dcd71d872288ddfc5d4155ad
Python
8,836
259
import sys sys.path.append('..') import os import torch import numpy as np import torch.nn as nn from torch.nn import functional as F import data import utils import metrics from main_bayesian import getModel as getBayesianModel from main_frequentist import getModel as getFrequentistModel import config_mixtures as cf...
c130294daf5a62cb309988b358d5f83f2bc86be28ba8ffb5e17cf4b129906183
Python
8,844
227
import logging import torch.utils.data as data import numpy as np import h5py import os from skimage.transform import resize from .data_utility import init_transform, count_samples, mr_normalization, merge_brain_mask_brats, merge_skull_brats logging.basicConfig() logger = logging.getLogger() logger.setLevel(logging....
4118cb19aaa86aaeea2cf531955771097d0fc310f2713e9c06beffb19dec50e9
Python
8,849
255
# Acquired from https://github.com/pytorch/vision/tree/master/references/detection import copy import os import torch import torch.utils.data import torchvision import torchvision.transforms as T from pycocotools import mask as coco_mask from pycocotools.coco import COCO class FilterAndRemapCocoCategories(object): ...
6b041b3e9f04855862b2a2c1093d631450a3e232799db65225d76a6c1019cdb8
Python
8,850
169
import torch from models.perception_loss import vgg16_feat, perceptual_loss from . import networks from .base_model import BaseModel class Pix2PixModel(BaseModel): """ This class implements the pix2pix model, for learning a mapping from input images to output images given paired data. The model training req...
f649dc5c2d77a30ec9f34d3bbaf516a403c95a1c1b29059168f81558d4347fd7
Python
8,850
221
import os.path import random import sys import cv2 import h5py import numpy as np import scipy.ndimage as ndimage from PIL import Image from data.base_dataset import BaseDataset, get_params, get_transform class BratsDataset(BaseDataset): """A dataset class for paired image dataset. It assumes that the dire...
60ec12b07d018830675d186f462f310eb3da831e2ec3d9d3160b319e4e6b3421
Python
8,857
154
import argparse import os import torch from exp.exp_main import Exp_Main import random import numpy as np def main(): fix_seed = 2021 random.seed(fix_seed) torch.manual_seed(fix_seed) np.random.seed(fix_seed) parser = argparse.ArgumentParser(description='Autoformer & Transformer family for Time S...
2ae5fd03aec67a2e7bbd3536159e901afc76f2c5d5f9c025624f788451e72912
Python
8,870
243
from __future__ import annotations from typing import Union import numpy as np from scipy.linalg import block_diag from .dataset import Dataset, Gammas from .generator import Generator from .options import Options from .shifter import Shifter from .skf import SKFSet from .solver import Solver from .spline import BSp...
90a37de58e8aa776092236a4e3e127c73dae360f5a6cce95116f0bf114d4ca27
Python
8,880
286
# Acquired from https://github.com/pytorch/vision/tree/master/references/detection import datetime import pathlib import pickle import time from collections import defaultdict, deque import torch import torch.distributed as dist class SmoothedValue(object): """Track a series of values and provide access to smoot...
8e049790889dec58e7716521f6e893b1829c2c94603a1f5d0862acc87012afda
Python
8,889
222
# ----------------------------------------------------------------------- # # Copyright (c) 2023, UChicago Argonne, LLC. All rights reserved. # # # # Software Name: Fast Autonomous Scanning Toolkit (FAST) # # By: Argonne Na...
e013f2e91332ac589a8aa5f90ddd503d09ba730de547ca766e7ac3d790221643
Python
8,894
271
# Copyright (c) OpenMMLab. All rights reserved. import os import warnings import numpy as np from mmcv import Config from xtcocotools.cocoeval import COCOeval from ...builder import DATASETS from .topdown_coco_dataset import TopDownCocoDataset @DATASETS.register_module() class TopDownCocoWholeBodyDataset(TopDownCoc...
db8656f1b703967dbc1855830b9c415b9812eb12fea8a0d2bb438e489ca8e8da
Python
8,904
253
## Acquired from https://github.com/pytorch/vision/tree/master/references/detection import copy import os from PIL import Image import torch import torch.utils.data import torchvision from pycocotools import mask as coco_mask from pycocotools.coco import COCO import torchvision.transforms as T class FilterAndRemap...
65826b301dc4083898ee42bbd5bdb5a7f93fa7c1197bc448294fae044603cc4b
Python
8,907
196
import logging import torch.utils.data as data import numpy as np import h5py import os from .data_utility import init_transform, count_samples, get_img_list_h5 logging.basicConfig() logger = logging.getLogger() logger.setLevel(logging.INFO) def get_transforms(): transforms_train = ["FilterLabel", "Resize", "...
262d9ba622485afe7532bd897faf3479c589d597ff0754a74aee49852372cd01
Python
8,911
262
import torch import torch.optim as optim import numpy as np import copy from ... import sync from ...cfg_holder import cfg_unique_holder as cfguh def singleton(class_): instances = {} def getinstance(*args, **kwargs): if class_ not in instances: instances[class_] = class_(*args, **kwargs) ...
1bfd05ee9b3ca4f4e1f3b4bd1022c08746eb1bf6dfe30ef26869a98df084788b
Python
8,924
213
# This file is part of sbi, a toolkit for simulation-based inference. sbi is licensed # under the Apache License Version 2.0, see <https://www.apache.org/licenses/> from typing import Tuple import torch from torch import Tensor, nn from sbi.neural_nets.estimators.base import ConditionalDensityEstimator from sbi.neur...
d3b23f5314988a89d9b8319ef1ee224a8df62844acd749bdbdb66adaefc90c28
Python
8,931
259
""" AnySleep: Attention-based U-Sleep for variable channel sleep staging. This module implements AnySleep, an extension of U-Sleep that uses attention mechanisms to combine information from multiple input channels. Unlike the standard U-Sleep which uses exactly 2 channels, AnySleep can process any number of EEG and EO...
5561f803ded3b6c154d1a766873ab7c774e50f61b8448692c6abd0a5ad3cc9f2
Python
8,936
260
""" Early fusion AnySleep variant (AnySleepEF). This module implements an attention-based sleep staging architecture where channel attention is applied BEFORE the U-Net encoder. The attention mechanism learns to weight and combine multiple input channels into a fixed number of "virtual channels" before any feature ext...
85ea82d4b565c0b87dee6fabac248a29178c69cd84dba45f0e304a33fcc3bc74
Python
8,941
226
import torch import tensorflow as tf import os os.environ['XLA_PYTHON_CLIENT_PREALLOCATE'] = 'false' tf.config.set_visible_devices([], device_type='GPU') from pprint import pprint import jax.numpy as jnp import jax.tree_util as tree import numpy as np from functools import partial import haiku as hk import optax impor...
84843d84219feb9470d21284b981cc72cbedc9b0dd6c68abe923d4d6d4ef05e7
Python
8,946
271
from typing import Tuple, Any import pytest import eagerpy as ep import numpy as np import copy import foolbox as fbn ModelAndData = Tuple[fbn.Model, ep.Tensor, ep.Tensor] def test_bounds(fmodel_and_data: ModelAndData) -> None: fmodel, x, y = fmodel_and_data min_, max_ = fmodel.bounds assert min_ < max_...
801daeb03fecf24ab86261267d371fd0baf4d7200061cf123591d1ecb9746e60
Python
8,947
202
import copy import logging import random import time import numpy as np import torch import wandb from .optrepo import OptRepo from .utils import transform_list_to_tensor class FedOptAggregator(object): def __init__(self, train_global, test_global, all_train_data_num, train_data_local_dict, te...
541a098364e93bd3c161a6e4e38c9275272580b8804dcce1514f2851dbedf634
Python
8,961
202
import torch as th import torch.nn as nn from latentvelo.anvi_dataloader import ANVIDataset from latentvelo.utils import normalize, sparse_mx_to_torch_sparse_tensor import os import numpy as np import matplotlib.pyplot as plt from latentvelo.utils import batch_func def set_adj(adata): import scipy as scp adata...
18a6f97cc49103605bdf87c7773e4add8d9f2d81d0fa7596135ffd8621f7056a
Python
8,967
236
import os import csv import shutil import hashlib import tempfile import numpy as np import pandas as pd from rdkit import Chem from rdkit.Chem import AllChem, MACCSkeys from rdkit.Chem import MolFromSmiles from padelpy import padeldescriptor # required to calculate KlekotaRothFingerPrint from metstab_shap.config imp...
3ef74a8a4a01c92557b08f6663856f0079864463bf7add82c3f84f6befc09526
Python
8,967
192
# Copyright Universitat Pompeu Fabra 2020-2023 https://www.compscience.org # Distributed under the MIT License. # (See accompanying file README.md file or copy at http://opensource.org/licenses/MIT) import glob import numpy as np import torch from torch_geometric.data import Dataset, Data __all__ = ["Custom"] clas...
026b3fc5367e3d6e4e22ae48419e3a6eab1212425988f8b7bb1835b33d064cca
Python
8,969
186
from models.med import BertConfig, BertModel, BertLMHeadModel from models.blip import create_vit, init_tokenizer, load_checkpoint import torch from torch import nn import torch.nn.functional as F from transformers import BertTokenizer import numpy as np class BLIP_VQA(nn.Module): def __init__(self, ...
7c5718a06b4060333f4f413da1ce879e1b12e9c237dcfdd80780533fda7ecfc9
Python
8,991
231
import logging import math import os import time from copy import deepcopy import torch import torch.backends.cudnn as cudnn import torch.nn as nn import torch.nn.functional as F import torchvision.models as models logger = logging.getLogger(__name__) def init_seeds(seed=0): torch.manual_seed(seed) # Speed...
a9c209c94a52f55e7181d2bdbb0149d4cafb8ee84be7dbd5fd11705e95e61dda
Python
8,997
210
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Sep 22 16:10:46 2020 @author: bariskuru """ import seaborn as sns, numpy as np import matplotlib.pyplot as plt sns.set(context='paper',style='whitegrid',palette='colorblind', font='Arial',font_scale=1.5,color_codes=True) load = np.load('rate_n_pha...
ad8b58653961028b1bb030b1cd3441623f4d1254f7b67c424a484e1df6a5d840
Python
9,002
222
import numpy as np import sklearn import sklearn.metrics as sk_metrics from sklearn.model_selection import ( BaseCrossValidator, cross_val_score, LeaveOneOut) from copy import deepcopy from . import base as pea2_base from . import validation as pea2_valid def aucScore(y_pred: np.ndarray, y_t...
6edf7712594293141bbcd2905ed0fd7927dc2dc162f34b1910472455bb9885cf
Python
9,003
255
import numpy as np from importlib import reload import sys sys.path.insert(2,'support') import functions reload(functions) import functions as f import parameters reload(parameters) import parameters as p import matplotlib import matplotlib.pyplot as plt matplotlib.rcParams.update({'font.size': p.fontsize}) plasticity...
3fe798d4b4ba63f0c0d4aed4d4d15f5927d1facf1a15100f91765b613fed523b
Python
9,004
308
import torch import numpy as np import logging logger = logging.getLogger(__name__) def minimize_bfgs(system, forces, fmax=0.5, steps=1000): from scipy.optimize import minimize if steps == 0: return if system.pos.shape[0] != 1: raise RuntimeError( "System minimization curren...
742f41b28aa236ab44e2475137702ca746b00ee07d1a88abbdbd08ada7330f0e
Python
9,010
251
''' ResNet for CIFAR-10/100 Dataset. Reference: 1. https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py 2. https://github.com/facebook/fb.resnet.torch/blob/master/models/resnet.lua 3. Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun Deep Residual Learning for Image Recognition. https://arxiv.org...
5d86b8b4f94aec4f1178be7fd38f22064d1baa444896c7e93d3efa6f1d6a25cd
Python
9,012
267
from os.path import join, exists from file_browser import get_models from config_path import PLOTS_PATH, TEST_RESULTS_PATH import pandas as pd from matplotlib import pyplot as plt import os base_dir = os.path.dirname(__file__) all_files= get_models() # number_patients= [884,592,214,103,68, 35] # number_patients= [884...
f6949dc971501d7584b006a64b33b4830472d85010db077dd2c3c217377eccd2
Python
9,012
260
# -*- coding: utf-8 -*- """ Functions for computing various metrics to aid interpretation of similarity network fusion outputs. """ import numpy as np from sklearn.cluster import spectral_clustering from sklearn.metrics import v_measure_score from sklearn.utils.validation import check_random_state from . import comput...
f35dce13b3a3a5133d9860460de6241ae4889db8520e6ecca7e12efb5f2b821d
Python
9,016
197
import argparse import logging import os import socket import sys import numpy as np import psutil import setproctitle import torch import wandb # https://nyu-cds.github.io/python-mpi/05-collectives/ from mpi4py import MPI # add the FedML root directory to the python path from torch import nn sys.path.insert(0, os.pa...
ebd537ec36bc355028013dc849bcfb22ed737b9562c408baceea5b72d4e4e0b1
Python
9,020
190
import numpy as np from torch import nn class CRNN(nn.Module): def __init__( self, configuration=None, input_channels=3, output_classes=22, convolution_layers=4, cnn_kernel_size=(3, 3), in_channels=None, max_pooling=None, batch_normalization=...
ed451d01e32e0e6d3d65cf3bfe6b097c723b212b3fb9c4ee860fbe32cb6d553e
Python
9,031
297
import spacy, utils from semquery import SemEHRES import re from os import listdir from os.path import isdir, isfile, join class StreamedDocs(object): """ effectively an abstract class for doing streaming docs """ _spacy_instance = None def get_doc_by_id(self, doc_id): pass def __ite...
c009395f870a0d4588c4231f54837253384982c3cef32a0a55876cb975a300e3
Python
9,041
222
# -*- coding: utf-8 -*- """CT dataset""" __author__ = "Sean Benson" __copyright__ = "MIT" import os from torch.utils.data import Dataset import pathlib import numpy as np from dtor.utilities.utils import cutup, pad_nd_image, expand_image,removeOutliers from dtor.utilities.utils import bbox3d, crop3d from tqdm import ...
dc089644d093d1812e5d59057c60f5fb26663b53c1d8c2749582617d4693c42f
Python
9,041
220
# -*- coding: utf-8 -*- """ Created on Fri Jun 4 16:35:35 2021 @author: fhu14 """ import json import os from InputParser import (collapse_to_master_settings, construct_final_settings_dict, parse_input_dictionaries) from .helpers import test_data_dir def test_excep...
0bc318e18a24b6ec44cfb8ad910e67cb6f53ef51bb4d7d19b1608a9ac3e284c5
Python
9,045
251
''' ResNet for CIFAR-10/100 Dataset. Reference: 1. https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py 2. https://github.com/facebook/fb.resnet.torch/blob/master/models/resnet.lua 3. Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun Deep Residual Learning for Image Recognition. https://arxiv.org...
ad76cff65e3ccc675c449d5332ed0e0310ba6fa475cc6f91cb3a3a529fa22f40
Python
9,067
240
from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Input from tensorflow.keras import Model import tensorflow as tf from tensorflow.keras.applications.xception import Xception from tensorflow.keras.preprocessing.image import ImageDataGenerator from glob import glob import pa...