sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
ec828626a9189f9bb54604f65d57f93ed2e09f9acc5615c3ba74f09c6118eb5b
Python
2,733
79
from typing import Optional import torch import torch.nn as nn from models.aggregators import BaseAggregator from models.aggregators.model_utils import MILAttention class AttentionMIL(BaseAggregator): def __init__( self, input_dim: int, num_classes: int, encoder: Optional[nn.Modu...
b47e8c9905bd3386412b479c0101ed370e498cef04634811cdeaf5b66bf6c184
Python
2,737
69
import math class Synapse(): ''' classdocs ''' def __init__(self, pre, post): ''' Constructor ''' self.type = 0 # 0: within a group; 1: different groups in the same layer; 2: other layer self.pre = pre self.post = post self.weight = 0 se...
b6f485071cd65f9d82cb577c6caeaeccbb7f2bbb215b9a16df7cd06d934aa8a6
Python
2,738
95
"""LIBSVM and SVMLight versions 1 and 2 decoding through datamonger-core.""" from __future__ import annotations from collections.abc import Mapping from dataclasses import replace from pathlib import Path from typing import cast from scipy import sparse from datamonger import _native from datamonger._decoder_option...
bd57ce72006f245566bc7ff95c034d826a975eb0334997a91f494d85a4140d64
Python
2,738
106
# coding: utf-8 """ """ import pytest import numpy as np from pysteps import motion, verification from pysteps.tests.helpers import get_precipitation_fields lk_arg_names = ( "lk_kwargs", "fd_method", "dense", "nr_std_outlier", "k_outlier", "size_opening", "decl_scale", "verbose", ) ...
017896d65332e00ce8b921a8f1d511ccfd8d51a7d1b5b54fffb552d593c77c9e
Python
2,743
91
''' JHK Python script for calculating the linear trend of SHAP values. ''' import numpy as np from netCDF4 import Dataset from scipy import signal import os, pathlib from scipy import stats #========================================================== # Set main directory #===============================================...
3dd44d583a5c225c0de124c2eefdcd1683094b77723748b6c900e3ac4bff728f
Python
2,745
70
import os import numpy as np import tensorflow as tf from util.util import myNumExt import time from sort.rafd8 import pet as myDB from ipdb import set_trace as st from math import ceil import random from options.AV45 import BaseOptions from tqdm import tqdm import logging opt = BaseOptions().parse() ...
616990a0ad9f07b34d62e916843a24acaee9aa132458d5f727f995164f59665b
Python
2,746
88
# JHK # Python script for generating ED Figure 10 from netCDF4 import Dataset import numpy as np import matplotlib.pyplot as plt #========================================================== # Set main directory #========================================================== hdir = '/home/jhkim/model/deep_detection' #====...
7378fd82d514c3c6b09f07e3db910ba7da4081f81a0328d7a8d20a64f9e4b102
Python
2,746
85
import gzip import numpy as np import os import pickle import tensorflow as tf # expect images as pickled and gzipped numpy arrays of shape (121, 145, 121) def loadImg(path): assert os.path.isfile(path), str(path) + " does not exist" with gzip.open(path, 'rb') as fh: img = pickle.load(fh)...
91c9eccee7c90e4aa771fc025f07cfd2b32fa8e7ce2a4b3027c0070748b8f1cc
Python
2,754
76
# -*- 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...
70df07bd3c0956466ea1217991987acc8522c2593eb361d5d52aa59854231706
Python
2,757
36
from devices._poke import _Poke from devices._MCP import MCP23017, MCP23008 from pyControl.hardware import Digital_output class Nine_poke(): # 9 IR beams, each with LED, controlled by MCP23017 i2c port expander. def __init__(self, port, rising_event_1 = 'poke_1', falling_event_1 = 'poke_1_out', ...
039770f64d030093db48375557a18b570f97e97e22424d5ea6977a9eb7e74ff3
Python
2,760
71
"""Abaqus + substructure. Case_029/030 cover substructure with DAMASK/MOOSE but are 100% ferrite, so no packet or block is ever generated there -- they only prove the pipeline is inert when nothing is transformable. This scenario is the counterpart: half the volume is martensite, so packets, blocks and the per-block A...
bbc8466eb1e69dc1bee6fb22dcce90a56fced8ff4929efd4b1ec66aa879b0be6
Python
2,760
85
# 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...
dbf3ff7969efd162ff91a23420ae19f6cedfce880bc927786198746a47084f26
Python
2,760
84
''' JHK Python script for calculating the linear trend of 5x5 occlusion sensitivity. ''' import numpy as np from netCDF4 import Dataset import os, pathlib from scipy import stats #========================================================== # Set main directory #==========================================================...
52d09338f56d60482903e8c489a99aba3c4e149dacc8e8d22ed40fc2ce09c381
Python
2,762
98
from copy import deepcopy from enum import Enum from mrHARDI.base.ListValuedDict import MagicDict from mrHARDI.base.fsl import serialize_fsl_args class OutlierReplacement(MagicDict): class Method(Enum): slice = "sw" multi_band = "gw" both = "both" def __init__( self, n_std=4,...
752cf25350f74b414d68d29c8fc68511b702b844454669c74e5029a0a4683a5f
Python
2,766
72
import numpy as np from netCDF4 import Dataset import os, pathlib #========================================================== # Set main directory #========================================================== hdir = '/home/jhkim/model/deep_detection' #========================================================== # Set out...
7ed38944b04231a5e035fb1eded90cebf225ca69dcddb328f6a43c989cf51471
Python
2,769
79
import numpy as np import pandas as pd results = { 'results-imagenet.csv': [ 'results-imagenet-real.csv', 'results-imagenetv2-matched-frequency.csv', 'results-sketch.csv' ], 'results-imagenet-a-clean.csv': [ 'results-imagenet-a.csv', ], 'results-imagenet-r-clean.csv...
3be167df5eed426c4c09be5e0f16aebbb0ebcf729925e8bf2c29c1575c05d9ea
Python
2,771
111
"""Plotting functions for SVAE model Author: Hikari Sorensen - Vector Engineering Team (hsorense@broadinstitute.org) Notes: """ import matplotlib.pyplot as plt from pathlib import Path # ClustalX AA Colors # (by properties + conservation) # http://www.jalview.org/help/html/colourSchemes/clustal.html clustalXAACol...
c2c1853404264d9e1d8c72d5f123146171e1a9cec7bc2efd288626f1ef86a7cf
Python
2,771
58
import numpy from numpy.typing import NDArray from typing import List, Tuple, Optional from pydantic import validate_call, ConfigDict from cellprofiler_library.opts.graytocolor import Scheme from cellprofiler_library.types import Image2DGrayscale, Image2DColor from cellprofiler_library.functions.image_processing import...
bdb79acea39781d4e8c1dd6c8c80c9f7e81a8ec630079bc6f6580d6498457398
Python
2,773
82
import functools from .._setting import Setting from .._validation_error import ValidationError class MultiChoice(Setting): """A setting that represents selection of multiple choices from a list""" def __init__(self, text, choices, value=None, *args, **kwargs): """Initializer text - the exp...
b61c17b6f1c77895df24e86e0b689a04720b6a2e1a8c20e7aad08dd26ec13357
Python
2,777
81
# -*- 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...
81aeebb0742df85b8d8c3e2fdd48dfaa0404ff48e779c5c10095feed757d9720
Python
2,779
64
import sys from nidm.core import Constants from nidm.experiment import Navigate import nidm.experiment.tools.rest def GetProjectsComputedMetadata(nidm_file_list): """ :param nidm_file_list: List of one or more NIDM files to query across for list of Projects :return: Dictionary or projects, each project h...
38c75593523763243d74fac75fd21ba176936889f926189a07a0a4c00d12bf2e
Python
2,781
91
import torch import torch.nn as nn import os import tifffile import numpy as np from model import UNet from dataset import * from config import * from torchvision import transforms from collections import OrderedDict dirc_data = args.dirc_data dirc_ckpt = args.dirc_ckpt dirc_result = args.dirc_result if ...
aeed27d3074b7817af3786352f03bdf0a96d3d03b55fa9297eed0b311533c461
Python
2,781
50
# coding=utf-8 """ ErodeObjects module for the CellProfiler library. This module contains the core algorithms for object erosion operations. """ from pydantic import validate_call, ConfigDict, Field from typing import Union, Tuple, Annotated from cellprofiler_library.types import StructuringElement, ObjectSegmentati...
958764f2d3dce97cf251bd4bd6212a6a223ada6288d15ae9162f5e82d079787c
Python
2,791
66
"""This module mimics the util.py module and contains helper functions primarily for the visualizer. These functions are used when input and output numpy arrays with a bit depth greater than the vanilla 8-bit pngs that are used as input""" import torch import numpy as np from PIL import Image import os import numpy as...
b86ca071d1dd761a0fce663857e094bdf33047df25fc2021c5c6ccaae38da265
Python
2,792
85
from ._does_not_predicate import DoesNotPredicate from ._does_predicate import DoesPredicate from ._filter import LITERAL_PREDICATE from ._filter_predicate import FilterPredicate from .._file_collection_display import FileCollectionDisplay from ...pipeline import ImageFile from ...pipeline import ImagePlane as ImagePla...
cb0bc3e5fc6f26b096a6210ee14148693bf7ba0dd2c91c4438d2a9a9a6cb9e09
Python
2,792
71
import functools from ._module import Module from ..constants.measurement import C_CHILDREN from ..constants.measurement import C_COUNT from ..constants.measurement import C_LOCATION from ..constants.measurement import C_NUMBER from ..constants.measurement import C_PARENT from ..constants.measurement import FTR_CENTER...
566dcde3a3e28dc92c5b5a9c2f98c3a945c1238be08721a23b6a3bdc7290c194
Python
2,794
74
""" pysteps.feature.interface ========================= Interface for the feature detection module. It returns a callable function for detecting features from two-dimensional images. The feature detectors implement the following interface: ``detection(input_image, **keywords)`` The input is a two-dimensional im...
99cf61b1ef6a6a3f0c6914952439bcedceb6f39dd03843e8739ddd5a1f218b97
Python
2,799
94
# -*- coding: utf-8 -*- """ pysteps.motion.proesmans ======================== Implementation of the anisotropic diffusion method of Proesmans et al. (1994). .. autosummary:: :toctree: ../generated/ proesmans """ import numpy as np from scipy.ndimage import gaussian_filter from pysteps.decorators import che...
980d3e5c328ac3cbcdc5cb7b64b51a755e081adb96fdbec502bef3b259efc0a3
Python
2,801
102
# -*- coding: utf-8 -*- import numpy as np import pytest from pysteps import motion, nowcasts, verification from pysteps.tests.helpers import get_precipitation_fields sprog_arg_names = ( "n_cascade_levels", "ar_order", "probmatching_method", "domain", "timesteps", "min_csi", ) sprog_arg_valu...
adbc59c8da8a230318325d3604688329ec74381ecb2a1005259a22c96748c008
Python
2,802
83
import argparse import importlib import pprint import os import tensorflow as tf from utils.config import Config parser = argparse.ArgumentParser(description='NetFrame, a pipeline for model development') parser.add_argument('--version', type=str, default='', help='version of exp, eg: $VERSION_$S...
9a7cca184c05303dc8950bbade4af294f622c648da7e16670ac0c0fb4aad5c21
Python
2,803
64
import yaml import argparse from pathlib import Path import utils def get_config(default_config_path): parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) arg = parser.add_argument arg("-c", "--config_path", type=Path, help="Path to the config.", default=default_conf...
7022afd4da7537f1da6c7d0474569848879f03fc30b6c1bb7b2dab4da2bca423
Python
2,804
81
import itertools import numpy as np import matplotlib.pyplot as plt from somata.basic_models import StateSpaceModel as Ssm from somata.basic_models import OscillatorModel as Osc from somata.source_loc.source_loc_utils import simulate_oscillation from somata.pac.decimate import DecimatedModel as Dec """ ##############...
82158940c787188e163cba1fbd01038a9e19d7596e6ecad2b346e9edd4cb8bba
Python
2,804
78
import wx import wx.lib.colourselect from ..artist import MODE_HIDE class WorkspaceViewRow: """A row of controls and a data item""" def __init__(self, workspace_view, color, can_delete): self.workspace_view = workspace_view panel = workspace_view.panel self.chooser = wx.Choice(panel)...
5745bd492fe0b8dfb809cca2f5e660caf9a37cc8e6724e0d1f22dc49ab4d8537
Python
2,806
66
import os import json import subprocess import numpy as np import pandas as pd import pickle as pkl import nibabel as nib from scipy.stats import zscore, pearsonr from os.path import join as pjoin from sklearn.preprocessing import StandardScaler from nod_utils import save_ciftifile # change to path of current file os....
eaf70e35aea6a415696182004959b4b8c9ae23cc4281ee6d21a00097dc466926
Python
2,807
54
import nengo import numpy as np # An asssociative memory network. Uses Voja + PES learning to learn a key-value mapping # Contains: # key_input: input to the network # value_input: the desired output # learning: if 0 learning is on, if positive learning is off # recall: the memeory network's output # Code taken from ...
65d1c72ff0d7db36eefd9f99f2522566778c53aeb0cc320b30dfe5e9f3ad60f5
Python
2,808
94
from __future__ import with_statement from alembic import context from sqlalchemy import engine_from_config, pool from logging.config import fileConfig import logging # this is the Alembic Config object, which provides # access to the values within the .ini file in use. config = context.config # Interpret the config ...
68803975102eb02ec3ef6e0b8fb188b8309aff88650962c324011514b4fe48ce
Python
2,809
103
import json from collections.abc import MutableMapping from copy import deepcopy from typing import Generator from mrHARDI.base.encoding import MagicConfigEncoder class MagicDict(MutableMapping): def __init__(self, init_attributes=None, dict2arg_trans=None): init_attributes = self._check_initialization(i...
9fb325661ed781d20c21606c9972f27b365a32781edd9eee83c1c72c0ecaf6c8
Python
2,809
73
# -*- coding: utf-8 -*- import torch import torch.nn as nn from function import trainingHook class FA_wrapper(nn.Module): def __init__(self, module, layer_type, dim, stride=None, padding=None): super(FA_wrapper, self).__init__() self.module = module self.layer_type = layer_type...
16c7b4b1a086e0edeadb746c33a6f671472b14ed4f4d4cd637ed112104ac699d
Python
2,810
92
import matplotlib as mpl mpl.use('agg') from matplotlib.testing.compare import compare_images from tempfile import NamedTemporaryFile import os.path import pygenometracks.plotTracks ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "test_data") tracks = """ [test with categories] fil...
a6e56eaa48be14d2d01583cb6500a97548fb0985ab8ebeb06c882773440df1d2
Python
2,811
87
import torch import torch.nn as nn import torch.nn.functional as F class ResidualUnit(nn.Module): def __init__(self, units, activation='tanh', kernel_initializer='he_normal'): super(ResidualUnit, self).__init__() # Initialize the activation function if activation == 'tanh': sel...
5bc4e6bb96e775b19b5b95bb1d0775bdbe1badf60e7cd8123d0064f460b6dfac
Python
2,814
81
"""Module providing various utilities.""" from __future__ import annotations import datetime as dt import cv2 import numpy as np from sentinelhub import BBox, DataCollection, MimeType, SentinelHubDownloadClient, SentinelHubRequest, SHConfig from sentinelhub.evalscript import generate_evalscript S2_BANDS = ["B01", ...
1054c88f0eaabe7d028486607967228d6ab6d45575b83b7266f450869c20598d
Python
2,816
87
#!/usr/bin/env python3 """Check vendored Rust metadata and synchronize core test fixtures.""" from __future__ import annotations import argparse import hashlib import shutil import tomllib from pathlib import Path ROOT = Path(__file__).resolve().parent.parent CORE = ROOT / "crates/datamonger-core" def synchronize(...
5d6cdd32ae537bcabc6485cb8ae82dff36d2373fcfa2e92ada03d47900490f17
Python
2,816
93
from pathlib import Path from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Dropout, Flatten from tensorflow.keras.layers import Convolution3D, MaxPooling3D from tensorflow.keras.callbacks import Callback import tensorflow as tf class AdaptiveLearningRate(Callback): def...
c37534617cc1f644107aec819a46d4c59d0eff0704953ff339f6308ebccd76cb
Python
2,819
84
def filter_duplicate_names(name_list): """remove any repeated names from a list of (name, ...) keeping the last occurrence.""" name_dict = dict(list(zip((n[0] for n in name_list), name_list))) return [name_dict[n[0]] for n in name_list] def get_name_providers(pipeline, last_setting): """Scan the pipe...
b4e37a96c2d4cc1df84f092a18c747f9a5280decf3380e0a890f61d81282ec81
Python
2,822
62
import unittest import numpy as np from centriole.bg_compensate import backgr, MODE_AUTO, MODE_DARK, MODE_BRIGHT, MODE_GRAY class TestBackgroundCompensation(unittest.TestCase): def test_01_basic_functionality(self): # Create a simple synthetic image with known background img = np.zeros((100, 100), ...
82800e62e82da04a383594aa7bd02b8f6bbc22cfdd000884f678c6101d745888
Python
2,832
84
""" Global Context Attention Block Paper: `GCNet: Non-local Networks Meet Squeeze-Excitation Networks and Beyond` - https://arxiv.org/abs/1904.11492 Official code consulted as reference: https://github.com/xvjiarui/GCNet Hacked together by / Copyright 2021 Ross Wightman """ from typing import Optional, Tuple, Ty...
34a47e17b46349a7cf33882678cdf35b142ae95771b64ee06032f3ffed2456d2
Python
2,834
88
''' 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_...
88d8778ce3ea60baade962c2ebbbc196b3ce7d5f93d58f862e6edf2e323d3934
Python
2,834
89
''' 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_...
b1d9b604595fa65f82424edab26aa4588920066dd89a1e8c75f58b9df2a671d8
Python
2,835
70
import pandas as pd import anndata as ad import numpy as np from scipy.sparse import hstack,vstack,csr_matrix import argparse parser = argparse.ArgumentParser() parser.add_argument('--path', default="./data/", help='Location to save pseudobulks data') parser.add_argument('--filename', ...
b0c76c33db46223784fa524a33f3a8891a38d3d3107423e74746c0623c3a673f
Python
2,839
85
import time # type: ignore import datetime # type: ignore from signal import pause # type: ignore from samplebase import SampleBase # type: ignore from rgbmatrix import RGBMatrix, RGBMatrixOptions, graphics # type: ignore import subprocess # For system audio playback # Matrix and Graphics Configuration options =...
9a286b034346a31b3016efd96abcf95931d9c29d980876291bc4514085318e7e
Python
2,841
89
import os import numpy as np import pytest from lightgbm import Booster from numpy.testing import assert_allclose, assert_array_equal import s2cloudless from s2cloudless import PixelClassifier from s2cloudless.cloud_detector import MODEL_FILENAME @pytest.fixture(name="booster") def booster_fixture() -> Booster: ...
4fbe461e025f753a73bab348c9b8716415e5485ad2f02ddcb436c6804125578d
Python
2,843
99
from ._filter_predicate import FilterPredicate from ._does_predicate import DoesPredicate from ._does_not_predicate import DoesNotPredicate from .._file_collection_display import FileCollectionDisplay from ...constants.image import MD_SIZE_T, MD_SIZE_Z from ...constants.measurement import C_RGB, C_MONOCHROME class Im...
365241d52ec02715725235a1f7709601338924d3d184fd24d693d0fdfc92ad68
Python
2,848
90
# -*- coding: utf-8 -*- import os import pytest import pysteps from pysteps.tests.helpers import smart_assert pytest.importorskip("netCDF4") expected_proj = ( "+proj=geos +a=6378137.000000 +b=6356752.300000 " "+lon_0=0.000000 +h=35785863.000000" ) test_geodata_crri = [ ("projection", expected_proj, No...
7e28f020aae4797c0797f84dcbfa2b58d51da46832895c77b6c7638fd68b9b2e
Python
2,848
89
import os import json from allensdk.core.brain_observatory_cache import BrainObservatoryCache PV = 'Pvalb-IRES-Cre' GC6S = 'Slc17a7-IRES2-Cre/wt;Camk2a-tTA/wt;Ai94(TITL-GCaMP6s)/wt' def load_json_file(json_file): with open(json_file) as f: return json.load(f) def save_json_file(obj, json_file): wi...
cc77b261580e3d85e73282c42b7aa3fe25b66713e43a713ae668343b3f4af0fa
Python
2,849
79
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
bdf49cbbd0758d21c08fae4ebe26419d342d8184fe395fd084464fda49cda861
Python
2,852
83
# -*- coding: utf-8 -*- import pytest from pysteps.visualization import plot_precip_field from pysteps.utils import conversion from pysteps.postprocessing import ensemblestats from pysteps.tests.helpers import get_precipitation_fields import matplotlib.pyplot as plt import numpy as np plt_arg_names = ( "source",...
9ed8263e63834b300984f41a030560d85ce67e72696e86f7e98d156b383915d2
Python
2,854
91
from tempfile import mkdtemp from shutil import rmtree import os import logging from nose.tools import ok_ import h5py from pdb2sql import pdb2sql import numpy from deeprank.models.environment import Environment from deeprank.models.variant import PdbVariantSelection from deeprank.features.accessibility import __comp...
928c5482f70b0645d225505756fc32a75c6845b138fb2c255942046386ead5a3
Python
2,859
76
"""Named split assembly using the existing single-artifact decoders.""" from __future__ import annotations from collections.abc import Mapping, Sequence from dataclasses import replace from typing import Any from datamonger._errors import UnsupportedDecoderError from datamonger._models import ( DatasetSplits, ...
dfd72c2314d4a70a800ba4816a3e54085637e098296f7b7fb4d468ade4d63df8
Python
2,863
98
import torch from torch.utils.data import DataLoader from rdkit import DataStructs from rdkit import Chem from multiprocessing import Pool, cpu_count import pandas as pd from rdkit.Chem import AllChem from sklearn.metrics import r2_score import math class predict_process(): def __init__(self, loss_df_name)...
21a5a083d1907b55a8c9e42578066581d55d2732de157e943c10264a835f7208
Python
2,868
75
import pytest import numpy as np from collections import OrderedDict from torchmeta.transforms.splitters import ClassSplitter from torchmeta.toy import Sinusoid from torchmeta.utils.data import Task def test_seed_class_splitter(): dataset_transform = ClassSplitter(shuffle=True, num_train_per_class=5, num...
6f2f23fb135344341043348163bac16502c69a5672b70ef5905a9ab8999fe33c
Python
2,872
115
''' adapted from https://github.com/all-umass/ManifoldWarping ''' import numpy as np from correspondence import Correspondence from distance import SquaredL2 from itertools import product def dtw(X, Y, metric=SquaredL2, debug=False): '''Dynamic Time Warping''' dist = metric.between(X,Y) if debug: path = _p...
06a6d38afa6462707be36262d44802df4e4f71323b4fd54747d873b5f4f58743
Python
2,876
96
from pepars.utils import DNA class Template(object): def __init__(self, sequence, name = None, id = 0, \ reverse_complement_template_id = None): from . import Database as db self._sequence = sequence self._reverse_complement_template_id = None if name == None: ...
1605b776a70232b0a3235383e900feac9e41a8c596005398aee01ca2b74015b1
Python
2,881
63
# -*- coding: utf-8 -*- """ Created on Tue Jan 5 12:13:20 2021 @author: filtez This script is to concatanate the phoneme and word transcription files. It will align phonemes and words and create new files with a structure like (Phoneneme, Phoneme Onset, Phoneme Offset, Word, Word Onset, Word Offset) """ ...
328ef73ee3bfb995b83f3e1f49bb4b5f9883b751553ba7701c92179aca4467e6
Python
2,882
74
""" MultiStep LR Scheduler Basic multi step LR schedule with warmup, noise. """ import torch import bisect from timm.scheduler.scheduler import Scheduler from typing import List, Tuple, Union class MultiStepLRScheduler(Scheduler): """Multi-step learning rate schedule with warmup and noise. Outside warmup, de...
d5c606aa343ca66ce0aeb1f922792a841001e1c95129237f66e0b8aeeb431014
Python
2,883
93
import os import pytest import pysteps from pysteps.tests.helpers import smart_assert pytest.importorskip("pyproj") root_path = pysteps.rcparams.data_sources["fmi"]["root_path"] filename = os.path.join( root_path, "20160928", "201609281600_fmi.radar.composite.lowest_FIN_SUOMI1.pgm.gz", ) precip, _, met...
4ffb9d58b9f9fc7479db13c8b0fb485bbf30ca3bbbfa33416ec51dfd4727e32a
Python
2,884
96
import numpy as np import matplotlib.pyplot as plt import pandas as pd import cmath path = '/scratch/c7051184/' data_dict = {} for j in range(1, 15): fileold = 'station{0}/temptest{0}.npz'.format(j) filenew = 'station{0}/temptestmap{0}.npz'.format(j) data = np.load(path + fileold) print(data) data...
e1e75d99e5c586d4ca44ecc94ac38c8663cd4613d849e32407595d8fe57ce607
Python
2,885
80
# -*- 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...
91fedb7625379929204638e80867a9e2e0a828b89df508518b1eb253f61a9dab
Python
2,888
87
import os from pathlib import Path import shutil import subprocess import sys import pytest @pytest.mark.parametrize("test_path", ["tests", "tests/core"]) def test_test_startup_is_headless(tmp_path, test_path): tests = tmp_path / "tests" core = tests / "core" core.mkdir(parents=True) shutil.copyfile(...
4b95eb06e985903f2773e4ca6c8ff78586e40851f280d13faa4cf9cd156dee22
Python
2,889
73
#!/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, 'NaturalScenes') ma...
67279e3627ac19a3a74d81b5ee51a514acaba6a5ed270474c57cbb2c7e66cbea
Python
2,892
91
import matplotlib.pyplot as plt import numpy as np import matplotlib.style import matplotlib as mpl import pandas as pd # fontsize plt.rcParams.update({'font.size': 18}) cutoff = [0,0.3,0.35,0.4,0.45,0.5] def get_res(dataset, model): if model == 'Chemformer': path = f'../results/Chemformer/single_task/{dat...
d8b406366a6a73de1e8d71ca0f0a5ddb974fd7fedc63e4d3613e8c26d2afdba1
Python
2,893
81
# -*- 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...
f3c5d5079ba1df0af5d0e2651a94272e3a30117ef370f45026bf149108be31c6
Python
2,893
100
import os import pandas as pd def load_transform_results_figure1(dataset, parcellation): idiff_path_combined_bins = os.path.join( "..", "..", "results", "idiff_combined_bins", dataset, "GS", f"dataset-{dataset}_preprocessing_level-GS_parcellation-schaefer2...
001b76b012d51645bfe5f7c0f8692b15ac42162d80904393dd68eba1489fd9f2
Python
2,896
75
# -*- coding: utf-8 -*- """ Implementation of Adaptive gradient clipping """ from typing import List, Optional import torch def unitwise_norm(x: torch.Tensor, norm_type: Optional[float] = 2.0) -> torch.Tensor: """ Compute norms of each weight tensor in a model, and return the global norm. Args: x...
47ae4787e1f0e9d8a1198558af4d4c674b9fa1c5839159ff2329ad419925f273
Python
2,898
94
# -*- coding: utf-8 -*- """Fit STEPS motion perturbation parameters to the output of run_vel_pert_analysis.py and optionally plots the results. For a description of the method, see :cite:`BPS2006`.""" import argparse import pickle from matplotlib import pyplot import numpy as np from scipy.optimize import curve_fit d...
6c6b5c4d45def09cc884d3ea0a20543a0840e98dcc70546db221e3fa3ef1e651
Python
2,900
72
# Copyright (c) OpenMMLab. All rights reserved. import warnings import numpy as np import torch def average_performance(pred, target, thr=None, k=None): """Calculate CP, CR, CF1, OP, OR, OF1, where C stands for per-class average, O stands for overall average, P stands for precision, R stands for recall a...
9d240ad77876ef813f5843d992d9e36626d7f5cef12e896a1a105e6087d380d9
Python
2,901
84
from pathlib import Path import pytest from rdflib import Graph, URIRef from nidm.core import Constants from nidm.experiment.Utils import read_nidm KEY_PREDS = { "prov:used": URIRef(Constants.PROV["used"]), "prov:hadMember": URIRef(Constants.PROV["hadMember"]), "prov:wasInfluencedBy": URIRef(Constants.PROV...
8857ae2dc9588ea628eb8cdcad9dee5522dc463d9fd16f0815eab034cf7d7dbd
Python
2,904
104
#!/usr/bin/python3 import itertools import numpy as np from os.path import join as pjoin import pandas as pd import os from os import linesep diri='data' diro='data/raw' #Cell types to keep for light-weight demonstration subsets={'celltype':set(['dysfunctional','naive'])} #Probability of dropping cell for downsampled...
d8210476f9c46945e66056b4ce1875b7436d4c9d929cf674e16d31a141bda1bb
Python
2,907
107
import numpy as np import pytest from pysteps import motion, nowcasts, verification from pysteps.tests.helpers import get_precipitation_fields anvil_arg_names = ( "n_cascade_levels", "ar_order", "ar_window_radius", "timesteps", "min_csi", "apply_rainrate_mask", "measure_time", ) anvil_arg...
221ba733d47d61112a93e2e1fc40b706cdaec58025d34f39835b9d1d2add425a
Python
2,908
64
import torch import torch.nn.functional as F import torchio as tio import time import logging logger = logging.getLogger(__name__) def series_pred(item_pointers, load_item, model, test_time_flipping=False, device=None): device = torch.device("cuda" if torch.cuda.is_available() else "cpu") if device is None els...
4d6d742d1d6d98cb3fd9caf387690aa85e7cec61e99365056a9da2aaf0cc5b0e
Python
2,908
79
#!/usr/bin/env python # coding: utf-8 import os import pandas as pd import numpy as np from sklearn.preprocessing import StandardScaler import matplotlib.pyplot as plt from matplotlib import gridspec import matplotlib.transforms as transforms import seaborn as sns import statsmodels.api as sm from statsmodels.formula....
03e32fdeab25d44c29db95e94e6aef49609435b9dc36bab09cac68e7d7c8c1a3
Python
2,909
62
import os import tensorflow as tf from .architecture import neurite_classifier from .data import prepare_pattern_dataset def train_pattern_vs_unpatterned(train_image_dir='PatternTrainImages', validation_image_dir='PatternValidationImages', as_generic=False): """This method trains the model to distinguish betwee...
c86c2d8d0d8c8098886250e784c6e07266601115d2640cfb59505a82bd5cc060
Python
2,912
80
import pytest from click.testing import CliRunner from GANDLF.entrypoints.config_generator import new_way, old_way from . import CliCase, run_test_case, TmpDire, TmpFile, TmpNoEx # This function is a place where a real logic is executed. # For tests, we replace it with mock up, and check if this function is ...
cf1c0514c83d03bb29f2d68f7d453b963f05bd29b4e9068c151df8443e41ab5f
Python
2,917
74
# -*- coding: utf-8 -*- import torch import torch.nn as nn from function import trainingHook class FA_wrapper(nn.Module): def __init__(self, module, layer_type, dim, stride=None, padding=None): super(FA_wrapper, self).__init__() self.module = module self.layer_type = layer_type...
4ba99acf43444498a435f579cfc160f499235aed110fd77624324520bfc0bf31
Python
2,920
92
# -*- 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...
4f069a01d22e70e9cf18104fe547867e97bd829eaaf98b01f6e9462e99a8b464
Python
2,920
80
import os import torch import torchtext import torchtext.data import torch.nn as nn import torch.nn.functional as F from model import CNN from data import DataIterator from collections import namedtuple from sklearn.feature_extraction.text import CountVectorizer from sklearn.cluster import KMeans import joblib from ...
11f632b4c00dbe39658c9010e1ae0efd3ba41de1adceb27c86f902c657a0232a
Python
2,922
124
""" Computes GLM metrics. @author: JingyiGF """ from .family import * def get_deviance(y, yhat, family, theta): """Deviance metrics. Parameters ---------- y : array Target labels of shape (n_samples, ) yhat : array Predicted labels of shape (n_samples, ) distr: str dis...
7d0f037e31bcaa35a7e07929bdfe5704704ad5d87de96c02b9c695a9dbcdc9f4
Python
2,924
101
import Functions.globalFunctions.utils as utils import Functions.globalFunctions.morphology_v2 as mphv2 import pandas as pd import numpy as np import matplotlib.pyplot as plt # https://matplotlib.org/stable/gallery/color/named_colors.html#sphx-glr-gallery-color-named-colors-py import matplotlib.colors as mcolors import...
febefffb1e709d9c14449bfe0f2ad197b92d194f67a9ae4c8f2fea40a7a398e7
Python
2,925
94
# -*- 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...
2bcaf110e3316f1812219b4af87c879ebca0b2ae84d1e0f0f9a250d65b63d39c
Python
2,926
86
from typing import Optional import torch import PIL.Image import numpy as np from torchio.transforms.intensity_transform import IntensityTransform from torchio.data.subject import Subject class RGB2RGBA(IntensityTransform): """ Convert RGB image to RGBA image. """ def __init__(self, **kwargs): ...
e025f8f73cd66a1597b6ea834aa4f0f35dbc070bed7ec7783e3dd4bc5fdc97a7
Python
2,929
87
# -*- coding: utf-8 -*- """ pysteps.io.readers ================== Module with the reader functions. .. autosummary:: :toctree: ../generated/ read_timeseries """ import numpy as np def read_timeseries(inputfns, importer, **kwargs): """ Read a time series of input files using the methods implemented...
4044e5835e650b002649531238d2fe84ce278807637d2dd495311b43780d537b
Python
2,933
85
from typing import Optional import torch from torchio.data.subject import Subject from torchio.data.image import ScalarImage from torchio.transforms.intensity_transform import IntensityTransform from torchio.transforms.preprocessing.intensity.clamp import Clamp class Threshold(IntensityTransform): """Threshold i...
947df3447af4af7a914b9b4bb14d4b0dd2c875e0ca279c7ad94b3d0f77af0df4
Python
2,943
75
#!/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, 'NaturalMoviesA') m...
4660379a803f08973f78b7b79551ea63f9af7c547c794da046e599363e230e87
Python
2,945
74
# -*- coding: utf-8 -*- # From https://github.com/jiesutd/LatticeLSTM import torch import torch.autograd as autograd import torch.nn as nn import torch.nn.functional as F import numpy as np # Build CNN to learn character-level features. class CharCNN(nn.Module): def __init__(self, alphabet_size, embedding_dim, h...
fc88b178dc17c46011003f070ff509489fffe251c64964d3b07eca36376a030a
Python
2,946
94
import math import numpy as np import scipy.linalg import torch class ConstantODE(torch.nn.Module): def __init__(self): super(ConstantODE, self).__init__() self.a = torch.nn.Parameter(torch.tensor(0.2)) self.b = torch.nn.Parameter(torch.tensor(3.0)) def forward(self, t, y): r...
6dfba570174594c1aa12062f6668017cd56da00f1f8edababb1f1a49e218494e
Python
2,947
100
""" Command-Line script used to evaluate oversegmentation of segmentations produced by the automatic method in the form of different metrics: - ratio of segments in the automatic segmentation vs the ground-truth segmentation - statistics on segment split count comparing segments in ground-truth vs overlapping segments...
d29782f746b37fb4d2bc3efc892c4f42046119bb0233a692515bdd0fb348b986
Python
2,949
86
# -*- coding: utf-8 -*- ''' --------- Imports ----------- ''' import matplotlib.pyplot as plt import numpy as np import pandas as pd import scipy as sp from prettytable import PrettyTable ''' --------- Pre-requisites: normality and variance ----------- ''' def normality(data_no_adap,data_div_adap,data_sub_adap):...
b521a3b575ffcec9a0da7e17a054f18e059ee529a907af6485290e6b0c9c3b61
Python
2,950
93
from itertools import product from os.path import exists import numpy as np import plotly.graph_objects as go from plotly.subplots import make_subplots from traitlets import Dict from mrHARDI.base.application import (mrHARDIBaseApplication, prefix_argument) _aliases = { ...
a1a990d523934e90270bcbd0ebba36d7543afdb1311a0fe102eaa51c69497c02
Python
2,951
84
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Mar 11 14:55:44 2021 @author: siddhesh """ import os from typing import Dict, List, Union import torch class Logger: def __init__( self, logger_csv_filename: str, metrics: List[str], mode: str, add_epsilon:...
c89d92f9055f47c1189b21a81bdfe55e8c1b41eeb781204c3285c6fa592073f6
Python
2,958
70
from . BedTrack import BedTrack from . GenomeTrack import GenomeTrack import numpy as np DEFAULT_BED_COLOR = '#1f78b4' class TADsTrack(BedTrack): SUPPORTED_ENDINGS = ['.domain', '.domains', '.tad', '.tads'] TRACK_TYPE = 'domains' OPTIONS_TXT = GenomeTrack.OPTIONS_TXT + f""" # If the bed file contains a c...
146589ed0dd1275bf32c2265019b2726be4cec7d1f77dc2318b815ba2b70e8c0
Python
2,959
83
class _PssmRecord: def __init__(self): self.amino_acid_values = {} # uses one-letter codes as keys self.information_content = None class Pssm: "This object stores pssm data" def __init__(self): self._residue_records = {} # the keys should be residue identifiers def set_am...