sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
0831de1ebad00b4a09c9d15cd60cdd21d3170b19e2f4d9c17141b1ddbcf30604
Python
3,280
111
''' Keras implementation of B networks ''' import tensorflow as tf def b_layer(x, filters, kernel, layer_num, pooling=True): '''Base layer for B models ''' if pooling: x = tf.keras.layers.MaxPool2D( pool_size=(2, 2), name='MaxPool_Layer_{}'.format(layer_num))(x) x = t...
105485824e45517d56cc114a93e01a6389be97007f99bca5357fcc5f52be7753
Python
3,281
75
""" Library of single-neurons configurations. Write here the single cell parameters. If you need another type of cell just add an "elif" case """ from __future__ import print_function #NB: Trefrac = 2ms (from Marrasco et al) # Ie = Ith!!! # A2 = Iadap update and A1 = Idep update. FOR THE MOMENT SAME VALUE AS...
99712e8fb4dc138e333aabd0e59851242cc79c7e226d76924c355d9b0b97be96
Python
3,281
83
import torch import torch.nn as nn import numpy as np import torch.optim as optim import itertools from model.warplayer import warp from torch.nn.parallel import DistributedDataParallel as DDP import torch.nn.functional as F device = torch.device("cuda" if torch.cuda.is_available() else "cpu") def conv(in_planes, out...
19e2e6d81088754e41feebc62630fec24502ca359653c47452a07f7dfd7921f7
Python
3,282
138
import os import sys import time import errno import time import timeit import numpy as np from numba import jit import warnings warnings.simplefilter("ignore") @jit(nopython=False) def VEP2Dmodel(params, constants, init_conditions, SC, dt, ts): nt=ts.shape[0] nn=SC.shape[0] #parameters eta=pa...
973b8280a82cafbd2a012d9d3ddb90291477aacdb179c91f9579761e364f89d9
Python
3,282
95
import logging import nltk import copy from nltk.tokenize import word_tokenize from nltk import word_tokenize, pos_tag, ParentedTree from agent.data.entities.config import ROOT_LOGGER_ID logger = logging.getLogger(ROOT_LOGGER_ID) NN_NN_RULE = r"NP: {<NN.?>+<NN.?>}" JJ_NN_RULE = r"NP: {<JJ>+<NN>}" DT_JJ_NN_RULE = r"...
33d671eb00f78f564682f33b75960ca0502e00342b33b7d676407efb78d1da9e
Python
3,283
72
import os import nibabel as nib import numpy as np import ivim import pandas as pd import time output_root = '/path/to/results' subs = [sub for sub in os.listdir(output_root) if sub.startswith('sub')] pars = ['D','f','vd'] times = {} for method in ['seg','nlls','bayesu','bayess']: times[method] = [] for sub in s...
5f00147c23b185dfe9ec226802d3452cf77433d06c6168c7ca9b0970539310d0
Python
3,283
147
from dataclasses import dataclass from typing import Any, List ################# @dataclass class divideopt: divide_type: str zslice: str param_alloc: str param_size_thres: float exception: dict module_7z: bool @dataclass class sampleropt: name: str cube_count: int cube_len: List[int...
57a9496fa9e303ec451d5b102021392f8c96c3308489edbd24d86e61cc318dc6
Python
3,285
99
import collections import pickle from typing import Optional from pfrl.collections.random_access_queue import RandomAccessQueue from pfrl.replay_buffer import AbstractEpisodicReplayBuffer, random_subseq class EpisodicReplayBuffer(AbstractEpisodicReplayBuffer): # Implements AbstractReplayBuffer.capacity capa...
74168d132b96f46727b6d6350e345a67d15237ababca5dfe1ec00de2126da1d4
Python
3,286
75
import os import time from subprocess import call import numpy as np import pandas as pd import seaborn as sns from scipy import stats import seaborn as sns import matplotlib.pyplot as plt import scipy as sc from matplotlib.colors import ListedColormap import scipy.sparse as sparse import importlib import copy import ...
25b4c89d8f929bcb667e2753674baf5fb53e28aed3e069778eb13075c5083930
Python
3,287
88
import torch import torch.nn as nn from random import sample from torch.nn.modules.linear import Linear import torchvision.models as models import math import torch.nn.functional as F from torch.nn.parameter import Parameter # encoder class MLPEncoder(nn.Module): def __init__(self, num_genes=10000, num_hiddens=12...
728ed3df55f3457a2d88c17b191fe82cf6b9ca50c83fbd0933c13baf259394c6
Python
3,288
101
""" const.py Helpful constants for working with IGS data, and methods to retrieve them. """ import numpy as np import matplotlib.colors as pltcolors """ Define constants (e.g. chromosome sizes, colormaps). """ SIZES_HG38 = np.array([0, 249250621, 243199373, 198022430, 191154276, 180915260, 171115067, ...
aa399686452c2b21f4e6b21b5877c4b6528a72a3458424e8dba9dc10b5731314
Python
3,289
91
r"""FlowSOM for cytometry — ``ov.flow.flowsom``. The same algorithm ``ov.single.ev.flowsom`` runs, on the same code (:mod:`omicverse.flow._som`), writing into ``uns['flow']`` instead of ``uns['ev']`` and defaulting to the layer a cytometry workflow actually produces. Automated clustering is a complement to gating, no...
b15b61e430d94c2af6d70e7beb10f9e0ad7b26decc6ec56e91060d4212229dbf
Python
3,289
89
# coding=utf-8 ''' Created on May 5, 2016 @author: jivan ''' import cPickle import itertools import re import requests from web_utilities import HTMLTableStripper def get_valid_hla_class_i_allele_names(): resp = requests.request('GET', 'http://hla.alleles.org/alleles/class1.html') ts = HTMLTableStripper() ...
511794883f823dc14d9accff12b6f54730fe384b2810fcae106c47f6a00d0516
Python
3,290
85
#################################################################################################### # Copyright (c) 2016 - 2024, EPFL / Blue Brain Project # Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch> # # This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis> # # This program is fre...
8b3c2d99908535a11ae5e9538d87d7c1691b22c46aa3768ba32f59720ec6f178
Python
3,291
94
import torch.nn as nn import torch class ConvBlock(nn.Module): def __init__(self, in_channels, out_channels) -> None: super().__init__() self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding='same') self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=...
0aa732ac8ef630bf74b516ec32356131c44827d91cadc1676d77bc5a89f325f2
Python
3,292
116
# -*- coding: utf-8 -*- # (C) Copyright 2026 IBM. All Rights Reserved. # # Licensed under the MIT license. See LICENSE file in the project root for details. """aihwkit example 13: Custom experiment training (3 fully connected layers). Example of customization of a Basic Training experiment, adding the use of a sched...
0be6222ed97edb08a1590189c2cfe77b495f191bc0c51f6bf4f7c75b46e5ec56
Python
3,292
25
from unittest import TestCase from web_utilities.HTMLTableStripper import HTMLTableStripper, HTMLParseError class HTMLTableStripperTests(TestCase): def basic_tests(self): html_results = ''' <tr class="odd"><td>HLA-DRB1*01:01</td><td>1</td><td>2</td><td>16</td><td class="sequence">IIGKKDKDGEGAPP...
6d5541ec952d783d226e63b242374cd4f26b1c48311788cb8ecb2e83a0061e10
Python
3,293
111
import pdb import numpy as np import torch from data_assimilation.oracle import ObjectStorageClientWrapper from data_assimilation.particle_filter.base import BaseForwardModel from latent_time_stepping.utils import ( load_trained_AE_model, load_trained_time_stepping_model ) class NNForwardModel(BaseForwar...
e71b5ea2790e37157586a2358687810df081e50fdf22acfd33a06fca179fa981
Python
3,293
111
""" """ import re from urllib.request import urlopen def show_method_list(): print( """ * All available method names: ----------------------------- 1) Chou-Fasman 2) Emini 3) Karplus-Schulz 4) Kolaskar-Tongaonkar 5) Parker 6) Bepipred-1.0 7) BepiPred-2.0 """) def show_detail_help(): print( """ detail help...
0b801524bc7a5a01fd08eaa6625f68fc8426f7fd8701aaa590a58beb5549e252
Python
3,294
106
"""Plotting for single-extracellular-vesicle (single-EV) proteomics. Only the EV-specific plot lives here: * :func:`misev_marker_plot` — MISEV2023 positive vs contaminant marker levels (the EV-preparation purity view). Generic single-cell plots — embedding scatters, marker dotplots, mean-signal heatmaps and stacke...
3919041ae1ee7160aa0773f521af1726c3eda4302e8024d2a3b070af7c55a731
Python
3,295
102
from typing import Tuple import torch from torch import nn class Img2SpikeLayer(nn.Module): """Layer to convert images to spikes. Args: image_shape: tuple image shape. tw: int Time window length. max_rate: maximum firing rate of neurons. layer_name: string layer name. ...
e5dfddef330cf2f83c0ac2936757e65bc7c63f06cdb0e062d66f19a47b151f60
Python
3,296
88
import tensorflow as tf from models.deep_learning.deep_learning_models import DLRegressor from utils.constants import is_spline class FCNRegressor(DLRegressor): """ This is a class implementing the FCN model for time series regression. The code is adapted from https://github.com/hfawaz/dl-4-tsc designed f...
6ca1bd67c2ee8af4c3f5742970b37ce91bdda3e45984c70fb7eb2d1b72d60dd2
Python
3,297
108
#!/usr/bin/env python3 import torch.nn as nn import torch import torch.nn.functional as F class Decoder(nn.Module): def __init__( self, latent_size, dims, dropout=None, dropout_prob=0.0, norm_layers=(), latent_in=(), weight_norm=False, xyz_i...
c7cd9ad7e6c99b73ed64d2dd0dc6dbafc1ea3ec2de040c6ca86d86f7dfe92db2
Python
3,297
108
#!/usr/bin/env python3 import torch.nn as nn import torch import torch.nn.functional as F class Decoder(nn.Module): def __init__( self, latent_size, dims, dropout=None, dropout_prob=0.0, norm_layers=(), latent_in=(), weight_norm=False, xyz_i...
0b8d5d0653fe6180c22dea21fa7a93eb0d5bf6c692a761bb09e56b9356d411e4
Python
3,298
106
import numpy as np from torch.utils.data import DataLoader, Dataset import scanpy as sc import torch import sys sys.path.append('..') from ..VAE.VAE_model import VAE from sklearn.preprocessing import LabelEncoder def load_VAE(vae_path, num_gene, hidden_dim): autoencoder = VAE( num_genes=num_gene, ...
53d27206af05e7360374ca37b79fd5b67ae21679622099c3ccf7e58808e5af1c
Python
3,298
91
import matplotlib.pyplot as plt import numpy as np from sklearn.metrics import confusion_matrix import pandas as pd def calculateConfusion(filename): data = pd.read_excel(filename, sheet_name=None) data_list = [] for k, df in data.items(): # Example true and predicted labels true_labels =...
bb6aa341564d80cc4fa93ca42da1dad0938567e21ccfec0cf061bec11cdea6ca
Python
3,298
86
import os import pprint SAMPLE_SIZE = 1000 INPUT_DIR = '../../../train/results/train_test_dataset/' NEG_DATASETS = [f'{INPUT_DIR}input_neg_1/800bp/test_neg_1.shuffle.fa', f'{INPUT_DIR}input_neg_random/800bp/test_neg_random.shuffle.fa'] POS_DATASETS = [f'{INPUT_DIR}input_pos_alts/800bp/test_pos_alts.shuffle.fa', f'{INP...
180671ebb843949a32a4d6218fef218224983d2cdf944667bf0d28c727317fbf
Python
3,301
113
import numpy as np from pokeformer.vocabs.prot_atom_names import atom_names, res_names from pokeformer.vocabs.prot_atom_vocab import ProtAtomFeature def _get_pdb_atom_lines(pdb_file: str): with open(pdb_file) as f: raw = f.readlines() return list( filter( lambda x: x[:6] == "ATOM ...
6b749645f4a8509473f05d1f7903d7296fc5cef84f5dfd38bb4e11374872afd0
Python
3,302
83
import requests from .__config import base_url from .__aux_funcs import process_response def get_all_gene_panels(direction="ASC", pageNumber=0, pageSize=10000000, projection="SUMMARY", sortBy=None): """ Get all gene panels from cBioPortal. \n :param direction: Direction of the sort. \n Possible val...
667d02129b18ee1568268d66085749c75d0c8fd6115d8772e2b9e01d03b78c18
Python
3,303
108
import numpy as np from copy import deepcopy from utils import to_pth class Polynomial(): def __init__( self, n_terms=5, max_coeff_val=.5, max_degree=3, max_shift=3, xrange=1, xstep=.01, noise_level=0, ): self.n_terms = n_terms self.max_coeff_val = max_coeff_val ...
ed8af9856da42377383e64a314a25566dd14f2631403dc9de1fef57e719496f8
Python
3,303
113
import time from logging import getLogger try: from gym.wrappers import Monitor as _GymMonitor except ImportError: class _Stub: def __init__(self, *args, **kwargs): raise RuntimeError("Monitor is not available in this version of gym") class _GymMonitor(_Stub): # type: ignore ...
2cef0f9418d0f93c8e029755570e28106c0fc04cdb5b7f94e86b8b4e91597370
Python
3,306
87
# %% import pandas as pd from UpSetPlot.upsetplot import plot from matplotlib import pyplot as plt from UpSetPlot.upsetplot import generate_counts, plot import matplotlib.patches as mpatches from UpSetPlot.upsetplot import UpSet from UpSetPlot.upsetplot import from_contents from matplotlib import cm import numpy as np...
14ce1c0a069494d8ee0905fb42fde58a2893190446db96bd19c3491970b032f5
Python
3,307
95
import dataclasses import logging import time from concurrent.futures import ThreadPoolExecutor from queue import Queue from typing import List from ray.autoscaler.v2.instance_manager.instance_manager import ( InstanceUpdatedSubscriber, ) from ray.autoscaler.v2.instance_manager.instance_storage import InstanceStor...
bceded8ef978f977d98b645b68a4bc96e9edf19f22ccd7b59e9eb46f1eb10e3f
Python
3,307
97
"""Script to download the SeizeIT dataset doi:10.48804/P5Q0OJ. The script requires a valid API key and depends on the requests library. """ import hashlib import json import logging import os from pathlib import Path import requests from requests.adapters import HTTPAdapter, Retry def downloadSeizeit(destination: s...
58ee74c4e35a2f48a671ee07a8091053b71debce9fb881fdc8c9db709650cb5d
Python
3,308
72
#################################################################################################### # Copyright (c) 2016 - 2024, EPFL / Blue Brain Project # Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch> # # This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis> # # This program is fre...
eecf2979a15d94099be584e2c2b40ebf6d69c01f6b25d492c91b495c27ceeb1c
Python
3,308
76
#################################################################################################### # Copyright (c) 2016 - 2024, EPFL / Blue Brain Project # Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch> # # This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis> # # This program is fre...
8bdbc6c389dc0ca87040ee563511e17241eaa05051e6a30eba2c9f5321d1dc0e
Python
3,309
93
"""Random-partition baseline. Uniformly assigns each cell to one of ``n_metacells`` buckets, optionally stratified by an ``obs`` column (e.g. cluster) so that within-stratum random sampling is what gets compared against principled metacells. This is the **honest baseline** users should sanity-check against — see Bilo...
6d2587df273226de81dc8bdd908cdd26638f9b40abf39984efd85d66f7b90167
Python
3,310
78
import numpy as np import random def scramble_timeseries(timeseries): """Expects a dense NxTx3 array of three-channel timeseries data, with N samples of duration T. If the three channels are: heartrate, stepcount, nonmissingness, returns two new datasets. The first returned value is the 'scramble...
94748e6f9cff43a36d3c270ca86ac1c5b807774034ac23f7f5b10ec398a93414
Python
3,310
76
from typing import Any import math import numpy as np from tqdm import tqdm from .countdata import CountMatrix from . import Colors, EMOJI def log_fold_change(old, new, base=2): return math.log(new/old, base) def expression_modulo_metadata(count_matrix: CountMatrix, header: str ...
820e12d1ce73fce4038c0989d34305150878ad2757132c1b7f6f37d6f6990902
Python
3,313
112
""" Minimal working example for shotgun VAE using mouse USVs. 0) Define directories and parameters. 1) Tune preprocessing parameters. 2) Warp song renditions & train a generative model. 3) Plot. 4) The world is your oyster. """ from itertools import repeat from joblib import Parallel, delayed import numpy as np impo...
1ff7c8857a6a074cc690ddc949fe757144ea6058f2789777b9371d35c72e4fd7
Python
3,315
208
import matplotlib.pyplot as plt import numpy as np from spinnaker2 import brian2_sim, helpers, s2_nir # , hardware import nir np.random.seed(123) timesteps = 50 # load NIR model nir_model = nir.read("lif_norse.nir") print(nir_model) # patch nir model LIF_node = nir_model.nodes["1"] assert isinstance(LIF_node, nir...
61b97c878279f4e407e4c64ae8800cbc848b7f9598b38e5cbfc6e016bb2695a9
Python
3,315
88
"""Register each run to one reference run.""" import os import subprocess import glob # ============================================================================= DATADIR = '/Users/sebastiandresbach/data/neurovascularCouplingVASO/Nifti' # Set subs to work on SUBS = ['sub-07'] # ===================================...
3390ee3b5c3d894326c73d760427367334e529afe20b4ec2f396deda61a99197
Python
3,316
86
import os import h5py import numpy as np from typing import List, Tuple, Dict from itertools import product from ml4h.defines import TENSOR_EXT from ml4h.TensorMap import TensorMap, Interpretation CONTINUOUS_TMAPS = [ TensorMap(f'{n}d_cont', shape=tuple(range(2, n + 2)), interpretation=Interpretation.CONTINUOUS)...
95af7651ce801c45a1acfdae2a3700bd54000c24955ed6044fb7a5a14b518638
Python
3,316
68
import requests from .__config import base_url from .__aux_funcs import process_response def fetch_gene_panel_data(molecular_profile_ids=None, molecular_prof_sample_ids=None): """ Fetch gene panel data from cBioPortal. \n :param molecular_profile_ids: List of Molecular Profile IDs (e.g., ["brca_tcga_gistic...
27eb1d7640c62163710f5399b60c604f9737e9be91369a1ef4d5a0b5ac4858f8
Python
3,318
114
""" Compare the statistical values computed with nilearn versus fsl """ import pandas as pd import numpy as np import nibabel as nb import glob import matplotlib.pyplot as plt import seaborn as sns # Set data path DATADIR = '/Users/sebastiandresbach/data/neurovascularCouplingVASO/Nifti/derivatives' # ============...
94d6ea77c3f619e6df90cd75eb2595b983f65b21e9439bba9b14494066741ae6
Python
3,318
108
#!/usr/bin/env python3 import torch.nn as nn import torch import torch.nn.functional as F class Decoder(nn.Module): def __init__( self, latent_size, dims, dropout=None, dropout_prob=0.0, norm_layers=(), latent_in=(), weight_norm=False, xyz_i...
1ffffbdf2622b83fa719465099ed678d16876a5d304438fe795c9990f24a9ce9
Python
3,319
87
#################################################################################################### # Copyright (c) 2016 - 2024, EPFL / Blue Brain Project # Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch> # # This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis> # # This program is fre...
bf275c6b38c57240712da3471f13906c984668b1da6da9c58e09b753e62cede4
Python
3,319
82
import sys def main(): output_dir = "./dataset/" output_files = [output_dir+"pos/", output_dir+"pos_MANE/", output_dir+"pos_ALTS/", output_dir+"neg_1/", output_dir+"neg_random/"] target = "splam" for output_file in output_files: for target in ["spliceai/spliceai.noN", "spliceai/spliceai.N", "s...
013af86a66e1deb0f1b76db45f45abfb82a8cc38c91d4f773c906d47c051481c
Python
3,320
101
# flake8: noqa # fmt: off # __example_deployment_start__ import time from ray import serve from starlette.requests import Request @serve.deployment( # Each replica will be sent 2 requests at a time. max_ongoing_requests=2, # Each caller queues up to 2 requests at a time. # (beyond those that are sent ...
e2314afeac99d5d7f70438a8accd308b26a44a90f00ba167838d1401247d3915
Python
3,320
111
#!/usr/bin/env python # Copyright (c) 2017-present, Facebook, Inc. # # 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 a...
09c3207d7a2252b8552cf745768fbcd5a0dcbfb9ff6e2941adb9cdb932693acf
Python
3,321
88
""" Copyright (c) Meta Platforms, Inc. and affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ from __future__ import annotations import logging from typing import TYPE_CHECKING, Literal import torch from fairchem.core.units.mlip_u...
242e8bf0cbe3e82256c05374ed843dd77aead985c82a96babc42afa87677a67b
Python
3,321
90
#################################################################################################### # Copyright (c) 2016 - 2024, EPFL / Blue Brain Project # Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch> # # This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis> # # This program is fre...
d81c63b70db816c261566c8598cd1d144c577922fcfe59730230e87b38a72074
Python
3,321
104
import numpy from pfrl import agent from matplotlib import pyplot def scale(x, space, key): return x * (space[key]["high"] - space[key]["low"]) + space[key]["low"] def rescale(x, space, key): return (x - space[key]["low"]) / (space[key]["high"] - space[key]["low"]) class HumanAgent(agent.BatchAgent): "...
69bd434801231cc959ffcd873f90e1ecbfd0f6efc70a32db54cd5cca9a1e5aed
Python
3,322
104
''' Calculates ALL 39203 combinations for Yi2014. This takes VERY long. ''' import moabbpatch import moabbpatch.datasets import moabbpatch.baseparadigm import moabbpatch.mne_estim_output SEED = moabbpatch.set_random_seed(1023) import numpy as np import pandas as pd import swifter import moabb import mne # to disable ...
99af90c87f3c67d6c24102e95e30a3ebcc24c86d8e5af86cad15601e01852178
Python
3,322
88
# Copyright (c) DP Technology. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from __future__ import absolute_import, division, print_function import numpy as np import torch from torch.utils.data import Dataset from .data import DataHub fro...
0ec8b1a410f10ae03f7762f269e52486d8fabb3d18b3d2074554a491a51f683c
Python
3,323
127
# flake8: noqa # fmt: off # __init_namespace_start__ import ray ray.init(namespace="hello") # __init_namespace_end__ # fmt: on ray.shutdown() # fmt: off # __actor_namespace_start__ import subprocess import ray try: subprocess.check_output(["ray", "start", "--head"]) @ray.remote class Actor: pass ...
44cc8e86a1714754f6b4f4ee753c1d6f462dbeef0b34c4dbe093cb3fde40acb1
Python
3,323
86
import pandas as pd import os def get_hg38_chrom_size(): f_chrs = open("../src/hg38_chrom_size.tsv", "r") lines = f_chrs.read().splitlines() chrs = {} for line in lines: eles = line.split("\t") chrs[eles[0]] = int(eles[1]) return chrs def main(): chrs = get_hg38_chrom_size() ...
8443283062ea7bff3e8feb6084415f26336454a35883060a17bf884e9f976f37
Python
3,323
80
import numpy as np import struct from spinnaker2.neuron_models.application import BaseApplication from spinnaker2.configuration import PEConfig from spinnaker2.neuron_models.common import add_log_memory_region, format_routing_table from spinnaker2.coordinates import ByteAddr class SpikesFromImagesApplication(BaseApp...
0f823d610bfb074a9f9736394090af7cb00e144055dce881939aa4447a2a56f0
Python
3,324
80
import torch __all__ = ["local_pixel_shuffle", "random_inpainting", "random_outpainting"] def local_pixel_shuffle( data: torch.Tensor, n: int = -1, block_size: tuple = (0, 0, 0), rel_block_size: float = 0.1 ) -> torch.Tensor: batch_size, channels, img_rows, img_cols, img_deps = data.size() if n < 0: ...
09e1e7c74d413356caa13ab174bcbe1ba083156915c4319474bd71e02428ef9c
Python
3,325
116
# built-in dependencies import os from unittest.mock import patch # 3rd party dependencies import pytest import psycopg from deepface import DeepFace # project dependencies from deepface.commons.logger import Logger logger = Logger() connection_details_dict = { "host": "localhost", "port": 5433, "dbname...
3544ccc7d321b106d0970802f3af88839618f401e7d1a433c69c76101c51f265
Python
3,325
109
import gc from os.path import join import anndata import dask.dataframe as dd import lightning.pytorch as pl import numpy as np import pandas as pd import xgboost as xgb from scipy.sparse import csr_matrix from cellnet.estimators import EstimatorCellTypeClassifier from cellnet.models import TabnetClassifier, LinearCla...
63a5e4d25bbfd1967c285eaa5b0d80d3f98d1f818107a727bb71b2ba750b1fdd
Python
3,325
74
#################################################################################################### # Copyright (c) 2016 - 2024, EPFL / Blue Brain Project # Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch> # # This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis> # # This program is fre...
fcb26dbe7a2508e839eb2f71d0cf32e270b7e3e2643379039328226500966c8f
Python
3,325
92
r"""``ov.epi.pl`` — epigenomics plotting (wraps :mod:`epione.pl`). QC diagnostics, embeddings, differential-accessibility and peak-to-gene plots, footprints and Hi-C contact visualisations, delegating to `epione <https://github.com/aristoteleo/epione>`_. Each function imports epione internally and returns the matplotl...
500f08e7ff3c8d90f043b293a4890436c36850fb35dedf13b8cdaaabcac5f75a
Python
3,326
94
"""Tests for toy.py.""" import numpy as np import pytest import torch from torch import nn class TestMLPModule: @pytest.fixture def module_cls(self): from skorch.toy import MLPModule return MLPModule def test_one_hidden(self, module_cls): module = module_cls() parameters ...
8f30021e9605366af8964b9bf3e538161b34bce4dc439160d2b63362b73985b0
Python
3,326
120
from typing import Callable, Optional from numpy.typing import ArrayLike from jaxtyping import Key import numpy as np import jax import jax.numpy as jnp import jax.random as jr from .modules import NoGradLayer from ..global_defs import ( get_default_dtype, get_params_dtype, get_sites, ) class Scale(NoGrad...
9177e4e719fc38904ce67f37263a9451029938bf88d19ef217bca2fb341a4fc8
Python
3,326
95
import torch.nn as nn from network import resnet_d as Resnet_Deep from network.nn.mynn import initialize_weights, Norm2d, Upsample from network.nn.operators import ModuleHead, Aux_Module, ChannelReasonModule class SRNet(nn.Module): """ Implement DeepLabV3 model A: stride8 B: stride16 with skip c...
91b2d0e870ad8271f007a20de8ff9ada9834fe873cc54ce0636b5f039d066e21
Python
3,326
89
import numpy as np import scipy.special as ssp def get_tc(y, hd, bin_len=40): # compute empirical tunning curve of data hd_bins = np.linspace(hd.min(), hd.max(), bin_len) tuning_curve = np.zeros((len(hd_bins) - 1, y.shape[1])) for ii in range(len(hd_bins) - 1): data_pos = ((hd >= hd_bins[ii]) * (...
a057a21c1b7b555c6fe093e498bf38fe9eb1e343ee11cc3dc74b25508d3ab0d8
Python
3,328
121
""" Some handy utilities for working with vector geometries """ from typing import List, Tuple, Callable import warnings from shapely import geometry as geo def get_ccw_vertices_from_two_lines(line1: List[Tuple], line2: List[Tuple]): """ Convenience method two do both get_vertices_from_two_lines() ...
2718f7ba7416b2b194ad7b05fef28448a1f47c55e56604efb5b4cb23a9d6a56f
Python
3,329
72
#Imports relevant modules import os import numpy as np import csv #Defines the directory containing pipeline results. feat_dir = '/<directory root>/FEAT/' #Full path removed for purpose of public sharing. #Defines the pipeline we're interested in. pipeline = '0' #Defines the filepath of this pipeline. pipeline_dir =...
992e4794dc8968b0b86aefddfc8ff2a32723993c23d1972a0449d648753465f3
Python
3,329
83
"""Methods for Facets notebook integration.""" import base64 import os import pandas as pd from facets_overview.generic_feature_statistics_generator import GenericFeatureStatisticsGenerator FACETS_DEPENDENCIES = { 'facets_html': 'https://raw.githubusercontent.com/PAIR-code/facets/master/facets-dist/facets-jupyter...
9fbb3ce4e47bc6aa84be0444912eb3b8d709674327d2280e78ae73b54b4e5775
Python
3,331
101
__all__ = [ 'Wasserstein2Loss' ] import cupy as cp import torch from typing import Dict, Tuple from .utility import torch_to_cupy, cupy_to_torch, BLOCKDIM, BLOCKSIZE ker_blur = cp.RawKernel(r''' extern "C" __global__ void blur( const float* src, int size, int n, float B, float* dst) { int ...
5494ae7eec942d9c3a442a6f90412e6ce125e62842bb7636acef0f640c5f64da
Python
3,332
88
"""Validated inputs for the HiveServer2 read API. This module defines the API boundary without opening a Hive connection or creating a Ray read task. The public read_hive facade is defined in ray.data.read_api. """ from __future__ import annotations import re from dataclasses import dataclass, field from typing impo...
81d6ea9d368509834e17cd1206f8de21d69c44a93719ab3c8925352d745fda51
Python
3,332
87
# -*- coding: utf-8 -*- # (C) Copyright 2026 IBM. All Rights Reserved. # # Licensed under the MIT license. See LICENSE file in the project root for details. """Runner that executes Experiments locally.""" from typing import Dict, List, Optional from torch import device as torch_device from torchvision.datasets impo...
caebca2febba273f5cad2801426aa6672912ad617bd7df5166e8ae4fae435b87
Python
3,332
67
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'thinbass.ui' # # Created by: PyQt5 UI code generator 5.15.2 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, QtG...
e7d7cd21d7c94c8f78a303b1265cc9b1b4878e4bdf05dd99558e2762d9d95a68
Python
3,332
113
# flake8: noqa # isort: skip_file # __xgboost_start__ import pandas as pd import xgboost # 1. Load your data as an `xgboost.DMatrix`. train_df = pd.read_csv("s3://ray-example-data/iris/train/1.csv") eval_df = pd.read_csv("s3://ray-example-data/iris/val/1.csv") train_X = train_df.drop("target", axis=1) train_y = trai...
f617e984fd7536802627a537d6382cad3e3c7820dd691c82be7001934d8f7b2d
Python
3,334
72
import argparse import json import os.path import keras import glob import numpy as np import PIL.Image from tensorflow import keras as k import time from utilities import extract_patches from osgeo import gdal PIL.Image.MAX_IMAGE_PIXELS = 500000000 def calculate_qs(tile_path, model, num_patches=9, us...
218f335a7f0f13f0c5968ce189ee615c128e7f507db075615f1207f388ce4e0e
Python
3,335
99
""" Copyright (c) Meta Platforms, Inc. and affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ from __future__ import annotations import os from abc import ABCMeta import hydra import numpy as np import omegaconf import torch from t...
4cae92373ea761973145b3d1412fd83b9ba090761656c42748fd2e6db8e24e0d
Python
3,335
117
""" Synfire chain example Reproduction of synfire chain implementation from SpiNNaker2 prototype chips. References: 1. Implementation on Santos28 chip: Höppner, Sebastian, et al. "Dynamic power management for neuromorphic many-core systems." IEEE TCAS I(2019). https://doi.org/10.1109/TCSI.2019.2911898 2. Impl...
76d74d35297b290552c631731d8fc371a3965fb1b58a6e52fda49b9a0fc6dd4a
Python
3,335
119
from typing import Optional, Callable import jax import jax.numpy as jnp from equinox.nn import Lambda from .modules import Conv, Sequential from .nqs_layers import ReshapeConv from ..sites import TriangularB from ..utils import neel, stripe from ..global_defs import get_lattice, get_subkeys def sign(neg: bool = Fals...
8b78b46c164efa28605fc60830b95c3b2059d8d9b2b5f71ebfba547f064e42ac
Python
3,336
74
# Copyright 2023 The HuggingFace Team. 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 applicabl...
bab16644bf3f1d091a0f5a99c1a01512a77c93099e463937564cc3b8f21d8044
Python
3,336
97
# -*- coding: utf-8 -*- # (C) Copyright 2020, 2021, 2022, 2023, 2024 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. #...
33846f81538868630f6ed798963ca72ea9e9cd5dfd34b2ea3c1268066684d5cf
Python
3,337
108
# 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...
a2edb0167cb2e446cbc1013d93589b746f1a73e283beba4c2d126a08ee38ac64
Python
3,337
131
import argparse import torch import random import os import numpy as np import pandas as pd from chromoformer import ChromoformerDataset from chromoformer import ChromoformerClassifier from tqdm import tqdm from sklearn import metrics def seed_everything(seed=42): random.seed(seed) np.random.seed(seed) ...
ff5f68d49f573f5f2ff9042a6dd5039dafd79ba27a33455ee37f137c9c4df31e
Python
3,338
98
import os import hashlib from typing import Any, Set import logging from datetime import datetime # pylint: disable=broad-except class Logger: """ A Logger class for logging messages with a specific log level. The class follows the singleton design pattern, ensuring that only one instance of the Logg...
e55a5c6e54cecac56f0cfd6ea527854cfd4da8fcdccbd5cf43bceb056049db2f
Python
3,340
80
import torch from torch import nn from monai.networks.nets import EfficientNetBN class PrognosisModelD(nn.Module): def __init__(self): super(PrognosisModelD, self).__init__() self.extractor_liver = EfficientNetBN(model_name="efficientnet-b0", in_channels=1, spatial_dims=2, num_classes=32) ...
1d358dacd57782198e9fc003971e8a2901c8a92ac9c4bef12e1b82e19a7305e4
Python
3,342
93
"""Functions related to n_component inference from fit data.""" # Copyright (c) 2024 Valentin Goldité. All Rights Reserved. # Modified from https://github.com/scikit-learn (BSD-3-Clause License) # Copyright (c) Scikit-learn developers. All Rights Reserved. from math import log from typing import Union import torch fr...
1fc7b4d2e2b9daf729372bab480e2751748f3b9ede7ccf7401827007229d754a
Python
3,343
100
import os import sys import time import h5py import numpy as np from typing import Tuple, Optional, List from ml4h.defines import TENSOR_EXT, StorageType from ml4h.TensorMap import TensorMap, Interpretation Shape = Tuple[Optional[int], ...] DataDescription = Tuple[str, Shape, StorageType] SYNTHETIC_DATA_PATH = os....
225bb97947a32b2593013bb53f93c30a2e61bf4178f6227eb9f9880ea665e0dd
Python
3,343
138
#!/usr/bin/env python # -*- coding: utf-8 -*- # """ Access multiple TabixFiles from a single interface. Fetching from the list of TabixFiles returns an iterator over merge-sorted entries in the tabix files. """ import heapq import pysam from svtk.utils import is_smaller_chrom class _TabixRow: def __init__(self...
9096815ef1d36126c51332167ff464bfb2defb9603bdacda04a124f78dbf400f
Python
3,345
92
# built-in dependencies from typing import Any, List, TypeVar, Union, cast # 3rd party dependencies import numpy as np from numpy.typing import NDArray import torch from torch import nn # project dependencies from deepface.models.FacialRecognition import FacialRecognition from deepface.commons.logger import Logger l...
d304ff17fa36d538c0243c1221b8381b20e6fb21bb7f7ebebe835c860415ad13
Python
3,345
109
"""input/output functions.""" import os import pickle from pathlib import Path def save_object(obj, folder=".", filename="./obj"): """Save general object in a pickle.""" if not Path(filename).parent.is_dir(): Path(filename).parent.mkdir() pickle.dump( obj, open(os.path.join(folder,...
dba1ef27a47fff46448791f7b2aa141f3df98551483405878dafe4793812d17f
Python
3,345
89
import json import os import pandas as pd from anndata import AnnData from sklearn.metrics import f1_score def _dataframe_to_markdown(df): # Create the header pretty_columns = [ ( "Consensus Prediction" if col == "popv_prediction" else (col[4:-11].replace("_", " ")...
586a96b08e4b1a126e9ddf9db8016c2190514ebdf24c3518cc8a69a423b42963
Python
3,346
108
import warnings import torch import torch.nn as nn import torch.nn.functional as F from lqit.registry import MODELS def gaussian(window_size=11, sigma=1.5): x = torch.arange(window_size) gauss = (-(x - window_size // 2)**2 / (2 * sigma**2)).exp_() return gauss / gauss.sum() def create_window(window_si...
6b42a61dd99526b6044ecbcfc7f23ac0cb3a9695962f58dddc67091a9bf3077e
Python
3,346
90
import numpy as np from typing import List, Set, Dict, Tuple import visionloader as vl import spikebinning SAMPLE_RATE = 20e3 #ACFT1 = 0.5e-3 # units seconds ACFT1 = 0 # units seconds ACFT2 = 1e-3 # units seconds ACFT1_SAMPLES = ACFT1 * SAMPLE_RATE ACFT2_SAMPLES = ACFT2 * SAMPLE_RATE def count_refractory_violat...
9576f817cc63c955fe0a64fb4a85253672b13326045db8165f928f689d870e63
Python
3,346
101
import socket import os import sys if socket.gethostname() == 'kelarion': CODE_DIR = '/home/kelarion/github/' SAVE_DIR = '/mnt/c/Users/mmall/Documents/uni/columbia/assignment_errors/' LOAD_DIR = '/mnt/c/Users/mmall/Documents/uni/columbia/assignment_errors/server_cache/' repler_DIR = 'repler/src' else: ...
59a05f33482c1e62db85d07df8e437efd3ded4b263f9fc8ac02b43d6fd00f0e2
Python
3,347
90
import numpy as np import nibabel as nb from nilearn import image from nilearn import datasets def _load_aal(): aal = datasets.fetch_atlas_aal() img_aal = nb.load(aal.maps) mtx_aal = img_aal.get_fdata() list_val = np.unique(mtx_aal) return img_aal, mtx_aal, list_val def _expand_parcels(img_aal, ...
9886d1a18b31dea0052b9309b562fac2fa1fe0a47c7ca229c8875b2efde8ccf3
Python
3,347
91
from typing import Callable, Optional import torch import torch.nn as nn class Repeat(nn.Module): """Utility layer which wraps any nn.Module. It flattens time and batch dimensions of the input before feeding it to the child module and unflattens those dimensions to the original shape before passing it t...
1257f0d077893b610716355b508aaf9c0e863c978845735a7dfea39622508228
Python
3,350
105
# # CEBRA: Consistent EmBeddings of high-dimensional Recordings using Auxiliary variables # © Mackenzie W. Mathis & Steffen Schneider (v0.4.0+) # Source code: # https://github.com/AdaptiveMotorControlLab/CEBRA # # Please see LICENSE.md for the full license document: # https://github.com/AdaptiveMotorControlLab/CEBRA/bl...
907d2da2bceee304cd71006af6d2b13edcfa54051ba90fb59be84dc370920efe
Python
3,350
88
''' Registering anatomical to functional image because that seemed to work better than the other way round. Then applying the inverse transformation to register func to anat. ''' import glob import os import subprocess subs = ['sub-07'] # Define data dir DATADIR = '/Users/sebastiandresbach/data/neurovascularCoupl...
daa370a63f458de4c4ada4c8a48aa869f6503c15d54ee2f31ce3666cffdcdeca
Python
3,350
100
"""Enrichment dispatcher for ``ov.protein`` — thin wrapper over ``ov.es``. For protein-level analysis the canonical input to ``ov.es`` is either: * the AnnData itself (per-sample scoring), or * a ranked statistic vector from ``ov.protein.de`` (one-shot GSEA / ORA). This module re-exposes the relevant ``ov.es`` funct...
ebbf463e521689f3fd90bbc52299c59dcbebf640884395e26f04f01bb70dab5a
Python
3,352
103
#!/bin/python #------------------- Description & Notes --------------------# #------------------- Dependencies ---------------------------# # Standard imports from pathlib import Path # Third-party imports import numpy as np import pandas as pd # Internal imports from ..shared.kmer.common import * from ..shared.co...