sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
a7baa2a6c2033896e384b63bda43a6f39b49ddd130ab370c3309903e2c9e9977 | Python | 2,959 | 91 | '''
This is a python script for running supervised machine learning to predict compassion score
data input : foldname
data output $np.save.....
'''
import numpy as np
import pandas as pd
import scipy.stats as ss
import sklearn.linear_model as slm
from sklearn.linear_model import LinearRegression
from sklearn.model_... |
25a8a273bcbc110c61dd2d900c20757cad091eaf823c0e2eef58f21e31acd53c | Python | 2,966 | 98 | """
ReduceNoise
===========
**ReduceNoise** performs non-local means noise reduction. Instead of only
using a neighborhood of pixels around a central pixel for denoising, such
as in **GaussianFilter**, multiple neighborhoods are pooled together. The
neighborhood pool is determined by scanning the image for regions sim... |
7890d5a4d405c0373cb907513a105b0dfa53a723d9232917a3df688945a05ffc | Python | 2,971 | 81 | from unittest import TestCase
import numpy as np
from .cifar_10 import Cifar10
data = Cifar10('data/cifar_10', val_size=10000)
class Cifar10Test(TestCase):
def test_init(self):
self.assertEqual(data.train.num_examples, 50000)
self.assertEqual(data.val.num_examples, 10000)
self.assertEqu... |
dd698a06b68c04d5fd446caed69ab1387ab69bd9fc0c09ec8577642d44134ad4 | Python | 2,971 | 97 | """
SGDP Optimizer Implementation copied from https://github.com/clovaai/AdamP/blob/master/adamp/sgdp.py
Paper: `Slowing Down the Weight Norm Increase in Momentum-based Optimizers` - https://arxiv.org/abs/2006.08217
Code: https://github.com/clovaai/AdamP
References for added functionality:
Cautious Optimizers: ht... |
08185abd26a1397a6352e522ec899a54e1db32b897bc8420e64b8e16a0d427ac | Python | 2,973 | 80 | # Fundamental libraries
import os
import sys
import time
import glob
import random
import datetime
import warnings
import itertools
import numpy as np
import pandas as pd
import pickle as cp
import seaborn as sns
import multiprocessing
from scipy import stats
from pathlib import Path
from ast import literal_eval
import... |
c8a8f163bfe7136463f1270f77e404737967d1d41efd45fb283af6a9c8502690 | Python | 2,973 | 105 | from pathlib import Path
import numpy as np
class UpdatingScaler:
"""A class capable of scaling a list of boxes
and updating the average and standard deviation
with the values it's scaling
"""
def __init__(self, m, m2, count):
"""Constructor.
:param m: the current average value... |
9e306f7fb68f7314a838866ad6b94ddb263d48602fbfc28bf8fa7939f03a93e0 | Python | 2,977 | 65 | # 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... |
d74b6925d67f61bc100318f77998463554a7a1217ab2622e2c592760ee0e2340 | Python | 2,977 | 78 | # -*- coding: utf-8 -*-
# (C) Copyright 2020, 2021, 2022, 2023 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.
#
# Any... |
386f7ff98a5e297e2d30274540242fb8ca4127caee05844f2209f2441c4c75cf | Python | 2,979 | 94 | #!/usr/bin/python3
import matplotlib.pyplot as plt
import numpy as np
import sys
import scipy.signal as signal
import getopt
import os
import researchdata1258
VEPstartTime = 0.35 # sec
VEPendTime = 0.45 # sec
SlidingWindowSize = 2 # sec
class NoiseWall:
class NoiseWallException(Exception):
pass
d... |
e3fd69ca19ae33b72843ff8aecf80de38e111ef9e3981f18c305a6c8033c73b4 | Python | 2,979 | 76 | import torch.nn as nn
import torch.nn.functional as F
class IncDownsamplingModule(nn.Module):
def __init__(
self,
input_channels,
output_channels,
Conv,
Dropout,
InstanceNorm,
leakiness=1e-2,
kernel_size=1,
conv_bias=True,
inst_norm_a... |
cbc6a1d14222353a47fe961d6f562c6ad461a34dfd2766b8eeecbd1b25064ce3 | Python | 2,980 | 63 | """Tests for queryai resolution of direct NIDM/BIDS predicates.
Facts like the functional task (``nidm:Task``), session (``bids:session_number``),
run (``nidm:AcquisitionObject``) and filename (``nfo:filename``) are stored as
predicates on the acquisition object, not as ``nidm:DataElement`` nodes, so the
DataElement r... |
732d208568969b6d9e46edefa2b04a40cc01a23a966cc918889936e85fcd30fd | Python | 2,983 | 72 | import torch
import matplotlib.pyplot as plt
import mne
import numpy as np
from codetiming import Timer
from somata import OscillatorModel as Osc
from somata.source_loc import SourceLocModel as Src
from somata.source_loc.source_loc_utils import simulate_oscillation
"""
################################################... |
d5d21960e30b68e5c226696404d69b6ce8bdc619ed2412d8e220f55ee4a7ed09 | Python | 2,985 | 74 | # coding=utf-8
# Copyright 2020 The SimCLR 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 applicable law or... |
208467b81176f5abd1aa8cda16e3cdf4089b95c4637d15836d10699ee796d75a | Python | 2,986 | 76 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 5 15:57:59 2018
@author: saskiad
"""
import numpy as np
import pandas as pd
import os, h5py
import core
manifest_path = core.get_manifest_path()
save_path_head = core.get_save_path()
save_path = os.path.join(save_path_head, 'DriftingGratings')
... |
39693dd9aa79c7efbe60b27860cf9479c876acff0ed30ff7f05a7fa22b1b0820 | Python | 2,986 | 70 | # adapted from https://github.com/fepegar/torchio/blob/main/src/torchio/transforms/augmentation/intensity/random_noise.py
from collections import defaultdict
from typing import Tuple, Union
import torch
from torchio.data.subject import Subject
from torchio.transforms import IntensityTransform
from torchio.transforms.... |
a63c149fdb8ad5a0aaa798124a6bcca36d30ecdcc62c6d13c96f427488c85e67 | Python | 2,988 | 100 | from attr import dataclass
from torch import nn
import torch
from tqdm import tqdm
import pdb
from DT_for_WDN_leak_localization.trainers.base import BaseTrainStepper
from DT_for_WDN_leak_localization.trainers.logging import AEMetricLogger
@dataclass
class EarlyStopping:
num_non_improving_epochs: int = 0
best_... |
b225b6b0f452a2f34bf1fe111d622a8d7e7c82e5f09406e481ee4493418e3a73 | Python | 2,988 | 76 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 5 15:57:59 2018
@author: saskiad
"""
import numpy as np
import pandas as pd
import os, h5py
import core
manifest_path = core.get_manifest_path()
save_path_head = core.get_save_path()
save_path = os.path.join(save_path_head, 'StaticGratings')
m... |
d8496ddfd38445ce27162f48474d22e6baf28d38ed40242b74dd416099e6246c | Python | 2,991 | 81 | from glob import glob
import os
from pdb2sql import pdb2sql
import numpy
import h5py
from deeprank.config import logger
from deeprank.features.FeatureClass import FeatureClass
from deeprank.config.chemicals import AA_codes, AA_codes_3to1, AA_codes_1to3
from deeprank.operate.pdb import get_residue_contact_atom_pairs, ... |
feadd3529d8b8c80f580f5d886aaae18b6ed3d8530ff1f8bddbf5b8242fef9df | Python | 2,994 | 82 | """
ShrinkToObjectCenters
======================
**ShrinkToObjectCenters** will transform a set of objects into a label image with single points
representing each object. The location of each point corresponds to the centroid of the input objects.
Note that if the object is not sufficiently *round*, the resulting sin... |
51309e1c8a8dfffba764d52faef319073fc51334ee19dc195b86d0daf3f6e2ed | Python | 2,997 | 60 | from tensorflow.keras.layers import Conv2D, UpSampling2D, LeakyReLU, Concatenate
from tensorflow.keras import Model
from tensorflow.keras.applications import DenseNet169
class UpscaleBlock(Model):
def __init__(self, filters, name):
super(UpscaleBlock, self).__init__()
self.up = UpSampling2D(s... |
112fbb4e74ade9903841b5ed2f54724cd140c1e53c41428879f8e2186ae60a0b | Python | 2,998 | 75 | import numpy as np
import sys
import os
import os.path as osp
sys.path.append('..')
from functions.individual_variability import difference_plots_sameHemi
from functions.individual_variability import difference_plots
from functions.individual_variability import difference_score
# All individuals
with open('./../list... |
44904a207ad579fc289787e8d40e20bde669292828c6c94fa794731b629f3fef | Python | 2,998 | 70 | ''' adapted from https://github.com/all-umass/ManifoldWarping '''
''' Warping aligners '''
import numpy as np
from distance import SquaredL2
from dtw import dtw
from embedding import isomap
from correspondence import Correspondence
from alignment import TrivialAlignment,CCA,ManifoldLinear,manifold_nonlinear
def ctw(... |
efff32d50a3b0ef5c1d1edc81c6c295de0abed15e5357ad6a3b05bfbfe5b6662 | Python | 3,007 | 80 | import nibabel as nib
import os
from os.path import join as pjoin
from nibabel import Nifti1Header
from nibabel import Nifti1Image
import numpy as np
import subprocess
from tqdm import tqdm
# save nifti
def save_ciftifile(data, filename, template='./supportfiles/template.dtseries.nii'):
ex_cii = nib.load(template)... |
1520d7197eba54fd18aaca20cc5f8591890ac2aec72ea830c9e8974365c24fbb | Python | 3,012 | 72 | # -*- coding: utf-8 -*-
"""
molvs.metal
~~~~~~~~~~~
This module contains tools for disconnecting metal atoms that are defined as covalently bonded to non-metals.
"""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
import logging
from rdkit import Chem
... |
530737ef3906b3fe75dd4f9039845535cd5550e5baaddd5a198b1a5e6a173dac | Python | 3,013 | 78 | from typing import Optional
import torch
from GANDLF.grad_clipping.clip_gradients import dispatch_clip_grad_
class GradScaler:
def __init__(self):
"""Initializes a GradScaler object with a PyTorch GradScaler."""
self._scaler = torch.cuda.amp.GradScaler()
def __call__(
self,
lo... |
c61ae269c866103a08d5054506d644d92c929054e200c4fec80a563acaab7ef3 | Python | 3,013 | 87 | # -*- coding: utf-8 -*-
import os
import pytest
import pysteps
from pysteps.tests.helpers import smart_assert
netCDF4 = pytest.importorskip("netCDF4")
# Test import_bom_rf3 function
expected_proj1 = (
"+proj=aea +lon_0=144.752 +lat_0=-37.852 " "+lat_1=-18.000 +lat_2=-36.000"
)
test_metadata_bom = [
("tra... |
08b2ebfed2d2bb292a66119629e2a7cb89bfd7bf39a34e9be0ac536b3880a275 | Python | 3,015 | 88 |
import numpy as np
import tensorflow as tf
from tensorflow import math as tfm
from tensorflow.keras import backend as K
CEL_logits = tf.nn.softmax_cross_entropy_with_logits
mse = tf.keras.losses.MeanSquaredError()
AAs = np.array(['A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V... |
6f7df668a73594e4ce07e2d37702e461263688d374aa6abbf3dd1b42cb41a5a9 | Python | 3,019 | 90 | #!/usr/bin/python3
import matplotlib.pyplot as plt
import numpy as np
import sys
import scipy.signal as signal
import getopt
import os
import researchdata1258
VEPstartTime = 0.35 # sec
VEPendTime = 0.45 # sec
desyncPowerReductionPercent = 40 # percent
class SNR:
def __init__(self,subj,task,startsec=False,minF=Fa... |
34f64649f70063ee57d8891b96db7b968e90a3d6569db7d438ed2312f8e041b1 | Python | 3,022 | 72 | import numpy as np
import torch
import torch.nn as nn
from models.aggregators import BaseAggregator
from models.aggregators.model_utils import PPEG, NystromTransformerLayer
class TransMIL(BaseAggregator):
def __init__(self, num_classes, input_dim=1024, pos_enc='PPEG', **kwargs):
super(BaseAggregator, sel... |
1c1bfc1e7252e8ea24d7c80a833c0d030bb646b173b99a30ac1288168405ca43 | Python | 3,023 | 108 | import torchvision
from torchvision import transforms
from .wrapper import CacheClassLabel
def MNIST(dataroot, train_aug=False):
# Add padding to make 32x32
#normalize = transforms.Normalize(mean=(0.1307,), std=(0.3081,)) # for 28x28
normalize = transforms.Normalize(mean=(0.1000,), std=(0.2752,)) # for 3... |
ceaf78a8e5aa864a93cd9709ec886e3265228b127c1040a6f204325a2906b3d5 | Python | 3,023 | 79 | # 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... |
dbd5cfe10d85d21eaf9bc96be6291eff12bdcf9ccd6c8e53ebb678262cb53010 | Python | 3,024 | 94 | """ Filter Response Norm in PyTorch
Based on `Filter Response Normalization Layer` - https://arxiv.org/abs/1911.09737
Hacked together by / Copyright 2021 Ross Wightman
"""
from typing import Optional, Type
import torch
import torch.nn as nn
from .create_act import create_act_layer
from .trace_utils import _assert
... |
a43574101020c641191ee85921d5f72cda900d93f17d7a49d0848d3aed08d0b8 | Python | 3,028 | 70 | from __future__ import annotations
from dataclasses import dataclass
from typing import Optional
import pytest
from nidm.experiment.tools.rest import RestParser
from nidm.util import urlretrieve
# We will test example NIDM files downloaded from
# the GitHub dbkeator/simple2_NIDM_examples repo
#
# DBK: this is a bit un... |
829053987061419344ed83cefd5ec2f12024bf1801dcc0b4f936d85b1b701ee3 | Python | 3,031 | 107 | from typing import Optional, Tuple, Union
import torch
import torch.nn as nn
def patch_dropout_forward(
x: torch.Tensor,
prob: float,
num_prefix_tokens: int,
ordered: bool,
training: bool,
) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
"""
Common forward logic for p... |
2429ac6d72bd0d114929d60d9e6321463fb48f83b2526f214930f2d1bf82ff36 | Python | 3,032 | 86 | from unittest import TestCase
import numpy as np
from .vessel12 import VESSEL12
data = VESSEL12()
class VESSELTest(TestCase):
def test_init(self):
self.assertEqual(1060, data.train.num_examples)
self.assertEqual(265, data.val.num_examples)
self.assertEqual(265, data.test.num_examples)
... |
934102ec37d836f4416294b4e850f3b90ae269c763dfeb7746c725ddf531e295 | Python | 3,032 | 66 | import numpy
from typing import Annotated, Union, Tuple
from pydantic import validate_call, ConfigDict, Field
from cellprofiler_library.functions.object_processing import outline
from cellprofiler_library.types import ObjectSegmentation
@validate_call(config=ConfigDict(arbitrary_types_allowed=True))
def identifytertia... |
fbd77ed34fe813996932e7f8f309ae39c07f12cb7eb80b9f80c089dea7e78a2b | Python | 3,034 | 79 | #!/usr/bin/env python
# Display a runtext with double-buffering.
from samplebase import SampleBase
from argparse import ArgumentTypeError
from rgbmatrix import graphics
import time
DEFAULT_FONT = "../../../fonts/7x13.bdf"
def color(value):
try:
return graphics.Color(*[int(v) for v in value.split(",")])
... |
563021fc0a2b835db55dce007f025b657b3c28175e9922578023d7515f8cad98 | Python | 3,035 | 67 | """This package contains modules related to objective functions, optimizations, and network architectures.
To add a custom model class called 'dummy', you need to add a file called 'dummy_model.py' and define a subclass DummyModel inherited from BaseModel.
You need to implement the following five functions:
-- <__... |
9d135ae655e057750c4af66e7ec18d69ddaecd07fcb0d29910185f7fa3b046f0 | Python | 3,042 | 99 | #!/usr/bin/env python3
from itertools import product
import numpy as np
import pandas as pd
import etspredict.selective_connectomes as sc
def test_ets_amplitudes():
ets = np.arange(9).reshape(3, 3)
ampl = sc.ets_amplitudes(ets)
assert len(ampl) == 3
def test_reorder_timeseries():
# test custom cr... |
4fb568e1667da9dff5f7f4f6dcfa211d7123490cd49906dbaf80dec38ba0d271 | Python | 3,043 | 117 | # -*- coding: utf-8 -*-
import numpy as np
import pytest
from pysteps import motion, nowcasts, verification
from pysteps.tests.helpers import get_precipitation_fields
sseps_arg_names = (
"n_ens_members",
"n_cascade_levels",
"ar_order",
"mask_method",
"probmatching_method",
"win_size",
"ti... |
d1a6006efd1fd8f9f4af6c24150b4e45abb0286aee53f583f4fe6d2103bcbe71 | Python | 3,043 | 84 | import shutil
from unittest import TestCase
from numpy.testing import assert_equal
from .dataset import PreprocessedDataset
from ..datasets.mnist import MNIST
from ..segmentation.algorithm import slic_fixed
from ..segmentation.feature_extraction import extract_features_fixed
from ..pipeline import preprocess_pipeline... |
b7743d10ad99a2d27b6df9a5acf606c3df367b0d94669c8a7d87bd52300f0cdc | Python | 3,044 | 117 | """
Created in 2022
@author: Nikolai M Chapochnikov
This file generates the files that are in results/dataset4
"""
# %%
import numpy as np
import pandas as pd
import matplotlib.pylab as plt
import importlib
import functions.nmf as nmf
import functions.white_circ_offline as FOC ### !!! different FOC !!!
import fu... |
58898f650ce9f9e04531a33b519ae63eff2e8cdae5c1dd17dd7a1293ce8f7a4b | Python | 3,056 | 102 | import os
from ._does_not_predicate import DoesNotPredicate
from ._does_predicate import DoesPredicate
from ._filter_predicate import FilterPredicate
from .._file_collection_display import FileCollectionDisplay
from ...utilities.image import is_image_extension
IS_TIF_PREDICATE = FilterPredicate(
"istif",
'"ti... |
a2f4ac061dd9d869b5738f91770349a4e741c9db58d8bc1bb497ff5898f7c8a0 | Python | 3,056 | 82 | # -*- coding: utf-8 -*-
# (C) Copyright 2020, 2021, 2022, 2023 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.
#
# Any... |
b4c0730894b62c0ff8b966a8f9713222b15422b5b0e1aea89554c9b23d593783 | Python | 3,056 | 88 | from ._objects import Objects
class ObjectSet:
"""A set of objects.Objects instances.
This class allows you to either refer to an object by name or
iterate over all available objects.
"""
def __init__(self, can_overwrite=False):
"""Initialize the object set
can_overwrite - True ... |
ada67a673abb78150697cfae92c93d9b7adb0355b6391b7142891faaf54d6301 | Python | 3,061 | 112 | # Inheritaed from open-mmlab/mmclassification
# Modified by Hangyu LIN
from time import time
class TimerError(Exception):
def __init__(self, message):
self.message = message
super().__init__(message)
class Timer:
"""A flexible Timer class.
Examples:
>>> import time
>>> i... |
8b7f7ed47a93234d08638809054541cbcc640a07e2d9ac964d38fb8ad40695f5 | Python | 3,066 | 72 | # -*- coding: utf-8 -*-
"""
pysteps.blending.interface
==========================
Interface for the blending module. It returns a callable function for computing
blended nowcasts with NWP models.
.. autosummary::
:toctree: ../generated/
get_method
"""
from functools import partial
from pysteps.blending impo... |
82cc374f9e271b0c10c7058aa19c41a89109b8c72e68368bb5fc9b44bd947bd2 | Python | 3,067 | 105 | #! /usr/bin/python
#-*-coding: utf-8 -*-
from scipy.signal import argrelextrema
import argparse
from pyBTK import btk
import os
from keras.models import model_from_json
from scipy import signal
from numpy import matlib as mb
import numpy as np
from .utils import *
def predict(load_model,acq,markers,pfn... |
4b6875488da01c96ca758b5f73c7d006c07574c21f2e660b44871bbacee9dc61 | Python | 3,069 | 73 | from pydantic import BaseModel, Field, AfterValidator
from typing import Dict
from typing_extensions import Literal, Optional, Annotated
from GANDLF.configuration.validators import validate_postprocessing
GRID_AGGREGATOR_OVERLAP_OPTIONS = Literal["crop", "average", "hann"]
class DefaultParameters(BaseModel):
we... |
8cee2a46a5e0f34cfdb6d317cf7f8870a5a38d6f392fe059f47cf3711158d724 | Python | 3,069 | 91 | import torch
from typing import List, Optional
from torchio.transforms.intensity_transform import IntensityTransform
from torchio.data.subject import Subject
from torchio.data.image import ScalarImage
class NormalizeRGB(IntensityTransform):
"""Threshold the intensities of the RGB images in the subject into a ran... |
499dc6367643304a0c0616247a63b2fe3b263e7821c9b15e84f957c4360cc502 | Python | 3,070 | 77 | # -*- coding: utf-8 -*-
#
# Evaluation of model performance."""
# pylint: disable= no-member, arguments-differ, invalid-name
import numpy as np
from src.utils.protein_utils import rigid_transform_Kabsch_3D
__all__ = ['Meter_Unbound_Bound']
class Meter_Unbound_Bound(object):
def __init__(self):
self.complex_rm... |
b47b965ebefac78b1100c510e1d195273c8717f9f52e2c0a1d38c0c21f2214c8 | Python | 3,072 | 100 | """
Author: "Keitaro Yamashita, Garib N. Murshudov"
MRC Laboratory of Molecular Biology
This software is released under the
Mozilla Public License, version 2.0; see LICENSE.
"""
from __future__ import absolute_import, division, print_function, generators
from servalcat.utils import logger
import numpy
def cgsolve... |
66ec91267c565b15409d6bbf799c4b3b06b54d240faf42b9a6bfd6008ca9f9c3 | Python | 3,074 | 80 | from unittest import TestCase
import numpy as np
2
from .m2nist import M2NIST
data = M2NIST('data/M2NIST')
class M2NISTTest(TestCase):
def test_init(self):
self.assertEqual(data.train.num_examples, 4000)
self.assertEqual(data.val.num_examples, 1000)
self.assertEqual(data.test.num_examples... |
c8ae7f502500a6b4c8fd6aaae23b2c4a65c8a5d69081b11816e221bb9ca23339 | Python | 3,076 | 84 | """Resolve strong registry selectors across Python configuration scopes."""
from __future__ import annotations
import json
import stat
from collections.abc import Mapping
from pathlib import Path
from typing import cast
from datamonger._errors import RegistryError
from datamonger._models import Pathish, Registry
fro... |
1a37709af3edbc808cba56d8fcf49e39d213457bd2ae4e2fa3391a1026ffeb4e | Python | 3,079 | 109 | import numpy as np
from pytorch_wavelets import DWT1DForward, DWT1DInverse
import torch
import pywt
import time
from torch.utils.data import DataLoader
import os
def wt_packet(inp, wavelet='db2', mode='symmetric', maxlevel=1):
"""
the last-dim vector to be decomposed
:param inp: shape: batch * n_attr * n... |
6fe88d4f4f170ecbdd046ce55786d39b457135337bf0ac7355044a93b5159769 | Python | 3,079 | 71 | import numpy as np
from ..kernels import KernelRect
from .glm import GLM
from .srm import SRM
from ..signals import shift_mask
from ..utils.time import get_dt
class LSSRM(SRM):
def __init__(self, vr=None, kappa=None, eta=None, vt=None, dv=None, gamma=None):
super().__init__(vr=vr, kappa=kappa, eta=eta, ... |
50581fadd750a9e8a939da4a934328fb0c09f93613112359c97cc4c9079a2dd2 | Python | 3,082 | 71 | import os
from typing import Tuple
import pandas as pd
def handle_collisions(
df: pd.DataFrame, headers: dict, output_path: str
) -> Tuple[bool, pd.DataFrame]:
"""
This function checks for collisions in the subject IDs and updates the subject IDs in the dataframe to avoid collisions.
This function t... |
46c7c5b7d251c1e7b4f8bc98e36235592a832cd4f5903e8f0278855993f5dadf | Python | 3,083 | 62 | from pathlib import Path
import torch
from DSEC.dataset.sequence import Sequence
class DatasetProvider:
def __init__(self, dataset_path: Path, mode: str = 'train', event_representation: str = 'voxel_grid',
nr_events_data: int = 5, delta_t_per_data: int = 20,
nr_events_window=-1... |
a8b65cda48dfe161d0b8d31bbcd31d4e50a9a5a44a9bf69d3f51225756e4801b | Python | 3,087 | 74 | """ Lookahead Optimizer Wrapper.
Implementation modified from: https://github.com/alphadl/lookahead.pytorch
Paper: `Lookahead Optimizer: k steps forward, 1 step back` - https://arxiv.org/abs/1907.08610
Hacked together by / Copyright 2020 Ross Wightman
"""
from collections import OrderedDict
from typing import Callable... |
b74dbb6060d8a1fdadfba2e805c33c2a718df036d2c3e692e28f7cb729e03fb4 | Python | 3,087 | 102 | from attr import dataclass
from torch import nn
import torch
from tqdm import tqdm
import pdb
from DT_for_WDN_leak_localization.trainers.base import BaseTrainStepper
from DT_for_WDN_leak_localization.trainers.logging import GANMetricLogger
@dataclass
class EarlyStopping:
num_non_improving_epochs: int = 0
best... |
4d5ff180731c8f5aca91c2b8040322517040a94ab0b2a90968b7101b2aa33e3c | Python | 3,090 | 84 | """Tests for ParamsReader — the EEG parameter-file reader.
ParamsReader supports three on-disk formats, all of which feed
samplerate + gain + data format into the binary EEG readers:
* ``params.txt`` — whitespace-delimited ``key value`` lines (legacy).
* ``sources.json`` — the modern per-dataroot JSON sidecar.
* ``<d... |
550a15f5dd3b47eae90e32416afec00d7635d481b594b4c41e68e3d30f5a5ac7 | Python | 3,093 | 89 | """ Position Embedding Utilities
Hacked together by / Copyright 2022 Ross Wightman
"""
import logging
import math
from typing import List, Tuple, Optional, Union
import torch
import torch.nn.functional as F
from ._fx import register_notrace_function
from .helpers import is_exporting
_logger = logging.getLogger(__na... |
4adadd99b0221023e9b0dd40a19a3be4c735cbe50098a17235f16626b9c73a0e | Python | 3,095 | 106 | #!usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import logging
from typing import Optional
from deprecated import deprecated
import click
from GANDLF.cli.patch_extraction import patch_extraction
from GANDLF.cli import copyrightMessage
from GANDLF.entrypoints import append_copyright_to_help
from GANDLF.ut... |
fa1f705b6b8708586c0e502bf2f9be08a6e686dcd777ecb19e90d472dc23fb01 | Python | 3,095 | 80 | import numpy
import scipy.ndimage
from cellprofiler_core.constants.measurement import (
M_LOCATION_CENTER_X,
M_LOCATION_CENTER_Y,
M_NUMBER_OBJECT_NUMBER,
FF_COUNT,
COLTYPE_FLOAT,
COLTYPE_INTEGER,
IMAGE,
)
from cellprofiler_library.measurements.wrappers import wrap_object_location_measuremen... |
761aa7a1ddd80133bee5f6444791cc745a701ad4588b4fa600222fa2772786ad | Python | 3,097 | 69 | """
@author: Johanna Rahm
Research group Heilemann
Institute for Physical and Theoretical Chemistry, Goethe University Frankfurt a.M.
VisualizeDeepSTORM2DLocs functionalities.
"""
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
def xy_loc_vis(frame_locs, pixel_size):
x = frame_locs["x ... |
e4621c1a2fda5af60dbdb97d957b623079bacf0ac896c76b4e9b1b2ca77ee444 | Python | 3,098 | 115 | import os
from itertools import product
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
##############################################################################
#
##############################################################################
cm = 1 / 2.54
figsize = (18 * cm, 18 * cm)
... |
4855d97df31fb588634ac0cebd9fde7f4dced9aee9007c635c670c31cd97981e | Python | 3,100 | 102 | """ Conv2d + BN + Act
Hacked together by / Copyright 2020 Ross Wightman
"""
from typing import Any, Dict, Optional, Type
from torch import nn as nn
from .typing import LayerType, PadType
from .blur_pool import create_aa
from .create_conv2d import create_conv2d
from .create_norm_act import get_norm_act_layer
class ... |
818870210d18ac0ef0ee84258f47215fc809169fa19ed13127bcf48f23ad423f | Python | 3,104 | 123 | import glob
import os
from pathlib import Path
import platform
import shutil
import sys
import webbrowser
from invoke import task
@task
def clean_build(c):
"""Clean the build directory."""
print("Cleaning build")
try:
shutil.rmtree("build")
os.mkdir("build")
except OSError:
pa... |
1b351b366154c39be1fb2ee052b4ef28ea78b80fa9fceb061f8bf054b49e31b4 | Python | 3,106 | 102 | import os
import warnings
import numpy as np
from pdb2sql import StructureSimilarity
def __compute_target__(decoy, targrp, tarname, save_file=False):
"""Calcuate CAPRI metric IRMSD, LRMSD or FNAT.
Args:
decoy(bytes): pdb data of the decoy
targrp(hdf5 file handle): HDF5 'targets' group
... |
dbb16f15d7fa8dfcaba7aa2da60b98cbebb60ae386a1e1e9193d36cbb2393160 | Python | 3,106 | 91 | import os
import pickle
import numpy as np
import torch
from torch.utils.data import Dataset
from tqdm import tqdm
class Alphabet(Dataset):
def __init__(self, train_or_test, transform=None, target_transform=None):
super(Alphabet, self).__init__()
roots = '../../Dataset/alphabet'
... |
e2e70c7c3abd56f75d1a52992c8cce62783f62c785ff8849c2b9e0dc412d1c53 | Python | 3,106 | 68 | import sys
from keras import applications
from keras.models import Model, load_model
from keras.layers import Input, InputLayer, Conv2D, Activation, LeakyReLU, Concatenate
from layers import BilinearUpSampling2D
from loss import depth_loss_function
def create_model(existing='', is_twohundred=False, is_halffeatures=Tr... |
62f5cc1177f685355e3ddceb70d813fdf3a94c89d1e2007786aad7f30ae77814 | Python | 3,112 | 88 | import pandas as pd
import splitter as sp
import modules.pair_generation_top as pg
import os
from sklearn.model_selection import KFold
import numpy as np
def make_dir(path):
if not os.path.exists(path):
os.makedirs(path)
def make_dir_file(file_name, random = False):
if random:
ouput_path = ... |
e0e3fc538b52447b67359df8ff7ac286c5009c1947143faddfa42489b2a83875 | Python | 3,116 | 89 | import os
import time
import urllib
from multiprocessing import Pool, Manager
import pandas as pd
import wget
from download_config import Config
config = Config()
def ftp_download(args):
# 将需要的下载的url复制下来,左边的URL为变量,可根据实际情况填写其他的
name = args[0]
fna_file_url = args[1]
output_file_name ... |
669dae99fc88001eb5dc67b6de3162b8bad6bb626e5605283acaec1bd6a9a221 | Python | 3,117 | 69 | ## TODO AUG 06 version
"""This package contains modules related to objective functions, optimizations, and network architectures.
To add a custom model class called 'dummy', you need to add a file called 'dummy_model.py' and define a subclass DummyModel inherited from BaseModel.
You need to implement the following fi... |
fa1ba3da3e221fb0bf6aa795dc77624f1af593d67c95abe34da4795f8a5db204 | Python | 3,122 | 82 | from __future__ import division
from unittest import TestCase
import numpy as np
from numpy import pi as PI
from numpy.testing import assert_equal
import scipy.sparse as sp
from .adjacency import (zero_one_scale_adj, invert_adj, points_to_l2_adj,
points_to_adj)
class GraphTest(TestCase):
... |
a9d6abcdfa2252bb9f535a3116ae184280aaf61cd17df99549cada7f032d72f5 | Python | 3,126 | 94 | # -*- coding: utf-8 -*-
"""
Script to test the plugin support.
https://github.com/pySTEPS/cookiecutter-pysteps-plugin
"""
import os
import pytest
import subprocess
import sys
import tempfile
__ = pytest.importorskip("cookiecutter")
from cookiecutter.main import cookiecutter
PLUGIN_TEMPLATE_URL = "https://github.com... |
76ed7b1d10c26f7c2fad94fc423efe8aabd0e34ad3ca2d17ad345e0232b427fa | Python | 3,127 | 103 | import networkx as nx
from dataclasses import dataclass, field
import pdb
import pandas as pd
from typing import Optional
def get_label_to_index_dict(labels):
"""Returns a dictionary mapping labels to indices."""
index = [labels.index(node) for node in labels]
label_to_index_dict = dict(zip(labels, index)... |
fb73c41bde44ed2f1d7d56a865f1f31642243f1d33a354c54002d68fe6d7c3d6 | Python | 3,129 | 104 | #
# nate berry
# 2023-04-01
#
#
# ---------------------------
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import solve_ivp
from pyrqa.time_series import TimeSeries
from pyrqa.analysis_type import Cross
from pyrqa.settings import Settings
from pyrqa.computation import RQAComputation
from py... |
8d68f349b78a24c63f5b7cfef180867a7279541fae38b2392cfdbd660522ac83 | Python | 3,138 | 99 | elements = {"Ag": 106.905095,
"Al": 26.981541,
"Ar": 39.962383,
"As": 74.921596,
"Au": 196.96656,
"B": 11.009305,
"Ba": 137.905236,
"Be": 9.012183,
"Bi": 208.980388,
"Br": 78.918336,
"C": 12,
... |
086785783c9675682347fc41cd60b20ee9844770bee088987e291dc6fc0a6deb | Python | 3,139 | 97 | #!/usr/bin/env python
import pandas as pd
from scipy.stats import norm, pearsonr
import math
import numpy as np
import matplotlib.pyplot as plt
plt.switch_backend("agg")
def pearson_confidence(r, num, interval=0.95):
"""
Calculate upper and lower 95% CI for a Pearson r (not R**2)
Inspired by https://stat... |
d81897bd45b75f5a9ae5d9fb56e79b2b54c57bd176eb03befe13800237e01bc6 | Python | 3,144 | 56 | """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 ... |
51cc9b4e6ea85e909fcc20f0700a897474c65fa9d1207b654d8f67aaceb6fd55 | Python | 3,153 | 113 | from functools import partial
from typing import List
import torch
from torchio.transforms import Lambda
def axis_check(axis: List[int]) -> List[int]:
"""
This function checks the axis for rotation.
Args:
axis (List[int]): The axes of rotation.
Returns:
List[int]: The affected axes.... |
b017dfe417f79f44c71f6ce8f4ce6d20babde655e29ff1f9b933a045525f62a0 | Python | 3,155 | 95 | from os import path
import numpy as np
import SimpleITK as sitk
from helpers import *
#############################
## General ##
#############################
PROJECT_NAME = "stroke_cta"
IMAGE_DIR = "/data/path_to_images/stroke-auto/data/"
PROJECT_DIR = f"/scratch/path_to_project_root/{P... |
d34de5f109e02749eb77ffcc59f9ade7ae8b5ed21fb015364254ef37e6a9f457 | Python | 3,156 | 97 | #!/usr/bin/env python3
# Copyright 2021 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
#
# Unless required by applicable law o... |
7869e9522c857a02824302a613564e239070ca3888858987253daee2e8ae8ab4 | Python | 3,158 | 69 | from PyQt5.QtCore import QObject, pyqtSignal
from dragen.run import Run
class Worker(QObject):
finished = pyqtSignal()
progress = pyqtSignal(int)
info_box = pyqtSignal(str)
def __init__(self, ARGS):
super().__init__()
self.root = ARGS['root']
self.box_size = ARGS['box_size']... |
ddd0b679d5aba3958f14ae64b031db13bfe5b0248a6d8e23c2f09b769f4645d8 | Python | 3,161 | 79 | """Execute the synthetic example notebook end-to-end as a test.
``docs/examples/getting_started.ipynb`` uses only ``numpy`` + ``matplotlib``
+ ``ptsa`` (synthetic signals, no rhino data), so it can run anywhere the
notebook toolchain is installed. Running it here guards against the
notebook's code drifting away from P... |
6166705892baeef835dc4bfbf205745f66efc2139b7d478b8913739884f68186 | Python | 3,170 | 70 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 30 14:46:14 2017
@author: Nikolai M Chapochnikov
"""
file_tbl = 'data/Si_2019/ORN_data_table.csv'
file_hdf = 'results/act2.hdf'
n_cells = 21
n_conc = 5
n_odors_EC = 34
# this is the order based on the 2nd loading vector of the PCA of ORN activ... |
1bbb8d3dd6eee585115de8e949b53c821314b1c152cff64adfff6769dff66333 | Python | 3,176 | 98 | ''' adapted from https://github.com/all-umass/ManifoldWarping '''
''' Example of the alignment methods in this directory:
# get your two data sets somehow
X,Y = gen_data(1000)
# make correspondences and/or neighbor graphs
corr = Correspondence(matrix=numpy.eye(1000))
Wx = neighbor_graph(X,k=5)
Wy = neigh... |
7784aac0771bc75a0c9b4f43e5ec96d830ae50d010b5965410315671d97678e5 | Python | 3,180 | 100 | import numpy as np
import SimpleITK as sitk
from scipy.ndimage import zoom
def get_affine(image):
# Coppied from TorchIO:
# https://github.com/fepegar/torchio/blob/164a1bf3699863ef3a74f2a7694f6f4cf0fff361/torchio/data/io.py#L271
spacing = np.array(image.GetSpacing())
direction = np.array(image.GetDi... |
a17d99bb1e7b69a0332f9303accd97db5e05e1f3b0a3eda5023d99a2648afc0c | Python | 3,181 | 93 | #!/usr/bin/env python
# coding: utf-8
# In[44]:
#Developed 07/13/2020 by Jeffrey Hu with assistance from Professor Jianjun Hu
#Sorts materials cif files by element number and space group
from pymatgen.io.cif import CifParser
from shutil import copyfile
from pymatgen.core.composition import Composition
import glob
im... |
29fbcc30154761ecaf3cb087616cbf846b6cad6f653b3fcc5d87548d79b1a4ef | Python | 3,182 | 88 | import logging
from datetime import datetime
import pandas as pd
import requests
_LOGGER = logging.getLogger(__name__)
def fetch_json_options_number(raw_url):
"""
Function to retrieve how many options a specific reproschema item contains.
Args:
raw_url: The github raw url to the given reprosche... |
7f5cb108a877d9b91f8f8c69b43612d24ba80cfc682c4a8047ddd97190964a36 | Python | 3,187 | 96 | import torch.nn as nn
class EncodingModule(nn.Module):
def __init__(
self,
input_channels,
output_channels,
conv=nn.Conv2d,
conv_kwargs=None,
norm=nn.BatchNorm2d,
norm_kwargs=None,
act=nn.LeakyReLU,
act_kwargs=None,
dropout=nn.Dropout... |
6ae9ec24f150408e6734896fc541c53d130c6d34ba27e2b361fcc900ad6c8ffb | Python | 3,189 | 89 | import os
import torch
import torch.nn as nn
from tqdm import tqdm
from torch.utils.data import DataLoader
from sklearn.metrics import classification_report
from transformers import BertTokenizer
from transformers import BertConfig
from transformers import BertPreTrainedModel
from transformers import BertForSequenceCla... |
f4a931536f704ef619454e969019880a468c6b088ded6741bd9722a2a21bc387 | Python | 3,190 | 103 | import numpy as np
from numpy import pi,linspace
import cmath, random
from pylab import *
from forward_backward import *
# hamitonian for H2
g0 = -0.4804 ;
g1 = +0.3435;
g2 = -0.4347;
g3 = +0.5716;
g4 = +0.0910;
g5 = +0.0910;
Hamiltonian = g0 * tensor(qeye(2), qeye(2)) + g1 * tensor(sigmaz(), qeye(2)) + g2 * tensor(qe... |
b9d2f10888486395401745bdcec3b2b892adcc663b3c197eea45e1e367241fe9 | Python | 3,191 | 96 | import pandas as pd
import numpy as np
import argparse
import matplotlib.pylab as plt
from rdkit import Chem
import rdkit.Chem.Descriptors
import os
def pref_split(smiles_string):
"""
splits a string on '|' into a list with two elements, starting from the right
the prefix token must be in '<pref... |
fd73fde3577f6f55b17efa724d0bed03fede28e7dd99abad897ee653fcf3645c | Python | 3,192 | 83 | import prov.model as pm
from .Core import Core, getUUID
from ..core import Constants
class DataElement(pm.ProvEntity, Core):
"""Class for NIDM-Experiment DataElement Objects.
Default constructor uses empty graph with namespaces added from NIDM/Scripts/Constants.py.
Additional alternate constructors for u... |
9bcb14a83daa7a4645663f8db0cb58e9c3834af450f0968df7688d4eed56ead9 | Python | 3,194 | 79 | """
Author: Mingjian He <mh1@stanford.edu>
em module contains a general run_em() function that works across SOMATA
"""
import numpy as np
from tqdm import tqdm
def run_em(obj: object, y=None, init_from_data=False, e_kwargs=None, m_kwargs=None,
max_iter=10, stop_thresh=np.finfo(float).eps, ignore_numerr=F... |
35debf39d5a971e805d99299de0e5ecf78277502ea118259cdbd2278e48fd8d5 | Python | 3,200 | 91 | import random
import copy
import Levenshtein as lv
from rdkit import Chem
import numpy as np
class Levenshtein_augment():
def __init__(self, source_augmentation=10, randomization_tries=1000):
self.source_augmentation = source_augmentation
self.randomization_tries = randomization_tries
def ... |
3c2551c5dd326d602c3485f0b2750636dd7c5a723f88b32e0e2a9bd1265b47d7 | Python | 3,202 | 103 | from enum import Enum
from centriole.zernike import get_zernike_indexes
"""Root module measurement category"""
C_RADIAL_DISTRIBUTION = "RadialDistribution"
class CenterChoice(str, Enum):
SELF = "These objects"
CENTERS_OF_OTHER = "Centers of other objects"
EDGES_OF_OTHER = "Edges of other objects"
"""L... |
68b0a5e2c84b93a9825c9184621edae703bfad5e4c9fe2ecad627403eff2885f | Python | 3,203 | 113 | from __future__ import annotations
import sys
from typing import TYPE_CHECKING, Dict, Optional
if sys.version_info >= (3, 8):
from typing import TypedDict # pylint: disable=no-name-in-module
else:
from typing_extensions import TypedDict
if TYPE_CHECKING:
from imctools.data.acquisition import Acquisition... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.