sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
6fa929f7d97af6e4791691ea6b5f28648d65f3513a109d481355d0af5e9ad8ff
Python
1,466
62
import keras from keras.models import load_model import numpy as np import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix ### PARAMETERS # number of kernels and width of kernels in CONV layer kn = 64 kw = 21 kn1 = 4 kw1 = 7 kn2 = 16 kw2 = 13 kn3 = 64 kw3 = 21 # ...
e543c8a5286f900051147c5beb685b5767c5a3dcc0eb8bd52a7e2b0342c67291
Python
1,466
55
#TODO SEP 08 version import os.path from data.base_dataset import BaseDataset, get_transform from data.image_folder import make_dataset from skimage import io from data.image_folder import merge_datasets import random import numpy as np import re def numericalSort(value): numbers = re.compile(r'(\d+)') parts ...
d4f2411adcd619974b26289134ce6a7c50b12cec278d5308ce743751b89522b7
Python
1,467
30
from .auto_augment import RandAugment, AutoAugment, rand_augment_ops, auto_augment_policy,\ rand_augment_transform, auto_augment_transform from .config import resolve_data_config, resolve_model_data_config from .model_config import resolve_input_data_config from .constants import * from .dataset import ImageDataset...
0b326042dcbe1bb629bb3d9bd070ae840b48fe2c50c79375552827d618f3da19
Python
1,469
45
import pandas as pd import matplotlib.pyplot as plt import numpy as np x = ['0','0.05', '0.1', '0.17'] def get_res(dataset): rmse = [] r2 = [] for i in x: path = f'../results/chemformer_snn/dropout{str(float(i))}/{dataset}/tables/' df = pd.read_csv(path + 'avg_res.csv') df = df[(df['...
3546421377ee7ba96b659420a1ba39951d5e16cf193991e8b0c0c3fb0c88f08f
Python
1,471
60
import keras from keras.models import load_model import numpy as np import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix ### PARAMETERS # number of neurons in LSTM layers lstm1 = 64 lstm2 = 0 lstm3 = 0 # number of neurons in FC layers fc1 = 200 fc2 = 100 # time window ...
d7f21346935fa56af852d77418a4a8c91207619f8b9d794c24ad847b74f9df88
Python
1,471
45
import json import os import shutil from pathlib import Path from .jsonldutils import load_file from .utils import fixing_old_schema def migrate2newschema(path, inplace=False, fixed_path=None): path = Path(path).resolve() if path.is_file(): print(f"migration of file: {path}") new_path = migra...
b22e17002dfe23dfbe1d24dca58a550278961af1918e1e60cb5c952ef4fa94d2
Python
1,475
50
import json from .model import ( Activity, Item, Protocol, Response, ResponseActivity, ResponseOption, ) def identify_model_class(category): # Normalize prefixed forms to full URIs if category.startswith("reproschema:"): category = category.replace( "reproschema:",...
d949e2fa124aab3a11a28ec1ff88616c65b59efb9d84605973a10f0556099e7f
Python
1,475
50
from .wrap_torch import ( base_triangle, triangle_modified, cyclic_lr_base, cyclic_lr_exp_range, exp, step, reduce_on_plateau, cosineannealingwarmrestarts, cosineannealingLR, ) from .wrap_monai import warmupcosineschedule # defining dict for schedulers - key is the string and the v...
29705e4d536fbc8145b51649fe551709b4a2d8936290227bb4ef926c9f847157
Python
1,478
48
# -*- coding: utf-8 -*- import numpy as np import pytest from numpy.testing import assert_array_almost_equal from pysteps.postprocessing.ensemblestats import excprob from pysteps.tests.helpers import get_precipitation_fields from pysteps.verification import probscores precip = get_precipitation_fields(num_next_files...
880545593954be9bdedbed8deff84d549f128bb29cb462de888e82c47940b840
Python
1,479
47
import pyControl.hardware as _h class LoadCell(): def __init__(self, port1, port2, rising_event_A = None, falling_event_A = None, rising_event_B = None, falling_event_B = None, debounce = 5): self._cell_threshold_high = _h.Digital_input(port1, rising_event_A, falling_event_A, debounce) self...
fb85d978becb9d86e1b7c5f7537e4931d20cd9d0d3a161fe1e98a12ad2bed5bc
Python
1,479
46
import shlex import subprocess # nosec B404 import pytest from GANDLF.entrypoints.subcommands import cli_subcommands as gandlf_commands old_way_entrypoints = [ # old-way entrypoints "gandlf_anonymizer --help", "gandlf_collectStats --help", "gandlf_configGenerator --help", "gandlf_constru...
caf9329bb4194460e6b3623c1aa67eede5e2bcca53eb04ec9418fcf495d0098e
Python
1,480
26
from .base_options import BaseOptions class TestOptions(BaseOptions): """This class includes test options. It also includes shared options defined in BaseOptions. """ def initialize(self, parser): parser = BaseOptions.initialize(self, parser) # define shared options parser.add_argum...
ad9842a79685183a9dc21bd844d3b2a4410c2b5491f5c2bfdf2ffaec81c21006
Python
1,481
55
import torch from rdkit.Chem import AllChem import pandas as pd from rdkit import Chem import numpy as np from rdkit import DataStructs import torch.nn as nn import torch def to_fp_ECFP(smi): mol = Chem.MolFromSmiles(smi) return AllChem.GetHashedMorganFingerprint(mol,2,2048) def toarray(fp): array = np.z...
499631e59c5ae5d2a36e3172a7e9e1a0feb8fc22fa3b404be38c447a1eef7b6c
Python
1,483
54
import torch from torch import nn class LayerScale(nn.Module): """ LayerScale on tensors with channels in last-dim. """ def __init__( self, dim: int, init_values: float = 1e-5, inplace: bool = False, device=None, dtype=None, ) -> ...
91a54fe722f628151c4ecffb5e5ec90236fd0a60fed89b9b623b69f9191b3d91
Python
1,486
69
from __future__ import division import matplotlib.pyplot as plt import sys sys.path.insert(0, '../../helpers/') from circ_stats import * import glob from pickle import dump thr = 20 #45 files = glob.glob("../preprocessed_data/*txt") files.sort() M=[] S=[] E=[] for si,fname in enumerate(files): bkg = fname.split(".t...
4a2a6c7e65ec465c6e79c5c5c6166ed06c1fb257047834067b48f2a8b26a0140
Python
1,487
47
""" Count co-occurence of cluster classes by moving a sliding window Author: Candace Liu Date: 4/6/21 """ import os import numpy as np from PIL import Image cluster_overlay_dir = "overlays_pxClusterIDs" points = list(range(1,13)) clusters = list(range(1,21)) step_size = 3 window_size = 6 # Create generator for all ...
9658f16cb80680584de50ef7ddc0c796989a0bf655abb9890c3aa682fb71ccc1
Python
1,488
47
import numpy as np import pytest from pysteps import io from pysteps.tests.helpers import get_precipitation_fields precip, metadata = get_precipitation_fields( num_prev_files=1, num_next_files=0, return_raw=False, metadata=True, upscale=2000, ) @pytest.mark.parametrize( "precip, metadata", ...
ba16faa024d5835c4d1d3cf0638b03da25d79aa45c314daf32d86a53aafa822f
Python
1,489
42
import numpy as np # define HH model class HH: def __init__(self, v_init=-65.0, n_init=0.3177, m_init=0.0529, h_init=0.5961): self.v = v_init self.n = n_init self.m = m_init self.h = h_init self.C = 1.0 self.g_Na = 120.0 self.g_K = 36.0 self.g_L = 0.3...
e9048790ce995abf362375fb0a2b3e64d7264adc6a278501ba36639d02adf0c9
Python
1,491
38
#!/usr/bin/env python # coding: utf-8 import subprocess as sub import os import time # The following code is to create multiple containers in docker and input multiple files containing multiple candidate # molecules into different containers. Tandem mass spectrometry of the candidate molecules are predicted and compa...
07a629703994ed6054ff8db72365f04500e739ec1e97ee3528f47b750b63a444
Python
1,493
41
# -*- coding: utf-8 -*- import pytest from pysteps.visualization import plot_precip_field from pysteps.utils import to_rainrate from pysteps.tests.helpers import get_precipitation_fields import matplotlib.pyplot as plt plt_arg_names = ("source", "map_kwargs", "pass_geodata") plt_arg_values = [ ("mch", {"drawlon...
bea3973287eade3e0da96b7825d29a2d0205b422327aa35b1ff9cbec196477c6
Python
1,496
36
# -*- coding: utf-8 -*- import torch from torch.autograd import Function from numpy import prod class HookFunction(Function): @staticmethod def forward(ctx, input, labels, y, fixed_fb_weights, train_mode): if train_mode in ["DFA", "sDFA", "DRTP"]: ctx.save_for_backward(input, lab...
8c14e44f9577c5b7cb369f2a3eb4ac2aae3cc505ddc7339d0dade8822b137f7f
Python
1,497
33
from src.models.tabular.widedeep.base import WDBaseModel from pytorch_widedeep.models import TabResnet class WDTabResnetModel(WDBaseModel): def __init__(self, **kwargs): super().__init__(**kwargs) def build_network(self): self.model = TabResnet( column_idx=self.hparams.column_idx...
eb31f753dd3687683154c97c6af62a817d24aaebf281617f190aac64340ff637
Python
1,497
79
# -*- coding: utf-8 -*- from allensdk.brain_observatory.ecephys.ecephys_session import EcephysSession from allensdk.brain_observatory.ecephys.ecephys_project_cache import EcephysProjectCache from allensdk.brain_observatory.ecephys.stimulus_analysis.drifting_gratings import DriftingGratings from allensdk.brain_observa...
78b3b5173db3a85329e7aec5392414089e33677f8ce81b1998bbfe372d5584fc
Python
1,498
52
# -*- coding: utf-8 -*- import os import pytest import pysteps from pysteps.tests.helpers import smart_assert pytest.importorskip("h5py") root_path = pysteps.rcparams.data_sources["knmi"]["root_path"] filename = os.path.join(root_path, "2010/08", "RAD_NL25_RAP_5min_201008260000.h5") precip, _, metadata = pysteps....
31314b9e8b837441059143b9c0dff9d0965d6f698b51e4f062fb584d2b6d967e
Python
1,500
63
import numpy as np import pytest from pysteps import motion from pysteps.nowcasts import utils as nowcast_utils from pysteps.tests.helpers import get_precipitation_fields main_loop_arg_names = ( "timesteps", "ensemble", "num_ensemble_members", "velocity_perturbations", ) # TODO: add tests for callbac...
cb120ce88816486a4f5fbd7266f832384f333c00b6b1f498a100f3c736587614
Python
1,500
46
""" 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. """ __version__ = '0.4.153' __date__ = '2026-10-21' import sys import importlib import types # If the system-wide gemmi is already loaded ...
a756d4c9fa2831d6208535eba1ccf745cbd73a299836248022747e3b200a6b51
Python
1,503
57
import platform from distutils.log import INFO from os import chdir, getcwd from setuptools import Command class Document(Command): description = 'Create documentation for library and apps' user_options = [] # user_options = [ # ('chdir=', None, 'path where to generate the doc (will overwrite)') ...
73f91a0407a0ba2bb191b4a1a56acbe938dd90276684f6ec3608ffdad21bbb08
Python
1,504
56
from pathlib import Path import weakref import h5py from utils.eventslicer import EventSlicer class EventReaderAbstract: def __init__(self, filepath: Path): assert filepath.is_file() assert filepath.name.endswith('.h5') self.h5f = h5py.File(str(filepath), 'r') self._finalizer = w...
7a357b2a2f53c549cf8fc5ba4829934f7eb416456d0f4964cca825f0526ee95d
Python
1,505
47
""" Global Response Normalization Module Based on the GRN layer presented in `ConvNeXt-V2 - Co-designing and Scaling ConvNets with Masked Autoencoders` - https://arxiv.org/abs/2301.00808 This implementation * works for both NCHW and NHWC tensor layouts * uses affine param names matching existing torch norm layers * s...
973e780aed5ccb4990f716c401d64d1aa7b8355169bc40cf4b6b1a1cd0e95b86
Python
1,509
43
# 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...
0f9629044fad3b807c0bc8faed338981cc225c4d1c54828320214a5c41144838
Python
1,510
38
import torch import torch.nn as nn import torch.nn.functional as F from .layer import GradientLayer, BoundaryGradientLayer class PINN(nn.Module): def __init__(self, network, no_flux_bnd:bool): super(PINN, self).__init__() self.network = network self.grads = GradientLayer(self.network) ...
5e83f83da96e291511cf15229bb6c365d5bdeeadf96ecd2c4ec10f086ce7c085
Python
1,513
43
import argparse def boolean_string(s): if s not in {'True', 'False'}: raise ValueError("%s: Not a valid Boolean argument string" % s) return s == 'True' def get_args(): parser = argparse.ArgumentParser(description="Training Arguments") parser.add_argument('--save_dir', default="checkpoints",...
689e74561c40da72250f566e5a17db92929c776e43bd7eb8dfa7bc84c4b6a5b6
Python
1,519
44
import inspect from typing import Any import scipy.io as sio class MatlabIO(object): __class_name = '' def __init__(self) -> None: pass def fill_dict(self, a_dict: dict[str, Any]) -> None: """ Recursively fills a dictionary of class members that are non-special :param a_...
450c390fb39bc930843dd588dd33cafd79850c3e40cd94ba986f7289fdd3a815
Python
1,520
51
import warnings warnings.filterwarnings("ignore", category=FutureWarning) from joblib import Parallel, delayed, cpu_count import os import sys # deletes all contents of dir and recreates it. def create_dir(path): if os.path.exists(path): print('Path ', path, ' already exists. Please delete and restart your job....
9750972347f85d3c9984260807d7fae3fe398360d98e9959e3db6c2bbd20562f
Python
1,523
42
import prov.model as pm from .AcquisitionObject import AcquisitionObject from ..core import Constants class MRObject(AcquisitionObject): """Class for NIDM-Experimenent MRAcquisitionObject-Level Objects. Default constructor uses empty graph with namespaces added from NIDM/Scripts/Constants.py. Additional ...
d30904073345a7f7531ad3560075d29d98d5c845486b9d2f2a1569e796b2fea4
Python
1,524
42
import prov.model as pm from .AcquisitionObject import AcquisitionObject from ..core import Constants class PETObject(AcquisitionObject): """Class for NIDM-Experimenent MRAcquisitionObject-Level Objects. Default constructor uses empty graph with namespaces added from NIDM/Scripts/Constants.py. Additional...
ed355d7d29f4e68742a4fbb4f1a5d488b6d3443a0314edd36a04e6d2fd67c573
Python
1,524
53
from matplotlib import pyplot as plt import pandas as pd import numpy as np from matplotlib.cm import viridis linewidth = 4 fontsize = 15 font = {'family' : 'monospace', 'weight' : 'bold', 'size' : fontsize } plt.rc('font', **font) # pass in the font dict as kwargs #Change the range of scan rate...
be4b6391e6d0d4f1dc66b99d5d96d8bc2fac488217457a1b3d6e2a68d88ed84e
Python
1,526
60
# -*- 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...
38141e31d2b050f24a9037745e51e335ffb594f8d00ac2ab176ee84a4126e350
Python
1,527
32
SEED_NO = 0 DEVICE = "cuda" EPOCHS = 300 NUM_GRAPHS_PER_BATCH = 256 NUM_FEATURES=32 NUM_TARGET = 1 EDGE_DIM=11 PATIENCE = 10 N_SPLITS = 5 MAXPATH = 2 MINPATH = 1 FPSIZE_RDKFP = 1024 MORGAN_RAD = 2 MORGAN_BITS = 1024 # Parameters for random forest model best_params_MD = {'n_estimators': 76, 'max_de...
60ae5926b4ad563216451493b223efa99764dcb9f93096e7e13e6e47dd6599a6
Python
1,528
48
import yaml import os class Config(object): """Configuration for the NetFrame applications.""" def __init__(self, version, config_yaml_path, debug=False): super(Config, self).__init__() self.version = str(version) self.debug = debug if '_' in self.version: self.sub...
b670ff91f2ac732775f8ea62b3a5601c452889972d8cbf97e605fdc5c3f071db
Python
1,528
37
import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as patches x_start = 40 y_start = 80 x_extent = 50 y_extent = -40 fig = plt.figure() fig.set_size_inches(5.5, 2.5) ax = fig.add_subplot(111) ax.set_xlim([0., 100.]) ax.set_ylim([0., 100.]) ax.set_xticks(np.arange(0, 101, 25)) ax.set_yticks(...
0362e1ca3ccb924e7c407fcb74a025dcfd785b66e57fd87bd099d5c0fcd673b3
Python
1,531
31
"""Shared helpers for the Hugging Face datasets / TFDS readers.""" import inspect from .targets import get_field, has_field def remote_code_kwargs(trust_remote_code: bool) -> dict: """Kwargs for datasets.load_dataset* that request loading-script execution, only when asked for. datasets 4.0 removed loading s...
08464f6ea8e38f7c3d7823e189f9ad814d498ec551e719d3d4709b1747152eaa
Python
1,533
62
""" All the losses are to be called from here """ from .segmentation import ( MCD_loss, MCD_log_loss, MCT_loss, KullbackLeiblerDivergence, FocalLoss, MCC_loss, MCC_log_loss, ) from .regression import CE, CEL, MSE_loss, L1_loss from .hybrid import DCCE, DCCE_Logits, DC_Focal # global defines...
0d28a74e15e384560af05cb17337dc1a54f02d102640d184d6dd4ebac464e3c8
Python
1,535
54
import glob import json from flask import Flask, request from flask_cors import CORS from flask_restful import Api, Resource from nidm.experiment.tools.rest import RestParser def getTTLFiles(): files = [] for filename in glob.glob("/opt/project/ttl/**/*.ttl", recursive=True): files.append(filename) ...
24daaf6dd297d85444bc0fa172df604d5f4795f13ccd87125f1fd51a36a4e0fa
Python
1,536
57
from matplotlib import pyplot as plt import numpy as np from matplotlib import cm linewidth = 4 fontsize = 15 font = {'family' : 'monospace', 'weight' : 'bold', 'size' : fontsize } plt.rc('font', **font) # pass in the font dict as kwargs colors = cm.Set2(np.linspace(0,1,8)) X_cor = [] Y_cor = ...
f4b0212a1aa5cd4899d00778129663ed6ad290a60c678a188cf7620e39efb31a
Python
1,536
70
import os import pytest import skimage import skimage.data import skimage.feature import skimage.io import cellprofiler_core.image import cellprofiler_core.measurement import cellprofiler.modules.matchtemplate import cellprofiler_core.object import cellprofiler_core.pipeline import cellprofiler_core.workspace import ...
65b3934385f973b1de84c9d95e9aa3d84af829afb173cb2f71c5b8c3d12a4225
Python
1,537
39
from enum import Enum class RescaleMethod(str, Enum): STRETCH = "Stretch each image to use the full intensity range" MANUAL_INPUT_RANGE = "Choose specific values to be reset to the full intensity range" MANUAL_IO_RANGE = "Choose specific values to be reset to a custom range" DIVIDE_BY_IMAGE_MINIMUM = ...
de563a2f562b3e875daad32ff1321561a89feda99e50f5d8b96ea4cbbb7befa4
Python
1,539
52
import json from ._setting import Setting class DataTypes(Setting): """The DataTypes setting assigns data types to measurement names Imported or extracted metadata might be textual or numeric and that interpretation should be up to the user. This setting lets the user pick the data type for their me...
a8b05fce051d75e4fa7830749ac6edd5ab49f56a3517f1ed7aa718ef5c6322a9
Python
1,546
46
import re import logging from enum import Enum from deeprank.models.forcefield.patch import PatchActionType, PatchSelection, PatchAction _log = logging.getLogger(__name__) class PatchParser: STRING_VAR_PATTERN = re.compile(r"([A-Z]+)=([A-Z0-9]+)") NUMBER_VAR_PATTERN = re.compile(r"([A-Z]+)=(\-?[0-9]+\.[0-9...
0f5166213226f4cfc0dc4e2c78caa80767f923252651fdfb361831750d222ba6
Python
1,548
67
import tkinter as tk class MyDialog: choice = False def __init__(self, parent): top = self.top = tk.Toplevel(parent) # Set position x = parent.winfo_x() y = parent.winfo_y() w = parent.winfo_width() h = parent.winfo_height() #print(x,y,w,h) top.geometry("+%d+%d" % (x+w/2-200, y+h/2-200)) ...
a1f9e9a699d2a3a3612e576926ed5eb06cb5e74a3cd808b4d1d10de27d7c78f6
Python
1,548
38
from src.models.tabular.pytorch_tabular.base import PTBaseModel from omegaconf import DictConfig from src.models.tabular.pytorch_tabular.repository.models.tabnet.tabnet_model import TabNetModel class PTTabNetModel(PTBaseModel): def __init__(self, **kwargs): super().__init__(**kwargs) def build_netwo...
64aa7ddb4c4c53ed22115cf15773984f4fbdded3737f979057348f61f7e027cd
Python
1,550
47
from deeprank.models.residue import Residue from deeprank.models.pssm import Pssm from deeprank.config.chemicals import AA_codes_pssm_ordered, AA_codes_1to3, AA_codes_3to1 def parse_old_pssm(file_): pssm = Pssm() for line in file_: data = line.split() chain_id, residue_number, residue_name = d...
061d046ff3a33d2a2fd89da540e7ad90b78cc95e352d05a2095794560fc1fc31
Python
1,551
49
from .trie import Trie class Gazetteer: def __init__(self, lower): self.trie = Trie() self.ent2type = {} ## word list to type self.ent2id = {"<UNK>":0} ## word list to id self.lower = lower self.space = " " def enumerateMatchList(self, word_list): if self.low...
063149e33da52520a9cb0856347616e86dfa51219f11992d40a24fc087aab93f
Python
1,552
45
import numpy as np def smallest_angle(x, y): """Least difference between two angles. Args: x (numpy array): An array of shape (number of vertices,1) containing the empirical polar angles y (numpy array): An array of shape (number of vertices,1) containing the predicted polar angle...
d0960c8112ab122cc595689b453a0852c23c68637bcca09e892c3ac588fbac84
Python
1,552
41
import torch import torch.nn as nn import torch.nn.functional as F class LogisticRegression(nn.Module): def __init__(self, vocab_size, output_dim): super().__init__() self.linear = nn.Linear(vocab_size, output_dim) def forward(self, x): return self.linear(x) class BasicDNN(nn.Module): ...
4673ebbe811a67f4615fcbcec0dbab6e938e867a1d9e8a0787a5478156b11f48
Python
1,553
49
""" Show final array configurations for multiple runs for side-dy-side comparison. """ import sys from pathlib import Path import numpy as np import sys from mayavi import mlab from megsimutils.viz import _plot_anatomy from megsimutils import read_opt_res R_ENCL = 0.3 # m, radius of an invisible sphere to plot to f...
8fd4abd91fad828c0c45df1d180aa0b7feeb128a39108581a2e8096cd4f65ded
Python
1,554
51
import numpy as np from scipy.signal import savgol_filter from fun_abfs import load_data, load_protocol from fun_signals import restrict, butter_filter, get_arg, get_dt class EPD: def __init__(self, t=None, data=None, stim=None, path=None, file=None, neuron=None, **kwargs): if len(t) != d...
0ce9b69bd243bc9c1ea8b63f54ea527cb85b9475ddbe4142de39294cb1db6f1c
Python
1,555
36
from src.models.tabular.widedeep.base import WDBaseModel from pytorch_widedeep.models import TabNet class WDTabNetModel(WDBaseModel): def __init__(self, **kwargs): super().__init__(**kwargs) def build_network(self): self.model = TabNet( column_idx=self.hparams.column_idx, ...
297e3f11481de2a3ad97aff9f2f4be2c4702c142ff8360ae2c1aef4e8f0dab34
Python
1,555
62
from __future__ import division from numpy import * import sys from scipy.stats import zscore sys.path.insert(0, '../../helpers/') from pickle import dump,load from pickle import load,dump from scipy.stats import * import warnings warnings.filterwarnings("ignore") W1=0.05 W2=0.3 f=open("../../Data/neural_data_conca...
20677eb0b8c2aabc244107576ff0a7f5ea81bcf9bfe7558c5e840dcc12226656
Python
1,556
50
from ._dependency import Dependency class MeasurementDependency(Dependency): """A dependency on a measurement""" def __init__( self, source_module, destination_module, object_name, feature, source_setting=None, destination_setting=None, ): "...
18b921e14ab7985720aa4ff975126408fe43cdb7d3836d2a1e6b4a36eaeb54f1
Python
1,565
56
""" MedialAxis ========== **MedialAxis** computes the medial axis or topological skeleton of a binary image. Rather than by sequentially removing pixels as in **MorphologicalSkeleton**, the medial axis is computed based on the distance transform of the thresholded image (i.e., the distance each foreground pixel is f...
cc15561e996b1fbc9e2c1499fea0f5e7a40fd04fd8ab15d4f9f5d98a594e0ad5
Python
1,565
58
import numpy as np import matplotlib.pyplot as plt # Define parameters dt = 0.1 # time step t = np.arange(0, 100, dt) # time vector # Define parameters Cm = 100 # membrane capacitance vr = -60 # resting membrane potential vt = -40 # threshold potential k = 0.7 # sensitivity of the membrane potential vpeak = 35 ...
f40ac2e2efec0c423040c47470bb2a7358daa5355103a2fc10d593b253ea45ae
Python
1,568
54
# Default logging settings for DeepRank. DEFAULT_LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'brief': { 'format': '%(message)s', }, 'precise': { 'format': '%(levelname)s: %(message)s', }, }, 'filters': { ...
3f7f87c339f202dd41d7373b22b494103cc6391e4e1f3586baab18868f8d3e79
Python
1,570
48
# -*- coding: utf-8 -*- """ Created on Tue Jan 15 14:36:39 2019 @author: Xiaoxuan Jia """ #------------# time to first spike import numpy as np from scipy.stats import norm import matplotlib.pyplot as plt import math def find_nearest(array, value, side="right"): idx = np.searchsorted(array, value, side=side) ...
eba422201453c883440ef1cd491bb0e2b10afe4904e5cf1a7b6f4f1d10f8fe7a
Python
1,570
42
from setuptools import setup, find_packages try: # for pip >= 10 from pip._internal.req import parse_requirements except ImportError: # for pip <= 9.0.3 from pip.req import parse_requirements # get requirements from requirements.txt install_reqs = parse_requirements('requirements.txt', session=False) try: ...
89ac07e857236c1062f923c193dabb9d5fc4cae20dd3a54dc4fc0ee2180f499d
Python
1,571
55
import matplotlib.pyplot as plt import pandas as pd import numpy as np plt.rcParams.update({'font.size': 13}) path_head = '../results/MLP_delta/' datasets = [ 'lipo/', 'freesolv/', 'delaney/'] top_1 = [] top_1_sd = [] half = [] half_sd = [] for i in datasets: path_top1 = path_head + 'top 1/' + i + 'tables/' df1...
b013245c8ad6228e3af5f071c5c552710a0f3fd1b6c9bbb8f8388b6623a681dd
Python
1,571
59
""" Closing ======= **Closing** is the erosion of the dilation of an image. It’s used to remove pepper noise (small dark spots) and connect small bright cracks. See `this tutorial <https://scikit-image.org/docs/dev/auto_examples/applications/plot_morphology.html#closing>`__ for more information. | ============ ====...
3e7f51621c65f09f4ad1337c46492885ef8ab14757a607cf69b224b81403cc27
Python
1,573
44
import torch from LAC import LAC from torchtext import data from torchtext import vocab from collections import namedtuple class LacTokenizer(object): def __init__(self): self.lac = LAC(mode="seg") self.lac.load_customization('static/data/addwords.txt', sep="\t") def __call__(self, text): ...
944c57bf0d031252d29274184fa54ab6509c868dc56885357ec7fccb6e9bd26f
Python
1,574
57
import keras from keras.models import load_model import numpy as np import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix ### PARAMETERS # number of neurons in FC layers fc1 = 200 fc2 = 0 ### END PARAMETERS for fi in range(5): x_test = np.loadtxt('../data/5fold_sp...
899fd325732b72cbced9e1c11effa3b3a61ea14a181d286def8dc9b2ef692f60
Python
1,575
41
import re from deeprank.models.forcefield.residue import ResidueClassCriterium, ALL_AMINO_ACIDS class ResidueClassParser: _RESIDUE_CLASS_PATTERN = re.compile(r"([A-Z]{3,4}) *\: *name *\= *(all|[A-Z]{3})") _RESIDUE_ATOMS_PATTERN = re.compile(r"(present|absent)\(([A-Z0-9\, ]+)\)") @staticmethod...
eb1796e3a88db176a748aa43b6102efd746cb175e09594804f99d9c5a465dfcd
Python
1,576
48
import os.path as osp import pytest from ptsa.data.readers.index import JsonIndexReader @pytest.fixture def reader(): here = osp.abspath(osp.dirname(__file__)) path = osp.join(here, 'data', 'r1.json') return JsonIndexReader(path) class TestJsonIndexReader: def test_aggregate_values(self, reader): ...
2fb48f6b310ead760dd31898cf52f329f8620377a48fd31a52a27aaf57a51d35
Python
1,580
48
import torch import torch.nn as nn class SpaceToDepth(nn.Module): """Rearrange spatial dimensions into channel dimension. Divides spatial dimensions by block_size and multiplies channels by block_size^2. Used in TResNet as an efficient stem operation. Args: block_size: Spatial reduction fact...
3be7f1fdbdf3e7e2ab7b3a60751f515b854fe715d9c5185e0d64837e22475621
Python
1,580
49
import json import os.path import random import tornado.httpserver import tornado.ioloop import tornado.options import tornado.web import tornado.gen import tornado.httpclient class IndexHandler(tornado.web.RequestHandler): def initialize(self, models): self.models = models self.model = None ...
9e212fbca44a0d6c567268c3fa8bd5f390bcb379798b7e96dce77b7823e14d45
Python
1,580
45
"""Unit tests for HelperFunctions methods that don't need a full Run()-configured RveInfo.""" import numpy as np import pandas as pd from dragen.utilities.Helpers import HelperFunctions from dragen.utilities.InputInfo import RveInfo def test_upsampling_rsa_conserves_volume_per_label(): rsa = np.array([ [...
d70aa7185123fb9e121c989c1ae0795b198f9c2f516187627f5da5f1ce591fb2
Python
1,580
40
import glob import cv2 as cv import numpy as np from models.epu import EPUNet from models.subnetworks import Subnet test = [cv.imread(img) for img in glob.glob("../data/banapple/test/*.jpg")] # pfm_order is useful to keep track of the order of the pfms and their respective subnetworks # it used later in the inferenc...
27c0b1a739a32d84602e50b78288fbe16b98ceee38c7b4e3dcfe893977ea5240
Python
1,581
46
import os import glob import time import argparse # Kerasa / TensorFlow os.environ['TF_CPP_MIN_LOG_LEVEL'] = '5' from keras.models import load_model from layers import BilinearUpSampling2D from loss import depth_loss_function from utils import predict, load_images, display_images, evaluate from matplotlib import pyplo...
5987a7c5634acec079bb9e3ef79606ed76c84f503265ba0de1fc193aca8fca35
Python
1,584
54
# -*- coding: utf-8 -*- """ pysteps.motion.constant ======================= Implementation of a constant advection field estimation by maximizing the correlation between two images. .. autosummary:: :toctree: ../generated/ constant """ import numpy as np import scipy.optimize as op from scipy.ndimage import...
bdbf9ba8c453a96bedf85bf2f96f5c4102e3b8e6e68982d435426356613089c3
Python
1,585
43
from typing import Optional import numpy as np import SimpleITK as sitk from torchio.transforms import Resample from torchio.typing import TypeTripletFloat class Resample_Minimum(Resample): """ This performs resampling of an image to the minimum spacing specified by a single number. Otherwise, it will perfor...
d8219ea538ac8a58b36d595df6e797df92059664fb2b78204b75d93d96cb7363
Python
1,586
53
from deeprank.features.FullPSSM import FullPSSM from deeprank.features.FullPSSM import __compute_feature__ as func ######################################################################## # # Definition of the class # ######################################################################## class PSSM_IC(FullPSSM):...
6f3d9cd0c0dfc39f42a231011d1f36860f1bb3044db6c9114b78881dbe7f2ed0
Python
1,587
58
""" Opening ======= **Opening** is the dilation of the erosion of an image. It’s used to remove salt noise (small bright spots) and connect small dark cracks. See `this tutorial <https://scikit-image.org/docs/dev/auto_examples/applications/plot_morphology.html#opening>`__ for more information. | ============ ======...
32b95863d31ec89b8c5c57d65b2d7fd64baad222a92bc2e346bba86d8d818fd1
Python
1,590
53
''' adapted from https://github.com/all-umass/ManifoldWarping ''' import numpy as np import scipy.spatial.distance as sd from sklearn.metrics.pairwise import euclidean_distances # from itertools import izip try: # Python 2 from itertools import izip except ImportError: # Python 3 izip = zip '''Distanc...
968336e0334cff8741491163e22d6d9890cc4782f7ac0974b3549b4e4ffa6e55
Python
1,590
53
class Dependency: """This class documents the dependency of one module on another A module is dependent on another if the dependent module requires data from the producer module. That data can be objects (label matrices), a derived image or measurements. """ def __init__( self, ...
388f3f900f5339b152f342c19564db3a2bea65a3196f1895456adaf873543c24
Python
1,593
60
#!/usr/bin/python3 import numpy as np from os.path import join as pjoin from os import linesep from shutil import copyfile from scipy.io import mmwrite from scipy.sparse import coo_matrix import gzip diri='data/raw' diro='data/coex' key='celltype' values=['dysfunctional'] #Load covariate info dc=np.loadtxt(pjoin(di...
94b3b5a1412570230db31cffb751b1df61831c3fc29b648a2778e3ce2f831bad
Python
1,595
40
from __future__ import division from unittest import TestCase import numpy as np from numpy.testing import assert_almost_equal from .feature_extraction import extract_features, extract_features_fixed class FeatureExtractionTest(TestCase): def test_extract_features(self): segmentation = np.array([[0, 0,...
cf2251900dd9b6fb935136c9c54316362845e5dc4f83eba1b18aad3fb2f7220c
Python
1,595
51
""" MIT License Copyright (c) 2022 Pawan Goyal Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, ...
3a41e95323b3c9d74c8ad3ab8facf854fc7e71ca5050b15ceeec21dfed3b18ee
Python
1,597
64
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup readme = open('README.rst').read() history = open('HISTORY.rst').read().replace('.. :changelog:', '') requirements = [ 'wheel>=0.23.0', 'Cython>...
4cda614c85380b77be86eeb6b03a510d6fe1ebfcdaf60ffb4e01231206917251
Python
1,598
49
from pathlib import Path import os from typing import Optional import numpy as np from panoptica import Panoptica_Evaluator def generate_instance_segmentation( prediction: np.ndarray, target: np.ndarray, parameters: dict, panoptica_config_path: Optional[str] = None, ) -> dict: """ Evaluate a...
998477a18b33f48dc67152acad8eee89a7c0bf2ba77c2c77ae58193e4f8cf73a
Python
1,599
58
import torch from .segmentation import MCD_loss, FocalLoss from .regression import CCE_Generic, CE, CE_Logits def DCCE(prediction: torch.Tensor, target: torch.Tensor, params: dict) -> torch.Tensor: """ Calculates the Dice-Cross-Entropy loss. Args: prediction (torch.Tensor): The predicted mask. ...
3fe9b6a29f66df7aa46cbc440364746e0051d7d2b14eed34d83bde9cd8d569b2
Python
1,600
51
"""Set up blueprint for ORCID authentication.""" from flask_dance.consumer import OAuth2ConsumerBlueprint, oauth_authorized from flask_dance.consumer.storage.sqla import SQLAlchemyStorage from flask_login import current_user, login_user from sqlalchemy.orm.exc import NoResultFound from afidsvalidator.model import OAu...
f894813a0295b2a0ae40049e2fea2a7012adadded7c39b4ab95b9c75160e4cd4
Python
1,602
61
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Feb 14 13:56:09 2022 @author: claudia Test file for behavioural clustering and clasification """ # Load module for behavioural decomposition from behavioral_decomposition import * # creat class cl_b=BehaviouralDecomposition() ## Training classifie...
99be7a9c966484694c269a9b4e32e0c1b3beaa255c33cc190b2e5d9243dfa729
Python
1,604
51
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages import guideseq import os if os.path.isfile("README.MD"): with open("README.MD", "r") as fh: long_description = fh.read() else: long_description="guide-seq" setup( name='guide_seq', version=str(guideseq.__version__), de...
fc6f1d9ef85c825263c8dc56de007694f141f2c005366f7981f25cfac59c48d4
Python
1,605
46
import yaml import json import numbers import numpy as np # Copied from ray.tune.logger: # https://github.com/ray-project/ray/blob/04bfba12742841bc0112d645ce85c537903fdf99/python/ray/tune/logger.py#L722 # and ray.tune.utils.util # https://github.com/ray-project/ray/blob/04bfba12742841bc0112d645ce85c537903fdf99/python/...
6ac2b089525aa51bd6b891197a643047b6aee7805f36e9264f3fb128365775f3
Python
1,608
50
import torch import torch.nn as nn from models.modules import ConvModule def simple_conv_layer( in_channels, out_channels, kernel_size, stride): return ConvModule( in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride...
462d6755ba00f501d59ec046c632c9ed1d549cb3a7c19e624b9e3325d10076a6
Python
1,611
53
import numpy as np import matplotlib.pyplot as plt import pandas as pd data = np.load("Trainingangle.npz") npz = data a = np.random.default_rng().uniform(low=0.01, high=0.1, size=1)[0] b = np.random.default_rng().uniform(low=0.01, high=0.1, size=1) print(data["DataX"].shape) print(data["DataY"].shape) print(data["Data...
35d3f21dba1eb4c68ebee29272a5fbdb574ee4de40f5517b339de238430d1abf
Python
1,612
58
import pandas as pd import numpy as np import scipy import math import torch from torch.nn.parameter import Parameter from torch.nn.modules.module import Module from torch.utils.data import DataLoader import matplotlib.pyplot as plt class ConvolutionNN(Module): """ Simple CNN layer """ def __inti__(...
6c08e35b1bd3ff67a30b7f9a43dd450cce44bf867a26aa7b8a78649f039878a0
Python
1,614
49
import tensorflow as tf from .layer import GradientLayer,BoundaryGradientLayer class PINN: def __init__(self, network): self.network = network self.grads = GradientLayer(self.network) self.boundaryGrad = BoundaryGradientLayer(self.network) def build(self,no_flux_bnd): TYR...
8b6090f47d0ff924d3c2959022e2e496060a53ab02d02d712f542c27a7e7475d
Python
1,614
44
"""If the predictions and labels inputs to the MLCube should come from different mount points and can't be referred to in a single csv, a custom entrypoint is needed to create a temporary csv file before calling GaNDLF's generate metrics command. This script should expect the same arguments passed to the command `mlcub...
f9629029e251bfb1b33b0d5c7b055b358751fac110b22caadf5f5e94579d4b52
Python
1,614
60
import numpy as np def get_arg(t, dt, t0=0, func='round'): """ Given t float, list or np.array returns argument of corresponding t values using dt """ if isinstance(t, float) or isinstance(t, int) or isinstance(t, np.int64) or isinstance(t, np.int32): float_or_int = True elif isinstance(t,...
5f8d588a255cafbb44eb48cb311301607511a812aa0395886907fd8cdef3f10c
Python
1,616
61
#!/usr/bin/env python import time import sys from rgbmatrix import RGBMatrix, RGBMatrixOptions from PIL import Image if len(sys.argv) < 2: sys.exit("Require a gif argument") else: image_file = sys.argv[1] gif = Image.open(image_file) try: num_frames = gif.n_frames except Exception: sys.exit("provid...
1b7ec3379466f236b8795f3aa3ece87bb893c22d363a4a2ba14198af393949a3
Python
1,617
52
from enum import Enum as BaseEnum from mrHARDI.base.ListValuedDict import Mergeable from mrHARDI.base.fsl import serialize_fsl_args _topup_pass_key_trans = { "warpres": "warp_resolution", "subsamp": "subsampling", "fwhm": "blur_fwhm", "miter": "n_iter", "estmov": "estimate_motion", "minmet": "...