sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
bc87241f65daaf3633ac8888e549945b2feb10ff6bc4aee49e46485ebf604f6c
Python
1,622
59
from __future__ import annotations from typing import TYPE_CHECKING, Hashable, Tuple import traits.api if TYPE_CHECKING: from ptsa.data.timeseries import TimeSeries __all__ = ['BaseFilter'] class BaseFilter(traits.api.HasTraits): """Base class for constructing filters.""" nontime_dims = traits.api.Tup...
93d36147c94ffa0b65542b2000e8548c7a256495d48e0fa3e65327fad8ebead8
Python
1,623
40
# coding=utf-8 """ an htmldialog with an ok button """ import wx import cellprofiler.gui.html.htmlwindow long_text = """\ This is a very important parameter which tells the module what you are looking for. Most options within this module use this estimate of the size range of the objects in order to distinguish them...
45bad5d00725325c50729258a47185909ddde45afa9802ec8b0f4cc4c358b26f
Python
1,624
61
from e2vid.model.model import * from collections import OrderedDict def load_model(path_to_model, return_task=False): print('Loading model {}...'.format(path_to_model)) raw_model = torch.load(path_to_model) arch = raw_model['arch'] try: model_type = raw_model['model'] except KeyError: ...
da5e4ec87550a17caceb29aaeff6eaeacb447694ab99cb9341a74ccd01b58592
Python
1,624
37
# Experiment class and constants used in specifying experiments. class Experiment: 'Class used to hold information about an experiment' def __init__(self, name, start_date, subjects, task, set_variables = None, persistent_variables = None, folder = None, summary_variables = None): ...
409f0bf1d209385720659b29c2e1e19366a28f1a2d7abf25d445382115cd5d06
Python
1,627
50
from __future__ import absolute_import import numpy as np from . import _propagate def propagate(image, labels, mask, weight): """Propagate the labels to the nearest pixels image - gives the Z height when computing distance labels - the labeled image pixels mask - only label pixels within the ...
6f894a9314a46f811dfbcd1f21135b65cea79307ac3487bc83160eefbb148479
Python
1,627
37
from src.models.tabular.pytorch_tabular.base import PTBaseModel from src.models.tabular.pytorch_tabular.repository.models.category_embedding.category_embedding_model import CategoryEmbeddingModel from omegaconf import DictConfig class PTCategoryEmbeddingModel(PTBaseModel): def __init__(self, **kwargs): s...
1716a2f30a7689db712f7689d75da7a5f93c92187ded1b81aeca0b506d76aff3
Python
1,628
39
from ._text import Text class Filename(Text): """A setting that displays a file name optional arguments - get_directory_fn is a function that gets the initial directory for the browse button set_directory_fn is a function that sets the directory after browsing browse_msg - mes...
5157b60d0952cda5f8ba37332ea4dd224280f4fe97ad09a858b620f20bd6035d
Python
1,628
72
from airtable import Airtable from . import Workspace def get_samples(metadata_filter): if not is_data_loaded: load_data_from_airtable() global FASTQ_files global samples global experiments current_experiment = None for experiment in experiments: if experiment["fields"]["N...
5528461d0feab285d491bcf08ea4ea73f2d98512e22c04815a8df9cb3be89a25
Python
1,628
49
import os import ftplib import os def upload_training(prefix_model, prefix,EPOCHS,lr, client="ftpclient",password="dextro",fig_dir='./fig',PORT = 2121, HOST = "213.206.185.111",h5format=False): def upload(ftp, file): if not os.path.exists(file): print("File '", file, "' doesn't exist") ...
1b084492d53add8970c77429efc403201ea7a50bd9320733b4185f63133c9d9a
Python
1,631
47
# this program gets solven accessibility values. import csv import math import os import sys # extracting the solvent accessibility from the CIF output files. aa_list = ['ALA', 'ARG', 'ASN', 'ASP', 'CYS', 'GLN', 'GLU', 'GLY', 'HIS', 'ILE', 'LEU', 'LYS', 'MET', 'PHE', 'PRO', 'SER', 'THR','TRP', 'TYR', 'VAL'] aaCodes ...
05662cb4fe8eff31e9179741036ce382de267721b8b08304ad684b1aa63c42d5
Python
1,633
69
"""Coordinate-, image-, and effect-size-based meta-analysis estimators.""" import lazy_loader as lazy # Estimators are imported on first access: a coordinate-based run never loads PyMARE # (and through it SymPy) for the image-based estimators, and CBMR's optional torch # dependency is only needed once CBMR is used. _...
d71c0120f395a57f9abcdbf54a40320d99b3c8ae0be0fc275da22f271f57acfa
Python
1,633
62
#!/usr/bin/env python3 import os from itertools import product import numpy as np from etspredict.job_submission import HTCSubmissionTemplate subjects = list( # np.loadtxt(os.path.join("..", "non_na_subjects.txt"), dtype=str) np.loadtxt(os.path.join("..", "remaining.txt"), dtype=str) ) sessions = ["REST1...
37974d7fc3739f42650c9fe630406b9661131b67d8df27c29592417d93545002
Python
1,634
57
from __future__ import annotations import os import subprocess from pathlib import Path import pytest import yaml ROOT = Path(__file__).resolve().parents[3] @pytest.mark.parametrize( ("crate", "workflow_name"), [("datamonger-core", "publish-core.yml"), ("datamonger", "publish-cli.yml")], ) @pytest.mark.par...
4c9370dc76f0ce3e2812b936d5988e24adf9edcc6e11d44b06ee568c5e5a3b19
Python
1,634
64
import os from itertools import product from etspredict.job_submission import HTCSubmissionTemplate def main(): datasets = ["hcp"] sampling_strats = [ "combined_bins" ] # ["individual_bins", "combined_bins", "sequential"] preprocessing_levels = ["GS", "no_GS"] parcellations = ["schaefer...
bad50377bfe4cbd6029d1be85166e3f311c26413b509a2a9c6482350cbf0c8c9
Python
1,636
59
import os import re import sys import tqdm import random import jieba import pickle import joblib import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader from LAC import LA...
bc8d0f209db3fb42170738ad13788970ce5d57f33321fbff404b9ff65b3c5675
Python
1,644
64
"""Extension module declarations for centriole. All package metadata lives in pyproject.toml. This file exists only because setuptools still needs a setup.py to declare C/Cython extension modules. """ import glob import os.path import numpy import setuptools try: import Cython.Build __cython = True except ...
d38f5560ba82de034ccc1a282697bb05d1d8c1feb62cc99791743946d9c34c32
Python
1,647
44
from ..module import Module from ..object import Objects from ..setting.text.alphanumeric.name._label_name import LabelName class InjectObjects(Module): """Inject objects with labels into the pipeline""" module_name = "InjectObjects" variable_revision_number = 1 def __init__( self, o...
f2938347417045a42a36a50a7a575f31feecb67a89062b572ad3dd402e396517
Python
1,647
49
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...
1d85f438b0a9776478ed6e0908f78b68902da8cf7db301697c777490b7b564cc
Python
1,653
45
from unittest import TestCase from numpy.testing import assert_equal from .grid import grid_adj, grid_points, grid_mass, grid_tensor from torch_geometric.transforms import Cartesian class GridTest(TestCase): def test_grid_points(self): points = grid_points((3, 2)) expected = [[0, 0], [0, 1], [1,...
9e6472f975536b825a8b6e5c23ae635c7c4f859c9f6195cca913e2ce950c62e7
Python
1,655
57
import torch import time import numpy as np import atexit cuda_timers = {} timers = {} class CudaTimer: def __init__(self, timer_name=''): self.timer_name = timer_name if self.timer_name not in cuda_timers: cuda_timers[self.timer_name] = [] self.start = torch.cuda.Event(enabl...
aaa1587754dbdb00dbb1c4de438e9bf18aa0283f724bba0ad06ef528f200e3fa
Python
1,656
48
import rvt.default import rvt.vis import rvt.blend_func import numpy as np # Prepare dem_path = r"test_data\TM1_564_146.tif" dem_dict = rvt.default.get_raster_arr(dem_path) dem_arr = dem_dict["array"] dem_res = dem_dict["resolution"][0] dem_nodata = dem_dict["no_data"] default = rvt.default.DefaultValues() default...
9287abc6bdc58c87a11ddab9da57331a303769bf8635ae5fdbebb62332f71d43
Python
1,660
66
import os from itertools import product from etspredict.job_submission import HTCSubmissionTemplate def main(): datasets = ["hcp"] sampling_strats = ["individual_bins"] preprocessing_levels = ["GS"] parcellations = ["schaefer200x17"] correlation_methods = ["pearson"] path_to_venv = "~/.venvs...
c62d73cb3d23c9331663049c4d2ad83bb7fc97bdeb9fc1109dedb629de9890d2
Python
1,661
48
import os import datetime import sys sys.path.insert(0, "./") import torch.distributed as dist from deeprank.models.variant import * from deeprank.generate import * from deeprank.learn import DataSet from deeprank.learn.NeuralNetDDP import NeuralNetDDP from deeprank.learn.model3d import cnn_class def spmd_main(): ...
b01326c4439f104dbedf431fb03202c7e068ecaf797da930f476e7a064f8740d
Python
1,662
43
import unittest import torch import torchdiffeq from problems import construct_problem, DTYPES, DEVICES, ADAPTIVE_METHODS EPS = {torch.float32: 1e-5, torch.float64: 1e-12} class TestCollectionState(unittest.TestCase): def test_forward(self): for dtype in DTYPES: eps = EPS[dtype] ...
53945e145c63cfee54bd0efd0af94142668836e9bdcfcd03498293b1aa4a11be
Python
1,665
56
import numpy import numpy.testing import skimage.morphology import cellprofiler.modules.dilateobjects instance = cellprofiler.modules.dilateobjects.DilateObjects() def test_run(object_with_data, module, object_set_with_data, workspace_with_data): module.x_name.value = "InputObjects" module.y_name.value = "...
a7e160f8d333b069432b046cd2ee053b8da4bf670003b0cd46d4650a8023f15c
Python
1,665
41
"""Regression test documenting a known bug: non-cubic periodicity settings are silently ignored. dragen/utilities/Helpers.py:466 has a self-flagged FIXME ("full periodicity applies for the x != y != z case, which is presumably not 100% reasonable") in make_periodic_3D_new's branch for when both box_size_y and box_size...
682ea87495bd58b84797e1e440d69a8af1401ed73d50b689b644d4f9a784f4ec
Python
1,668
41
from unittest import TestCase from lib.process.evaluation import KEvaluator from .train import Trainer, KTrainer from ..datasets.mnist import MNIST from dvn import FCN, VNET, UNET # import libraries import numpy as np import dvn.losses as ls import dvn.misc as ms dataset = MNIST() trainer = Trainer(model=None,datase...
f3e51c93fe445fc0abee2dae21bcbd9769a54cfd22f8249f2adc2b8fa968600b
Python
1,674
57
""" Example usage: CUDA_VISIBLE_DEVICES=1, python train.py --settings_file "config/settings_DDD17.yaml" """ import argparse import wandb from config.settings import Settings from training.ess_trainer import ESSModel from training.ess_supervised_trainer import ESSSupervisedModel import numpy as np import torch import ...
6c403fb177cf02d4241250618ff3ab91929669ee7058e971e6fbd86010da808b
Python
1,677
53
import numpy as np from functions.def_ROIs_WangParcels import roi def add_fovea(list, hemisphere = 'L'): """ Adds fovea to V1, V2 and V3 parcels (Wang et at., 2015) and group dorsal and ventral components. Parameters ---------- list : list List of the parcels. Returns ------- l...
9fe554509e82cf0bfc2c8b42b962d5ca7e6bb43f7704a8b2f859a93858fbe88a
Python
1,678
48
import os import pandas as pd import numpy as np import math from scipy.sparse import csr_matrix, find import matplotlib.pyplot as plt import time from scipy.stats import norm from joblib import Parallel, delayed import time, math # simple example of using one cell type from Chu et al. dataset data = pd.read_csv('lo...
eb9e41159a34f92069bd6adf8ff0ad80ced259ad5083c105ca5111b4766cddae
Python
1,679
45
import prov.model as pm from .AcquisitionObject import AcquisitionObject from ..core import Constants class DemographicsObject(AcquisitionObject): """Class for NIDM-Experimenent MRAcquisitionObject-Level Objects. Default constructor uses empty graph with namespaces added from NIDM/Scripts/Constants.py. A...
6868d38450d9045e4a3adcc046ee3085de081bf5de277d4d7235e2d177f21d2c
Python
1,681
66
import os from itertools import product from etspredict.job_submission import HTCSubmissionTemplate def main(): datasets = ["hcp"] sampling_strats = ["individual_bins"] preprocessing_levels = ["GS"] parcellations = ["schaefer200x17"] correlation_methods = ["pearson"] path_to_venv = "~/.venvs...
b142937a29d7c6784bea74d6bb0c68a77c517eb1c0588f493e3be93d8b5396e6
Python
1,681
50
# 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...
de1aa7d40d98e0b4df830cce052773a1e06fae2c2b42780e9357892399d367a8
Python
1,683
38
""" @author: Johanna Rahm Research group Heilemann Institute for Physical and Theoretical Chemistry, Goethe University Frankfurt a.M. """ import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup(name="ImageSumming", version="221116", au...
25fef05bb2bbd754edd2bf715f845176ef06c636e23839bae8d8f3676dd37bc3
Python
1,685
66
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np import TDBG import os import re # get the name of the folder cwd2 = os.path.split(os.getcwd())[1] print(str(re.findall("\d+", cwd2))) cwd2int = int("".join(filter(str.isdigit, cwd2))) npzfile = f"temptestnorm{cwd2int}.npz" print(npzfile) # f ----------...
2f55625b9e44cae5baae81117ae033a988fab36b006a2b7a94a00142449ea086
Python
1,685
54
""" pysteps.downscaling.interface ============================= Interface for the downscaling module. It returns a callable function for computing downscaling. .. autosummary:: :toctree: ../generated/ get_method """ from pysteps.downscaling import rainfarm _downscale_methods = dict() _downscale_methods["ra...
fec5044164a97bf8399d79c6b3e2d103d28f2b4ce0c8eb57e0f8e0ed48c08838
Python
1,685
42
import random import numpy as np class Evaluation(object): """Public evaluation methods""" def __init__(self): super(Evaluation, self).__init__() self.loss_arr = [] self.precision_arr = [] self.recall_arr = [] self.accuracy_arr = [] @staticmethod def _get_metr...
c92f85ee794f5af900bb07f6be2ea4a06ba7be01ada6491edd806c6a3667eff7
Python
1,686
50
import numpy as np from math import fabs def robust_min(img, p=5): return np.percentile(img.ravel(), p) def robust_max(img, p=95): return np.percentile(img.ravel(), p) def normalize(img, m=10, M=90): return np.clip((img - robust_min(img, m)) / (robust_max(img, M) - robust_min(img, m)), 0.0, 1.0) def...
08d046557ba01b8768aa6b1175ad47f7e8417c9c7f4548ac734bacb8ab172b11
Python
1,690
74
from math import sqrt def get_tp_tn_fp_fn(output_data, target_data): """ A classification metric Args: output_data(array of dimension (x,2)): considered negative if left value > right value target_data(array of dimension (x,1)): considered negative if 0, positive otherewise Returns (four...
c40fc9f5f78f5efc0732e65543760a018fa2fa9cb3c10057d03e5125c11cf618
Python
1,690
67
config = { 'alpha_di':0.000451125353657906, 'alpha_di_fb':0.611510021981854, 'apical_time_constant_fb':0.4318893018524684, 'adam_beta1':0.99, 'adam_beta2':0.999, 'dt_di_fb':0.004294669581123954, 'adam_epsilon':3.210886729268312e-07, 'adam_epsilon_fb':1.0433715362737473e-08, 'weight_decay_fb':0.001, 'k_p_fb':0.010409666...
649951539a6f378b1d44062fd50e92c173c0d2186f62ad8703c49626194b152c
Python
1,692
58
from ._setting import Setting class DoThings(Setting): """Do one of several things, depending on which button is pressed This setting consolidates several possible actions into one setting. Graphically, it displays as several buttons that are horizontally adjacent. """ save_to_pipeline = Fal...
e9203914e42d35fd4b7ae29253bf3962da96c1ff184fde0b77071cbb1589f8e5
Python
1,696
42
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for charge.py""" from __future__ import print_function from __future__ import unicode_literals from __future__ import division from molvs.validate import validate_smiles def test_none(): """IsNoneValidation should log due to SMILES parse error.""" asser...
e31978936018cbd9470d5099f72bf3b2fd1f354a53a4a30aa40303d6992bd763
Python
1,697
52
import torch from math import exp import torch.nn.functional as F def gaussian(window_size, sigma): gauss = torch.Tensor([exp(-(x - window_size//2)**2/float(2*sigma**2)) for x in range(window_size)]) return gauss/gauss.sum() def create_window(window_size, channel=1): _1D_window = gaussian(window_size, 1.5...
6b9224233cd8c4e9713836af74073901ba2a6b051e9560c332c3b67cefc14956
Python
1,700
52
from typing import Sequence from typing import Tuple import torch import torch.nn as nn from ..models.base import Model from ..models.featurenn import FeatureNN class NAM(Model): def __init__( self, config, name, *, num_inputs: int, num_units, num_outputs...
c3992edc22af074901838780062684538e125b9029b16abd82000ddb40f0f1f9
Python
1,700
47
import json import os import shutil from imskaper.experiment.experiment import experiment, read_Xy_data from imskaper.utils.classifiers import get_classifiers from imskaper.utils.features_selectors import get_features_selectors current_path = "tests" # os.path.dirname(os.path.abspath(__file__)) json_path = os.path.jo...
ceb7aaa580e15a5c2c8773338ca0a32eb013974f461007ab41a7248e344521c1
Python
1,700
48
"""If input folder to the MLCube does not contain a csv file that defines the data cases, a custom entrypoint is needed to create a temporary csv file before calling GaNDLF's run command. This script should expect the same arguments passed to the command `mlcube run --task infer`, i.e. it should expect the inputs and o...
d1b7c81f0afcca0379381b1459b7d2ffa00d9c4635444c9210475e1beb267672
Python
1,700
69
# Copyright (C) 2025 Severin Strobl <git@severin-strobl.de> # # SPDX-License-Identifier: MIT # # Exact calculation of the overlap volume of spheres and mesh elements. # http://dx.doi.org/10.1016/j.jcp.2016.02.003 import numpy as np import overlap import pyperf UNIT_HEX = overlap.Hexahedron( np.array( ( ...
b7db1775dd392b74223d67a6bb2f20976c0f28d73581234526c84ea99fc2516a
Python
1,702
68
config = { 'lr':0.0010924329072635147, 'alpha_di':0.0017723664900917734, 'k_p_fb':0.0713515876863314, 'alpha_di_fb':0.39857902933813705, 'weight_decay_fb':0.1, 'time_constant_ratio_fb':0.005870467170683501, 'dt_di_fb':0.0011421804343878519, 'apical_time_constant_fb':0.1404664564483908, 'lr_fb_init':0.000152412153530638...
1ebb992ad623f671b5c84e562b98fea3e72b115dc0aa8be5b20668d8f2edcc40
Python
1,705
53
import time class Timer(): def __init__(self, time_threshold): self.start = time.time() self.time_threshold = time_threshold def is_time(self): current_time = time.time() time_diff = current_time-self.start if time_diff>self.time_threshold: print("time elaps...
e4ba7a3a811163da50804ddae400199a0c1b0cedca5230b48c46342bedeffd6c
Python
1,705
44
import os import torch.distributed as dist import pickle import numpy as np from PIL import Image from .base_dataset import BaseDataset from utils.parallel import get_dist_info from .utils import download_and_extract_archive, check_integrity class ImageNet(BaseDataset): """Since there is prepared dataset class in ...
7684daf635f518500bb65167573788e2db446952dd6d31d56ea6683dd684919d
Python
1,710
66
import numpy import skimage.morphology import cellprofiler_core.image import cellprofiler.modules.removeholes import cellprofiler_core.workspace instance = cellprofiler.modules.removeholes.RemoveHoles() def test_run(image, module, workspace): module.x_name.value = "example" module.y_name.value = "output" ...
7205b873c0954654a536a919a226447d3135b06e11c8c3e699b00b21b95519b5
Python
1,713
54
#!/usr/bin/env python from __future__ import print_function from collections import OrderedDict import re # TODO nf-core: Add additional regexes for new tools in process get_software_versions regexes = { "nf-core/circrnasponging": ["v_pipeline.txt", r"(\S+)"], "Nextflow": ["v_nextflow.txt", r"(\S+)"], "Fas...
7926d51ccac69a2c2819a11d42cccb933778f62d65e2a619fef73c666072f37a
Python
1,713
55
from __future__ import annotations import datetime as dt import numpy as np import pytest from sentinelhub import CRS, BBox from s2cloudless.utils import download_bands_and_valid_data_mask BBOX1 = BBox((-90.9216499, 14.4190528, -90.8186531, 14.5520163), crs=CRS.WGS84) BBOX2 = BBox(((620000, 8210000), (660000, 8270...
927d980bdfe4173202ab312acecaf4954742dfd59b339b8d03cfe6a04e1233e3
Python
1,714
60
import wx import wx.adv from cellprofiler import __version__ as cellprofiler_version from cellprofiler.gui.utilities.icon import get_cp_icon class AboutDialogInfo(wx.adv.AboutDialogInfo): def __init__(self): super(AboutDialogInfo, self).__init__() self.SetCopyright( "Copyright © 2003...
0742d1545d4ec996208bf5d87d54bb2b7306d0b4c33b14339abc0f903b810666
Python
1,715
62
import torch import torch.nn as nn class MLP(nn.Module): def __init__(self, out_dim=10, in_channel=1, img_sz=28, hidden_dim=256, activation_override=None): super(MLP, self).__init__() self.in_dim = in_channel*img_sz*img_sz self.activation_override = activation_override self.linear...
f54cf43f9ed9fb4ed92b9372eb0949385296b60fceb1c25fbf859a88a616da46
Python
1,715
49
import os import csv import torch import torch.nn as nn from imageio import imsave # load image metadata (Image_ID, true label, and target label) def load_ground_truth(csv_filename): image_id_list = [] label_ori_list = [] label_tar_list = [] with open(csv_filename) as csvfile: reader = csv.Di...
0ff6ba79ab3d27d4056141f00f8dfadbd833f67a82968cd0862951c52b7f5e38
Python
1,717
54
from .util import prepare_for_display, window_manager, GuiLockError try: # we try to acquire the gui lock first # or else the gui import might trample another # gui's pyos_inputhook. window_manager.acquire('gtk') except GuiLockError as gle: print(gle) else: try: import gtk except Im...
2c988b4be260b351f487a7a59168bbe747217fb8d538ce87e22757842544b0e4
Python
1,718
58
import inspect from typing import Dict, Tuple, Union import torch.nn as nn NORM_LAYERS = { 'BN':nn.BatchNorm2d, 'GN':nn.GroupNorm, 'IN':nn.InstanceNorm2d, 'LN':nn.LayerNorm, } def build_norm_layer(cfg: Dict, num_features: int) -> Tuple[str, nn.Module]: """Build normalizatio...
354f98bb58d9c48c1fa2fbfa640f224ed1baddc6d8b38d37852033e5d7353995
Python
1,718
42
# -*- 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...
8e4eabb9356fef792e1794c47b07d16d4e59d8467c7aee82954656ed63d8f1ef
Python
1,719
49
""" Median Pool Hacked together by / Copyright 2020 Ross Wightman """ import torch.nn as nn import torch.nn.functional as F from .helpers import to_2tuple, to_4tuple class MedianPool2d(nn.Module): """ Median pool (usable as median filter when stride=1) module. Args: kernel_size: size of pooling kern...
ef6ca0cbdb3720db7634501f496e23f5dc719aebaf7f37c14c5d07c21d276015
Python
1,720
49
from typing import Union import os import pandas as pd from GANDLF.utils import get_dataframe, split_data def split_data_and_save_csvs( input_data: Union[pd.DataFrame, str], output_dir: str, parameters: dict ) -> None: """ Split the data into training, validation, and testing sets and save them as csvs i...
17be10210e9d64bf1c388b19914f957c375c1dec145bde7d19746f0dfa611829
Python
1,725
73
import os # hides torchio citation request, see https://github.com/fepegar/torchio/issues/235 os.environ["TORCHIO_HIDE_CITATION_PROMPT"] = "1" from .imaging import ( resize_image, resample_image, perform_sanity_check_on_subject, sanity_check_on_file_readers, write_training_patches, get_correct...
a4dba0063a7c342bd058a54a5e4c4172831c25f7175cd2e9facbf0578f736918
Python
1,725
61
from sklearn import svm import pickle import numpy as np from sklearn.metrics import confusion_matrix # import matplotlib.pyplot as plt # from scipy import stats ### PARAMETERS # SVM kernel (RBF or Polynomial) # kern_func = 'rbf' kern_func = 'poly' # Polynomial degree for 'poly' kernel (ingored fo...
ffec44cc70c00f740deb6c06993b71e29aa1f1458482da29150c746b5d9485ac
Python
1,726
39
# Inheritaed from open-mmlab/mmclassification # Modified by Hangyu LIN from .misc import (check_prerequisites, concat_list, deprecated_api_warning, has_method, import_modules_from_strings, is_list_of, is_method_overridden, is_seq_of, is_str, is_tuple_of, iter_ca...
8dd949f0f66f4d07c1c1e113be10ce5547bc038a9887c88e92c5b2dfcd61732b
Python
1,728
61
import numpy as np import matplotlib.pyplot as plt # Define parameters dt = 0.5 # time step t = np.arange(0, 1000, dt) # time vector V0 = -90 # initial potential Vr = -90 # reset potential theta = -60 # threshold potential tau = 10 # membrane time constant g = 1.5 # input conductance tau_s = 5 # synaptic time ...
77484a446ca075b7dbb64f907a9e6f37b0b61b0e9e8097c75f1e75e41eb3a557
Python
1,730
48
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Mon Apr 16 16:11:33 2018 @author: saskiad """ import pandas as pd import numpy as np import h5py import os from allensdk.core.brain_observatory_cache import BrainObservatoryCache import core def get_evoked_responses(): save_path = core.get_save_path(...
13e5a447a1b2c63226582881ac0eb68b7992ece02da803bb633ba9654163ca32
Python
1,731
40
# Author: Mingjian He <mh1@stanford.edu> from somata.oscillator_search import DecomposedOscillatorModel as DecOsc from somata import OscillatorModel as Osc import numpy as np # Simulate 10-s data with two oscillators, one slow and one alpha frequency np.random.seed(1) # to ensure reproducible results o1 = Osc(a=[0.99...
492c00265ee74e3241fc0361a033e07c56be7bcf1de64f7583ce5e4bca9137a0
Python
1,731
57
# Inheritaed from open-mmlab/mmclassification # Modified by Hangyu LIN def wrap_non_distributed_model(model, device='cuda', dim=0, *args, **kwargs): """Wrap module in non-distributed environment by device type. - For CUDA, wrap as to.device. - For CPU not wrap the model. Args: model(:cla...
70a3de3640c4ffc00b97f0c9cfdcff8b0584b85613e77fb163cd772743893d40
Python
1,732
25
from pyControl.hardware import Port from devices._MCP import MCP23017 class Port_expander(): # IO expander board which runs 8 behaviour ports from an MCP23017 i2c port expander. def __init__(self, port): assert port.I2C, 'Port expander must be connected to port that supports I2C.' self.m...
317cd88b7c11060ae01472dd7286b884b822e5829f4085b73f43288df2eefe7f
Python
1,733
46
class ActivationsAndGradients: """ Class for extracting activations and registering gradients from targetted intermediate layers """ def __init__(self, model, target_layers, reshape_transform): self.model = model self.gradients = [] self.activations = [] self.reshape_transfo...
85a25b8796f3085d9ee8731d24758a0cc2f0d06a43d3bae0d743f00bf5eeedb3
Python
1,733
57
import random import numpy as np from numpy import pi as PI def augment_batch(batch): batch_augmented = [] for example in batch: features, adjs_dist, adjs_rad, label = example features = random_brightness(features, 0, 3, max_delta=0.3) features = random_contrast(features, 0, 3, max_de...
b411ad0c074f1f816a503fbc0af058b4a105ea128dee29c5cf8bd4a5814adcb7
Python
1,736
55
from __future__ import annotations import importlib.util from pathlib import Path from typing import Any TOOLS = Path(__file__).resolve().parents[3] / "tools" SPEC = importlib.util.spec_from_file_location( "dm_ffi_licenses", TOOLS / "dm_ffi_licenses.py" ) assert SPEC is not None and SPEC.loader is not None dm_ffi...
7ef04cbfc42794991aef04f54af10b78abf9ac6b98b1aab22565b0b7978bcf81
Python
1,738
67
import random import dgl import torch from attentionmil import AttentionMIL from lamil import LAMIL from perceiver import Perceiver from transformer import Transformer from transmil import TransMIL def test_attentionmil(): attentionmil = AttentionMIL(num_classes=2, num_features=1024) input = torch.rand(1, 1...
516a6a6e8c305386094eb0648ea165efa33a9b70811e7107cd84a9f24fe2d645
Python
1,739
64
import json import os import pickle from typing import Any, Dict, Tuple import numpy as np import xgboost as xgb kRows = 100 kCols = 10 def generate_data() -> Tuple[np.ndarray, np.ndarray]: X = np.random.randn(kRows, kCols) y = np.random.randn(kRows) return X, y class TestPickling: def run_model_...
35f7e7b9412506c62e819b0ee2c2a89912ea791a75ab1fbe3696347faeeddbe3
Python
1,741
56
"""Add knowledge_chunks table for RAG vector store Revision ID: c4e7f1a9b2d8 Revises: 56d89145adbb Create Date: 2026-04-01 00:00:00.000000 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = "c4e7f1a9b2d8" down_revision = "56d89145adbb" branch_labels = None depends...
fbe13252ec3573bffb103cc395a157d08c216dce20b431ceb498e73fa2b31e8e
Python
1,741
41
"""Predictors based on gammatone spectrograms""" from pathlib import Path import os import numpy as np from eelbrain import * from trftools.neural import edge_detector language = 'French' DATA_ROOT = Path(os.path.dirname(os.path.abspath(__file__))).expanduser() STIMULUS_DIR = DATA_ROOT / 'stimuli' / language PREDICTO...
cf3c520a769eeb64ce3036bb348d3c03d9fac48840064d99facbe4028cb57ba5
Python
1,745
62
import os import shutil import numpy as np import pandas as pd from etspredict import selective_connectomes as sc from etspredict import timeseries as gts from etspredict.pipelines.base import Pipeline def test_pipeline(): # pretend to load subject specific data subject = "151425" run = "REST1LR" t...
1d29f082cef2069393986961412d9eb3d05ea6c736752a9b560aa8e523d20c04
Python
1,748
53
import torch.nn as nn from GANDLF.models.seg_modules.Interpolate import Interpolate class FCNUpsamplingModule(nn.Module): def __init__( self, input_channels, output_channels, conv=nn.Conv2d, conv_kwargs=None, scale_factor=2, interpolation_mode="trilinear", ...
855e8e76765608edac655659c928cf858f6c4ea174019ae8172e29f67064606b
Python
1,748
52
import torch.nn as nn from GANDLF.models.seg_modules.Interpolate import Interpolate class UpsamplingModule(nn.Module): def __init__( self, input_channels, output_channels, conv=nn.Conv2d, conv_kwargs=None, scale_factor=2, interpolation_mode="trilinear", ...
9b8879d72a2bc2e10a731704558629b3651632acd933dbf0f8d9400ceeb886db
Python
1,748
69
import hashlib from os import environ, path import pickle import tempfile from rdflib import Graph from nidm.core import Constants import nidm.experiment.Query from nidm.util import urlretrieve def download_cde_files(): cde_dir = tempfile.gettempdir() for url in Constants.CDE_FILE_LOCATIONS: urlretri...
26bfa0d3caec1604f572e77b852ac21ae6f287aa89120efb045b90450cee8c66
Python
1,749
60
from __future__ import division from six.moves import xrange import numpy as np # import numpy_groupies as npg import scipy.sparse as sp def normalized_cut(adj, rid=None): """Perform NormalizedCut on a given adjacency matrix. Return a cluster map indicating the resulting pairwise cluster.""" if rid is ...
f853bbdf046c21f3df5c252422bd2d1965296f8e72d3aa65a64e1429fa854afc
Python
1,750
61
import cv2 import numpy as np import pandas as pd import os from matplotlib import pyplot as plt def detect_mouse(frame): gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) blurred = cv2.GaussianBlur(gray, (35, 35), 0) _, thresh = cv2.threshold(blurred, 30, 255, cv2.THRESH_BINARY_INV) contours, _ = cv2.fi...
d2490d40c836498d3421f69c466b04e4f4aeee0f07f646b9419223650048b2b2
Python
1,754
60
import numpy import numpy.testing import skimage.morphology import cellprofiler.modules.erodeobjects instance = cellprofiler.modules.erodeobjects.ErodeObjects() def test_run(object_with_data, module, object_set_with_data, workspace_with_data): module.x_name.value = "InputObjects" module.y_name.value = "Out...
f7cf216735e2e38f6c4901f4b0855ce952f19a77fd6ae20ae80aa0bc4bf2ad13
Python
1,755
48
import torch from torchio.data.subject import Subject from torchio.transforms.preprocessing.intensity.normalization_transform import ( NormalizationTransform, TypeMaskingMethod, ) # adapted from https://github.com/fepegar/torchio/blob/master/torchio/transforms/preprocessing/intensity/z_normalization.py class...
f94975034b58b8b8b10f4c65095f033843d4f041019342ec71415a779fe4f839
Python
1,755
62
import numpy as np import matplotlib.pyplot as plt # Define parameters dt = 0.1 # time step t = np.arange(0, 1000, dt) # time vector V0 = -90 # initial potential Vr = -90 # reset potential theta = -60 # threshold potential tau = 20 # membrane time constant a = 0.02 # recovery variable time scale b = 0.2 # sens...
49ed228f7788e7334ad2c4428e0457dcbffb87194e51eed493d6685af2cf8462
Python
1,756
64
# -*- coding: utf-8 -*- import pytest import pysteps from pysteps.tests.helpers import smart_assert, get_precipitation_fields pytest.importorskip("h5py") # Test for RADOLAN RY product precip_ry, metadata_ry = get_precipitation_fields( num_prev_files=0, num_next_files=0, return_raw=False, metadata=T...
a15dbd522329fffb6c48f1b5ef4d894b2df6185d5fe2d59a10f5922b4837d912
Python
1,759
58
import pandas as pd import splitter as sp import os from sklearn.model_selection import KFold import numpy as np def make_dir(file_name): ouput_path = file_name + '/' try: os.mkdir(ouput_path) except OSError as error: print(error) return ouput_path k_folds = 10 skf = KFold(n_spli...
59ff4cece7fe5b63ba2cab9787f1d4443da5dec2c14baca91ff1830cd1248ed0
Python
1,761
67
#!/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/de' key='celltype' values=['dysfunctional','naive'] #Load covariate info dc=np.loadtxt(pj...
29cc3746d0783b06f0b600e40f72f39ccd85d6404072855ea8273f71951d7da3
Python
1,763
67
#!/usr/bin/env python import os import h5py def clean_dataset(fname, feature=True, pdb=True, points=True, grid=False): # name of the hdf5 file f5 = h5py.File(fname, 'a') # get the folder names mol_names = f5.keys() for name in mol_names: mol_grp = f5[name] if feature and 'fea...
0794161a463b3358ef9a50ef8566b60e8ab6d201f2282e3e7abfcf646247e31d
Python
1,765
52
#!/usr/bin/env python # -*- coding: utf-8 -*- import textgrid as tg import pandas as pd def textGrid_to_dataFrame(tgfile, tier='words'): """ Simply return a dataframe with the tier mark label aligned with time onset and offset. Parameters ---------- tgfile : str Path to TextG...
2f26203796ce005e4aea568658285efc2062d364663e1212ee76298a88ce0b4c
Python
1,768
34
from GANDLF.entrypoints.anonymizer import new_way as anonymizer_command from GANDLF.entrypoints.run import new_way as run_command from GANDLF.entrypoints.construct_csv import new_way as construct_csv_command from GANDLF.entrypoints.collect_stats import new_way as collect_stats_command from GANDLF.entrypoints.patch_...
1e539125aff6ddeac408c62d3437c68a0037e419d09746768a6ae48fecdffe55
Python
1,772
75
""" Helper functions for (pre-)processing Authored by Eric Easthope """ import numpy as np # Get N logarithmically-scaled frequency bands def log_scale_bands(low, high, N): return np.around( np.array( list( zip( np.geomspace(low, high, N + 1).tolist(), ...
93f8ef3a62413789a4864d6e888008615e7c48ebbcdd544b2db92eb1decee1f4
Python
1,780
56
import os import sys from contextlib import contextmanager try: import ctypes from ctypes.util import find_library except ImportError: libc = None else: try: libc = ctypes.cdll.msvcrt # Windows except OSError: libc = ctypes.cdll.LoadLibrary(find_library('c')) def f...
d03fc089aae1b70ea5ddbb156c7e893b4ace69473e221b424d9347271f56624b
Python
1,781
52
#!/usr/bin/env python # -*- coding: utf-8 -*- import textgrid as tg import pandas as pd def textGrid_to_dataFrame(tgfile, tier='phones'): """ Simply return a dataframe with the tier mark label aligned with time onset and offset. Parameters ---------- tgfile : str Path to Text...
0ecec61028dae1641df8ce9b760faf1e72526c542f043f5882d68be9139ff586
Python
1,783
53
# -*- coding: utf-8 -*- """ Created on Mon Sep 5 12:19:11 2022 @author: Manuel """ originals_path = "G:/Masterarbeit/MonitRaw" predictions_path = "G:/Masterarbeit/PredRaw" output_path = "G:/Masterarbeit/PredJPG" MAX_CLASS_VAL = 16 import os, glob from PIL import Image from exif import Image as exIm imp...
15e9e73d07e644e258b5fdf13ddcd639ce72743a238e900f3c5c3a64dbd3bc22
Python
1,785
56
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for resonance.py""" from __future__ import print_function from __future__ import unicode_literals from __future__ import division import logging from rdkit import Chem from molvs.resonance import ResonanceEnumerator, enumerate_resonance_smiles logging.basicCon...
3060bc342aeab2a2d904454125e69c7575e7f4f6e5a16d9a6cb02817e8d5adf3
Python
1,785
45
import os import re # TODO: eventually switch to tomllib, introduced in python 3.11 import toml def split_package(package): """ given a string containing a package and its version specifier: "package-a>=3,<5" splits the string into 2-tuple of (package, version_specifier) ("package-a", ">=3,<5") ...
9ed2e68554f9d4bbfb599a13c898feace4dbfb945091c7177eeff9e1509f16dd
Python
1,785
63
import os from pathlib import Path import numpy as np import pandas as pd import pkg_resources class HCPAgingTimeseries: def __init__(self): self.timeseries = None def available_subjects(self, unrelated=True): parent = Path(__file__).parent.resolve() path = os.path.join("timeseries")...
f3a9a7e093ae70b6e0e9588c56380b21fce251cb8efeaad14b69be17c56b6f8c
Python
1,785
53
import logging import torch.nn as nn logger = logging.getLogger(__name__) def _initialize_layers(activation, initialization, layers): if type(layers) == nn.Sequential: for layer in layers: if hasattr(layer, "weight"): _initialize_layers(activation, initialization, layer) ...
9037c8a4e80c04b50bd6cc6475ec6c20176f6a535c3e0afbbbc7ef9f8a5de3db
Python
1,794
66
import os from itertools import product from etspredict.job_submission import HTCSubmissionTemplate def main(): datasets = ["hcp", "hcp_aging"] sampling_strats = ["individual_bins", "combined_bins", "sequential"] preprocessing_levels = ["GS", "no_GS"] parcellations = ["schaefer200x17", "schaefer300x...