sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
aa2ada3a702ea94fecac2421e17902a7a4212b3f63df88c404e6c1955f9e05e3 | Python | 2,766 | 68 | from src.networks.feature_extractors.mednet3d import MedNet3D, BasicBlock, Bottleneck
from src.utils.constants import FeatureExtractorNetworks
import torch
def get_feature_extractor(config: dict) -> torch.nn.Module:
if config["network"] == FeatureExtractorNetworks.MEDNET3D.value:
if config["depth"] == 10:... |
82acb5cf7e4183d8109fd0ad463066fa5e77e465ee865afb0bcc060ce2de230f | Python | 2,768 | 56 | import argparse
import sys
from config import TrainConfig, InferenceConfig
import os
def train_arg_parser():
default_config = TrainConfig()
default_param = vars(default_config)
parser = argparse.ArgumentParser(description='train CNN model to denoise volumetric functional recordings')
for att in defau... |
1730eb063b239e27b0a575a2dceed920a4cabaad3c386f9bcb24f6a79ab50c76 | Python | 2,769 | 45 | from torch_pgn.featurization.simple_featurization import (
featurize_atoms_ECFP_like, featurize_edges_simple
)
######################### Function to calculated all of the atom and edge features #####################################
#TODO: make featurization function an argument to allow for other possible choices... |
ffa131d9b7f0e80dc72eff9ccb9331a90c611951416b2d0faaf0ca5cf4a02ccf | Python | 2,770 | 91 | # 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 applicable law or agreed... |
3806a804f415d45b2595348214d289a4d9c03b9af4e6a3bca827425486b8eb8a | Python | 2,771 | 130 | # -*- coding: utf-8 -*-
"""
========
Images
========
The `image_io` subpackage provides tools for working 2D images. It includes
methods for:
- Converting to and from VTK's `vtkImageData`_ class.
- Image reading and writing via VTK's image reader/writer classes.
- The image trimming utilised by `vtkplotlib.screenshot... |
8dba6cb7411cda1bf270a33723761aabe6041c404e44cf434e3cf16faad6b617 | Python | 2,772 | 73 | import datetime
import grpc
import queue
import time
from projectmetis.python.logging.metis_logger import MetisLogger
from concurrent import futures
from grpc._cython import cygrpc
from pebble import ThreadPool
from projectmetis.proto.metis_pb2 import ServerEntity
class GRPCChannelMaxMsgLength(object):
def __i... |
fdf6d5da690a535e1c6c73b56d76daad29d4c9efd16eccbd6e1fb79b75abb00e | Python | 2,772 | 69 | #!/usr/bin/env python3
import os, sys
from IsoNet.util.image import *
from IsoNet.util.metadata import MetaData,Label,Item
from IsoNet.util.dict2attr import idx2list
def predict(args):
if args.log_level == 'debug':
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '0'
else:
os.environ['TF_CPP_MIN_LOG_LEVEL'... |
8d32d848f6ebf549d941be9ac8d84637d21c73a9177c76a62f461c6eee955d44 | Python | 2,773 | 97 | from data_profiling.config import Settings
from data_profiling.report.formatters import fmt, fmt_bytesize, fmt_numeric, fmt_percent
from data_profiling.report.presentation.core import (
HTML,
Container,
Image,
Table,
VariableInfo,
)
from data_profiling.visualisation.plot import scatter_complex
def... |
dabc858c6c185702b7431761d90ca693cec1f7310ff0c759c9825909e8caa6ac | Python | 2,773 | 64 | # SPDX-License-Identifier: MPL-2.0
# Copyright (C) 2007 Julien Pommier
# Copyright (C) 2014 Pedro Gonnet
# Copyright (C) 2009-2019 Gael Guennebaud
# This Source Code Form is subject to the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, obtain one at
# https://mozilla.org/MPL/... |
e2d3a04b45808d95bd8b197c026640ad29f1c81e1a2114a8c7ff22b7d9089349 | Python | 2,773 | 86 | from spinnaker2.configuration import PEConfig, MemoryRegion
from spinnaker2.coordinates import ByteAddr, QPE
N_WORDS_MPT_ENTRY = 3 # number of words per master population table
def add_log_memory_region(pe_config, byte_addr=0x0001b000, word_count=4000):
# for all apps, add debug info
# debug register locactio... |
3a507408099ed7657ccc3b852342f0b1881d1cc9c0475c24eaf7d02107a1cbfb | Python | 2,775 | 78 | """Check if there is any part of V1 outside of the sphere but inside of the funcitonal coverage"""
import nibabel as nb
import numpy as np
import pandas as pd
folder = '/Users/sebastiandresbach/data/neurovascularCouplingVASO/Nifti/derivatives'
subList = []
coveredList = []
inSphereList = []
subs = ['sub-05', 'sub-0... |
6558275de913a3fe4c27183346adf92b9b87e59cdae4933cc3787a61d5c5f533 | Python | 2,775 | 71 | import os
import sys
from multiprocessing import Pool
import imgaug.augmenters as iaa
import numpy as np
from skimage.io import imread
from skimage.io import imsave
def distort_image(input_image_path: str, output_image_path: str) -> None:
"""This function takes the path of an input image and the desired output
... |
87ad8037f2c3800efb98c9d1a2333556eda7c686b2f09ac3095159a0779c063d | Python | 2,775 | 97 | import sys
from unittest.mock import patch
import pytest
from ray._common.deprecation import (
DEPRECATED_VALUE,
Deprecated,
deprecation_warning,
)
def test_deprecation_warning_warn():
with patch("ray._common.deprecation.logger.warning") as mock_warning:
deprecation_warning("old_feature", "n... |
bf14c6b14ecf8733778d3f6c4c62140451be8f07462cebbdb8ab2f0ea7445739 | Python | 2,775 | 93 | """Convert a jupytext-compliant format in to a python script
and execute it with parsed arguments.
Any cell with 'remove-cell-ci' tag in metadata will not be included
in the converted python script.
"""
import argparse
import os
import subprocess
import sys
import tempfile
from pathlib import Path
import jupytext
p... |
69904949ccf94f6692f502e6cfeb7d06aeae4bfa377dab337c043ac35e4f12ac | Python | 2,776 | 73 | # 3rd party dependencies
import pytest
# project dependencies
from deepface.commons import package_utils
from deepface.commons.logger import Logger
logger = Logger()
@pytest.fixture
def pandas_missing(monkeypatch):
real_find_spec = package_utils.importlib.util.find_spec
def find_spec(name, *args, **kwargs)... |
ffe52da9e63a05095d18399676016f254cfbe52e952a44ce3278296daa415c7c | Python | 2,776 | 73 | import subprocess
import sys
from pathlib import Path
# new scripts need to be added here to be included in the docs
HEADERS = {
"download_pretrained_models.py": "Download Pretrained Models",
"init_config.py": "Initialize Configuration",
"flyvis_cli.py": "Command Line Interface Entry Point",
"training/... |
971a3e6af66d3be107ea474721b013a4866b6ecfff02907249790a28e8a13969 | Python | 2,777 | 105 | from pickle import FALSE
from datagenerator_pd import DataGenerator
from sklearn.metrics import confusion_matrix, accuracy_score
from tensorflow.keras.utils import to_categorical
import matplotlib.pyplot as plt
import seaborn as sns
import SimpleITK as sitk
import pandas as pd
import numpy as np
import random
... |
2cf6e6424f44fcd867a90e056264a1dff6947b91ddc35ccecffcbca102c44547 | Python | 2,778 | 82 | from typing import TYPE_CHECKING, Any, Dict, Iterator, List, Optional, Union
from ray.data.block import Block
from ray.data.datasource.file_based_datasource import FileBasedDatasource
if TYPE_CHECKING:
import pyarrow
class CSVDatasource(FileBasedDatasource):
"""CSV datasource, for reading and writing CSV fi... |
b02f6c1756da9e70810578c19ea63738a0b8e40157e27e00243602f68e46e33f | Python | 2,778 | 53 | #######################################################################################################################
# This script handels the loading and processing of the input dataset for cell segmentation with Unet #
# Contains the pytorch lightning DataModule ... |
d05c90852ca25e1bc1320425816497f0e9af91b3e7522315cb245058b1885aa0 | Python | 2,781 | 68 | # -*- coding: utf-8 -*-
"""
This is the implementation of the model corresponding to the pre-print `Iso-orientation bias of layer 2/3 connections: the unifying mechanism of spontaneous, visually and optogenetically driven V1 dynamics`
Rózsa, T., Cagnol, R., Antolík, J. (2024).
https://www.biorxiv.org/ TODO: Update
"""
... |
b3371179a149808c46141478c19c4b1caaeba136abb20ad4cd842fa331c1466d | Python | 2,783 | 81 | # -*- 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.
#... |
67454f72db12b752260e66b2302deda1ca3f6a6e026847867dcf7106daa92a2a | Python | 2,784 | 77 | from typing import Optional, List
import numpy as np
from scipy import stats
from scipy.spatial import distance
from neuron_morphology.feature_extractor.data import Data
from neuron_morphology.features.statistics.coordinates import COORD_TYPE
from neuron_morphology.feature_extractor.marked_feature import marked
from... |
759226cf94dc07466599380005737224bc545db66b7b46b0e4fae750d4446595 | Python | 2,785 | 100 | import sys, os
comm = None
from collections import namedtuple
import numpy as np
def mpi_init():
if sys.platform.startswith('win32'):
print("mpi4py does not work properly on Windows, so its use will be skipped.")
return
try:
# test = 1 / 0
from mpi4py import MPI
except Impo... |
acbd09e73ae62918fb5dfbf3403ccf7c10f25627dbba50221a794a23a4a80d89 | Python | 2,785 | 69 | # -*- coding: utf-8 -*-
"""
This is implementation of model of corresponding to the article `Large scale model of cat primary visual cortex`.
Antolík, J., Cagnol, R., Rózsa, T., Monier, C., Frégnac, Y., & Davison, A. P. (2024).
PLOS Computational Biolology.
https://pmc.ncbi.nlm.nih.gov/articles/PMC11371232
"""
import m... |
50b7d43aa2a1edb3ca72c4d34b399b574ffd9c5c271a4b05ccd104740c7e854b | Python | 2,786 | 95 | '''
Doing LayNii stuff like:
- layerification
- Defining perimeter
- Flattening
'''
import subprocess
import nibabel as nb
import numpy as np
# Set data path
DATADIR = '/Users/sebastiandresbach/data/neurovascularCouplingVASO/Nifti/derivatives'
# Set subjects to work on
subs = ['sub-09']
# Set sessions to work on
#... |
ab355d46cf4267acc5923fdab310836856383d81b1284e2418520c88d77f1fb0 | Python | 2,786 | 82 | # __client_script_begin__
import logging
import time
from datetime import datetime
import requests
APPLICATION_NAME = "my-app"
DEPLOYMENT_NAME = "TextProcessor"
SERVE_ENDPOINT = "http://localhost:8265"
SCALING_INTERVAL = 300 # Check every 5 minutes
logger = logging.getLogger(__name__)
def get_current_replicas(app_... |
bcd598d236c7d63c87122e96ed6736e0976a8a48e24166e6d6adc409f4eaa1db | Python | 2,787 | 107 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 23 10:20:00 2024
@author: ju-bar
Functions useful for working with mean-squared displacements
in the Einstein model of independent harmonic oscillators
This code is part of the 'emilys' repository
https://github.com/ju-bar/emilys
published under the GNU General Publishin... |
7bf547100594a2145d9e387dc0e753ee084cbf43de100daaa3ed61aac19edacc | Python | 2,788 | 64 | import pathlib
path = pathlib.Path.cwd()
if path.stem == 'tmb_survival':
cwd = path
else:
cwd = list(path.parents)[::-1][path.parts.index('tmb_survival')]
import sys
sys.path.append(str(cwd))
import numpy as np
from lifelines import CoxPHFitter
from lifelines.utils import concordance_index
import pandas as pd
i... |
a3ec31b6fece99e1e6cb61379ce9738f68bc692d0d08f9ea27ad6878c6c4f844 | Python | 2,791 | 86 | """Script to validate an each model of an ensemble on the compute cloud."""
import argparse
import logging
from importlib import resources
from typing import List
from flyvis.utils.compute_cloud_utils import launch_range
logging.basicConfig(
format="[%(asctime)s] [%(filename)s:%(lineno)d] %(message)s", level=log... |
b8771ba800d9428539b834c8dad48c03da1049b2bba41b5f16bd828ec92d367f | Python | 2,792 | 107 | """
From https://github.com/ehoogeboom/e3_diffusion_for_molecules/
"""
import torch
def batch_stack(props):
"""
Stack a list of torch.tensors so they are padded to the size of the
largest tensor along each axis.
Parameters
----------
props : list of Pytorch Tensors
Pytorch tensors to... |
946ce7792a26a3a3c449b291cbcd5eb6e0bec1783b54fc41e633554bafbdd8bc | Python | 2,793 | 76 | """
Functions to identify TE-dependent and TE-independent components.
"""
import logging
from tedana.metrics import collect
from tedana.selection.component_selector import ComponentSelector
LGR = logging.getLogger("GENERAL")
RepLGR = logging.getLogger("REPORT")
def automatic_selection(component_table, n_echos, n_vo... |
c3d17a490c6c0763d388ab934cf6f1e193a3daeeab52ed73cc4c307340001150 | Python | 2,795 | 101 | #!/usr/bin/env python3
import sys
from pathlib import Path
import pygraphviz as pgv
if len(sys.argv) < 2:
print("DAG should be provided in stdin (i.e. piped in from snakemake or cat)")
print(f"Usage: {sys.argv[0]} <output_prefix> ")
print(f"e.g.: snakemake --dag | {sys.argv[0]} out_dags/mydag")
sys.e... |
0acd4b7de1471f216dcc72f4b960f040271ae872309d309a2d1dbe96f633f277 | Python | 2,797 | 91 | # flake8: noqa
# fmt: off
# __tasks_fault_tolerance_retries_begin__
import numpy as np
import os
import ray
import time
ray.init(ignore_reinit_error=True)
@ray.remote(max_retries=1)
def potentially_fail(failure_probability):
time.sleep(0.2)
if np.random.random() < failure_probability:
os._exit(0)
... |
14ab213c7a23db85002df745928b7eff636a8627ab3a00df4bd559702d47534d | Python | 2,797 | 95 | from nose.tools import eq_, ok_, raises
from mock import patch, Mock, MagicMock
import os
import sys
from os.path import *
import logging
import common
class LogBase(common.BaseClass):
modulepath = 'ngs_mapper.log'
def setUp( self ):
super( LogBase, self ).setUp()
self.filename = join('Proje... |
ae68ef8a0b4b9a25879bdab5ee43fb0628afb500c2b334f54ccd5bf0d17946fa | Python | 2,797 | 95 | """Utils functions."""
import logging
import multiprocessing
import multiprocessing.pool
from scipy import signal
import pandas as pd
import numpy as np
L = logging.getLogger(__name__)
class NoDaemonProcess(multiprocessing.Process):
"""Class that represents a non-daemon process"""
# pylint: disable=dangerou... |
49e5c54e9066a7b16d0bd9995d7eb946cc0d36b022f6a867e3ce5167b864d153 | Python | 2,798 | 90 | import setuptools
import string
import os
from numpy.distutils.core import setup
from numpy.distutils.core import Extension
from sys import platform
pkg_name = "fmm3dpy"
## TODO: this should be automatically populated using "read directory, or whatever"
## TODO: fix problem with relative location for executable
list... |
ac0ed7f5cc7e29cd3a7795e69bfe320757743f57e91cabbc86736b9382c55f98 | Python | 2,798 | 122 | import argparse
import os
import shutil
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from PIL import Image
from torch.autograd import Variable
from torchvision import transforms
import cv2
import time
import argparse
from scipy.io import loadmat
from torch.nn import functional as F
... |
0c83d2e3742b7b86e2d204dc15770c23e421557e83dbc3a208e4965586a98ba3 | Python | 2,800 | 107 | # -*- coding: utf-8 -*-
"""
Pull and test code-blocks from docstrings. I'm 100% certain this must be a
reinvention of the wheel but I can only find doc-testing for interactive console
style code examples.
"""
import re
import types
import itertools
_code_blocks_re = re.compile(
r"(?:^|\n)( *)\.\. code... |
7a67d889afe9c78b59782709a75713c3a8d86c72f0e9a74d143968212fbfc7e6 | Python | 2,800 | 103 | # flake8: noqa
import ray
import dask.array as da
z = da.ones(100)
# fmt: off
# __timer_callback_begin__
from ray.util.dask import RayDaskCallback, ray_dask_get
from timeit import default_timer as timer
class MyTimerCallback(RayDaskCallback):
def _ray_pretask(self, key, object_refs):
# Executed at the s... |
b390a01d9025992ae4f51999fa1639661c688b924a5a4abf14a7417dad46ae47 | Python | 2,802 | 86 | # Copyright 2026 Google LLC.
#
# 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 agreed to in writing, ... |
ab3a32b867c7339a13a3a3d675888b1319199b149d732f00f0e0af1224045864 | Python | 2,803 | 68 | import torch.nn as nn
import torch
from transformers import BertModel, BertConfig, RobertaModel, RobertaConfig, AlbertModel, AlbertConfig
from transformers import OpenAIGPTConfig, OpenAIGPTModel, XLNetConfig, XLNetModel
from transformers import BartConfig, BartForSequenceClassification
# class prediction_layer(nn.Modu... |
b446e4617eb4c664643235592102c341e1eec5ffad8c963ab8f911de95dc2c50 | Python | 2,804 | 97 | import pytest
import torch
from sinabs.activation import (
MaxSpike,
MembraneReset,
MembraneSubtract,
MultiSpike,
SingleExponential,
SingleSpike,
)
@pytest.mark.parametrize(
"spike_fn, reset_fn, output, v_mem",
[
(
SingleSpike,
MembraneSubtract(),
... |
6c269866782ecf5acfd1bf752c19ec35ba1b13799ec8a6bbd648d089a94f61fc | Python | 2,805 | 96 | """Script to run ensemble analysis."""
import argparse
import logging
from importlib import resources
from typing import List
from flyvis.utils.compute_cloud_utils import launch_single
logging.basicConfig(
format="[%(asctime)s] [%(filename)s:%(lineno)d] %(message)s", level=logging.INFO
)
logger = logging.getLogg... |
21f47ed517ef2ad0c9e86076a174279cb4d1828d7250961b2bc6994ae65fd223 | Python | 2,808 | 61 | ####################################################################################################
# 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... |
0a5cb778a21ede0dc6c25e1d24d56057281637fd6604e7dbee36caeabca863ab | Python | 2,809 | 80 | import torch.nn as nn
from optuna import Trial, Study
from typing import Optional, Sequence
from argparse import Namespace, ArgumentParser
import yaml
from pathlib import Path
with open(Path(__file__).parents[1] / "config.yaml") as f:
config = yaml.safe_load(f)
class BaseModelConfig:
image_size: Sequence... |
8affcb8b4fc4f9f5510a1c4cfba0f2b06ccce47e3f135c2ea976feac034a3a20 | Python | 2,812 | 72 | from tensorflow.keras.utils import Sequence
import numpy as np
import mrcfile
import os
# Here, `x_set` is list of path to the images
# and `y_set` are the associated classes.
class dataSequence(Sequence):
def __init__(self, x_set, y_set, batch_size):
self.x, self.y = x_set, y_set
self.batch_size ... |
73a5677b1a1570e0f1bb0ba8a1773e1208dd52970c7c5f0d1f9d2a0bab42aa50 | Python | 2,814 | 55 | import numpy as np
from .isodepth_scaling import adjust_isodepth
from .cluster_plotting import plot_isodepth
import matplotlib.colors as pltcolors
def restrict_spots(counts_mat, coords_mat, S, gaston_isodepth, gaston_labels, isodepth_min=0, isodepth_max=1,
adjust_physical=True, scale_factor=1,
... |
158cd82ef0e3b69239d43706eba6db2bff1f63c87013e991a535a22ffc068e76 | Python | 2,815 | 73 | from sklearn.cluster._kmeans import *
def kmeanspp(X, n_clusters, seed=None, replace=False,
n_local_trials=1):
n_samples, n_features = X.shape
x_squared_norms = row_norms(X, squared=True)
random_state = check_random_state(None)
centers = np.empty((n_clusters, n_features), dtype=X.dtype)
... |
4e9e8d9f37b34527a8ae6f8286264f2f26e56e0f070abd7464e729c7e7818fd5 | Python | 2,815 | 100 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
"""
Filter vcf to clean, autosomal, biallelic sites prior to cohort-wide PCA
"""
import argparse
import sys
import pysam
NULL_GTs = [(0, 0), (None, None), (0, ), (None, ), (None, 2)]
def get_call_rate(record):
n_samples = len(record.samples)
n_non_null = le... |
624680c222beabd6bc9e33f9e602032e2575570ba93c07d438398e3f719a5821 | Python | 2,815 | 51 | from inference import seq_to_tensor, BS_LS_upper_lower, BS_LS_upper_lower_concat, BS_LS_pred
from pre_trained_model_structure import *
### using the function defined in inference.py to do prediction to new exon pairs
def predictions(testing_df_path, trained_model):
'''
:return: predicted circRNA (1) or linear... |
09d2856f311883a2d5047de93177d1013593c749d1fa5f7b52ec46b628f8b33e | Python | 2,816 | 76 | from typing import List, Any
import copy
import torch
from monai.inferers import Inferer
import numpy as np
from torch.nn import functional as F
from pathlib import Path
from src.networks.vqvae.baseline import BaselineVQVAE
from src.networks.transformers.transformer import TransformerBase
class LikelihoodMapInferer(... |
2e944c9a7c3e4ece07b284a1e80aa12369fa830fa42141d33ee13d2d447f9733 | Python | 2,817 | 87 | import contextlib
import warnings
from typing import Any
import matplotlib
import seaborn as sns
from pandas.plotting import (
deregister_matplotlib_converters,
register_matplotlib_converters,
)
@contextlib.contextmanager
def manage_matplotlib_context() -> Any:
"""Return a context manager for temporarily... |
3b79b07e6a94dbc4092d2d44115df7e8259ef01a3981c8c3dcc11ed0e9447da0 | Python | 2,817 | 82 | """
Compute (pre-stim normalized) response for each neuron / target.
Mean of response in evoked window.
Cache results to load for figure 2.
"""
import os
rdir = os.path.dirname(os.path.dirname(__file__))
import sys
sys.path.append(rdir)
from nems.tools import recording
import helpers.tin_helpers as thelp
from settin... |
bb67a35b218d0090aa4c944fac65813e3d0173ae1ba76f33af5241657ca8dadc | Python | 2,817 | 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... |
b4676bdb3ab38f4da712a28710d3a2b9ceb11ac4184c5bc49c72973536d5b306 | Python | 2,818 | 72 | import torch
import soft_rank_numpy
def wrap_class(cls, **kwargs):
"""Wraps the given NumpyOp in a torch Function."""
class NumpyOpWrapper(torch.autograd.Function):
"""A torch Function wrapping a NumpyOp."""
@staticmethod
def forward(ctx, values):
obj = cls(values.detach(... |
be56cc568ce35669361ca547850849e02ddf21ec7e895a29e07fa17327de573f | Python | 2,818 | 88 | """
This file serves as a documentation example and CI test.
Structure:
1. Monkeypatch setup: Ensures serve.run is non-blocking and removes accelerator requirements for CI testing.
2. Docs example (between __direct_streaming_example_start/end__): Embedded in Sphinx docs via literalinclude.
3. Test validation (deployme... |
dae131fc9031b41b8fcd6a1b2ccd499de00239eca648f6877122eb59f2dea928 | Python | 2,818 | 67 | import os
import argparse
import scipy.io as sio
import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import *
from tensorflow.keras import backend as K
import matplotlib.cm as cm
from tensorflow import keras
from skimage.transform import resize
import matplotlib.pyplot as plt
def visualize_lstm_a... |
fc8656fae9372607f104b0c96aabc3b5280d0655f6aea4a031031b7cd8eccb75 | Python | 2,818 | 78 | # -*- coding: utf-8 -*-
"""
Created on Mon Jul 3 14:27:00 2023
@author: ju-bar
Random number generation for user-defined probability distribution
This code is part of the 'emilys' repository
https://github.com/ju-bar/emilys
published under the GNU General Publishing License, version 3
"""
import numpy as np
from sci... |
5eec737a53adbb3fafdb6f41ed55b56f7572640d65f700dd6baf8a68356d8e85 | Python | 2,819 | 104 | from dataclasses import asdict
import numpy as np
import pandas as pd
import pytest
from data_profiling import ProfileReport
@pytest.fixture
def tdf(get_data_file):
file_name = get_data_file(
"meteorites.csv",
"https://data.nasa.gov/docs/legacy/meteorite_landings/Meteorite_Landings.csv",
)
... |
b33b78c44591f7425e48a41cb550b50d55be595992dac36daf563cf6b91b57ab | Python | 2,819 | 85 | #!usr/bin/python
"""Example code for using scdemon library."""
# ---------------------------------------------------------------------
# Example - compute co-expression modules using a scanpy anndata object
# Updated: 06/20/22
# ---------------------------------------------------------------------
import logging
import... |
79e3d8f1e201e2a708f0aa266fd32383d334e67e8558f3c776e14d9592d56415 | Python | 2,820 | 78 | import numpy as np
import torch
from sklearn import metrics
import dgl
import networkx as nx
def caculate_metrics(real_score, pre_score):
y_true = real_score
y_pre = pre_score
fpr, tpr, thresholds = metrics.roc_curve(y_true, y_pre, pos_label=1)
auc = metrics.auc(fpr, tpr)
precision_u, reca... |
b0dcac8057636585cb94e6f7d025be911c7427231d9ce2d029ca520980331c90 | Python | 2,820 | 66 | """CellChatDB v2 tables, exported verbatim from R CellChat 2.2.0 (``CellChatDB.<species>``).
``data/<species>_interaction.csv.gz`` keeps the R rownames as ``id`` (the LR key
R uses as ``dimnames(net$prob)[[3]]``) plus the columns the inference and the
annotations need; ``complex`` and ``cofactor`` are complete. ``gene... |
5b8d240da7776c274e9596c87785f29a2a3e4d84debdf7b493c243d3932298d6 | Python | 2,822 | 89 | from abc import abstractmethod
from typing import Optional, Sequence, Union
import torch
from rising.utils.shape import reshape
__all__ = ["AbstractParameter"]
class AbstractParameter(torch.nn.Module):
"""
Abstract Parameter class to inject randomness to transforms
"""
@staticmethod
def _get_n... |
b4c06a869431753aa1a10fec4e1806f4319913efe3ce3c531ee136b90c684322 | Python | 2,822 | 62 | import os
import numpy as np
import nibabel as nib
import ivim
root = '/path/to/results'
# Generate phantom
# 'WM','CGM','DGM','CSF'
pars = {'D': [0.85e-3, 0.95e-3, 0.90e-3, 1.70e-3], 'f': [1.5e-2, 2.5e-2, 2.0e-2, 3.5e-2], 'vd': [1.75, 1.75, 1.5, 1.5]}
dx = 15
x = 100
n = 50
seg = np.zeros((x,x,n),dtype=int)
for i in... |
6c45f22538ccfc94a10e56597f3d259bc0b8ee975a809f9a74c29b30dea8222a | Python | 2,824 | 73 | # built-in dependencies
from typing import Any, List, Tuple, Union
# 3rd party dependencies
import numpy as np
from numpy.typing import NDArray
# project dependencies
from deepface.commons.onnx_utils import build_session, run_session
from deepface.models.spoofing.FasNetUtils import crop
from deepface.commons.logger i... |
8c2864a7a03a15f976946c804792a7d75ca50826ac62b2ba68a06922c2344f62 | Python | 2,824 | 100 | from multiprocessing import Pool, cpu_count
import dill
from hic3defdr.util.progress import tqdm_avail, tqdm
def _pack_for_apply(fn, kwargs_list):
return [dill.dumps((fn, kwargs)) for kwargs in kwargs_list]
def _unpack_for_apply(payload):
fn, kwargs = dill.loads(payload)
return fn(**kwargs)
def para... |
a5453c7e23a7489a2d65ff543e88f354601a0ac26ad6bc951abdf544740fec31 | Python | 2,824 | 83 | """
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
from unittest.mock import Mock
from omegaconf import OmegaConf
from fairchem.core.launchers import sl... |
0c18cb778503f9480a153062055dd4cdc1b039125ec1739f686f4abfaff5b62a | Python | 2,826 | 63 | """Vendored copy of CAMEX (Cross-species cell-type Annotation and integration
via Multi-species EXpression graphs).
CAMEX is a graph-neural-network method for cross-species single-cell
integration and annotation. Given one AnnData per species (raw counts, gene
symbols) plus many-to-many gene-homology tables linking th... |
d564cda979b5b27533b23b5c1fcac13ca2395c30a1ee47837f94c8113134e398 | Python | 2,826 | 77 | import numpy as np
from collections import defaultdict
def get_discont_genes(pw_fit_dict, binning_output, q=0.95):
_,_,discont_mat,_=pw_fit_dict['all_cell_types']
gene_labels_idx=binning_output['gene_labels_idx']
discont_genes=defaultdict(list) # gene -> [domain boundary p], ie bounary between R_... |
3aa2ddb8568d198ee94896195b6b461d3985bd18541aeb5b7935053912598f85 | Python | 2,827 | 83 | ####################################################################################################
# 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... |
5c383763ad070f3119550cba4fb7aa25b0500291615b328a1b8a13f08ade2490 | Python | 2,827 | 109 | import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from task import CSW
from sklearn.decomposition import PCA
from utils import compute_smth_mean, to_sqnp
sns.set(style='white', palette='colorblind', context='poster')
cp2 = sns.color_palette(n_colors=2)
# setup
event_len = 4
noise = 0
reptype = '... |
cbee780beb7a121b93c4beb838205975184b1468f290fd5c865b17f155ad009c | Python | 2,827 | 83 | """Provide the functions for equilibrium sampling."""
from typing import Tuple
import numpy as np
from openmm import unit
from openmm.app import Simulation
from tqdm import tqdm
from endstate_correction.constant import kBT
def _collect_equ_samples(
trajs: list, every_nth_frame: int = 10
) -> Tuple[list, np.arr... |
311f8459bb5b2739f46ee32561725baa7a9939cac0661ef803a2675fa4ab7390 | Python | 2,829 | 69 | # -*- coding: utf-8 -*-
"""
This is implementation of model of corresponding to the pre-print `Large scale model of cat primary visual cortex`
Antolík, J., Cagnol, R., Rózsa, T., Monier, C., Frégnac, Y., & Davison, A. P. (2018).
https://www.biorxiv.org/content/10.1101/416156v5.abstract
"""
import matplotlib
matplotlib.... |
36225645d4054104a0e5e221cb540b953b6a4d7de792baef9d0deff221ad69cb | Python | 2,829 | 103 | import logging
from collections import Counter
from pokeformer.vocabs.vocab import Vocab
logger = logging.getLogger(__name__)
class ProtAtomFeature:
def __init__(self, res_name=None, atom_name=None):
if res_name is None:
return
self.res_name = res_name
self.atom_name = atom_n... |
15014ffbb24794299363671bcf8fae64f1ab3f0f21ba2adb89627577098bea6f | Python | 2,830 | 103 | from copy import deepcopy
import pytest
import torch
import torch.nn as nn
from sinabs.backend.dynapcnn import DynapcnnNetwork
from sinabs.backend.dynapcnn.chip_factory import ChipFactory
from sinabs.from_torch import from_model
ann = nn.Sequential(
nn.Conv2d(1, 20, 5, 1, bias=False),
nn.ReLU(),
nn.AvgPo... |
e38ad4d9c733858179030b2d23027e01bcd0e737d55b76f8846fcf5736d89171 | Python | 2,830 | 77 | # -*- coding: utf-8 -*-
# (C) Copyright 2020, 2021, 2022 IBM. All Rights Reserved.
#
# Licensed under the MIT license. See LICENSE file in the project root for details.
"""Conductance converter for the fusion chip."""
from typing import Dict, List, Tuple
from torch import Tensor, sign
from torch.autograd import no_... |
8b90fdff87f44fb49aef230908539f0a0b3a683d08389571ed62132b3b32dbb4 | Python | 2,831 | 78 | """
These are 'traditional' RNA velocity methods computed with scVelo.
"""
import scanpy as sc
import scvelo as scv
import numpy as np
import scipy as scp
import anndata as ad
import tempfile
import shutil
def compute_scvelo(adata_raw, min_shared_counts=30, n_top_genes=2000, n_pcs=30, n_neighbors=30, mode='both', n_j... |
5983a48a197b923dbc08b1ccc1ac5399d04b24092d36eb4f032dcf69c4552393 | Python | 2,832 | 75 | import os
import subprocess
path = "./"
gpus = 2
available = [i for i in range(gpus)]
seed_list = [1111 * i for i in range(2, 5)]
cnt = 0
def multi_task(path, parameters):
global cnt
for r in parameters["ratio"]:
for se in parameters["seed"]:
for mo in parameters["model"]:
... |
515e1b747c49e40a4e468a73cb75df12cf1bafd5542be0e959d76ad740da06d1 | Python | 2,833 | 100 | # Ultralytics YOLO 🚀, GPL-3.0 license
from pathlib import Path
from ultralytics.yolo.cfg import get_cfg
from ultralytics.yolo.utils import DEFAULT_CFG, ROOT, SETTINGS
from ultralytics.yolo.v8 import classify, detect, segment
CFG_DET = 'yolov8n.yaml'
CFG_SEG = 'yolov8n-seg.yaml'
CFG_CLS = 'squeezenet1_0'
CFG = get_c... |
1e53f45e4603d9be42c96193dc5f858978a0bfb82102497d0a19782397a7f728 | Python | 2,834 | 98 | import pytest
from siapy.core.exceptions import InvalidInputError
from siapy.datasets.schemas import (
RegressionTarget,
TabularDatasetData,
)
from siapy.utils.plots import (
InteractiveButtonsEnum,
display_image_with_areas,
display_multiple_images_with_areas,
display_signals,
pixels_select... |
6fb8e8f3b97e5213d2b9ce8e5c8526a5974ad60a4db67afd69201f848ad02198 | Python | 2,834 | 85 | """NeuralNet subclasses for regression tasks."""
import re
import textwrap
from sklearn.base import RegressorMixin
import torch
from torch.utils.data import DataLoader
from skorch import NeuralNet
from skorch.utils import get_dim
from skorch.utils import is_dataset
neural_net_reg_doc_start = """NeuralNet for regre... |
71975791656e62da0fafb88066ebb178b281b1c8b7779f536a751fadd7c40622 | Python | 2,835 | 72 | import argparse
import logging
import numpy as np
from src.config import ConfigFile
from src.model import Model
from src.pdbbind_dataset import PDBBindDataset
def parse_params(config_file=None):
try:
if not config_file:
parser = argparse.ArgumentParser(
description="Parsing o... |
943eca3c8ec3e9c6c71e765597563d8647f8c70be94a3d3dc94821cbefd04c48 | Python | 2,836 | 56 | # Python script for generating helical prior used in relion helical reconstruction. See inital steps below.
# Step 1: Within the desired PEET alignment directory, run createAlignedModel to generate updated particle coordinates.
# For example: createAlignedModel "peet_alignment_base_name.prm"
# Step 2: Run imodinfo wi... |
eeb277c0c26c5d360eff9408f82011680b2993ed2b5a75746b934e589480e6eb | Python | 2,836 | 119 | import pdb
import numpy as np
import matplotlib.pyplot as plt
import ray
from data_assimilation.particle_filter.base import BaseForwardModel
from data_assimilation.test_cases.burgers.PDE_model import Burgers
from data_assimilation.test_cases.single_phase_pipeflow_with_leak.PDE_model import PipeflowEquations
def com... |
af662460125813cc760afa9d6f36bf26f4c431640b6a58361f4bfab4dd626db5 | Python | 2,838 | 69 | import numpy as np
import torch
import torch.nn as nn
from model import Circuit, Circuit2D
from utils import find_peaks, bin_traj
class Reservoir2D(nn.Module):
def __init__(self, batch, Nx, Ny, N_out, V_min=11, V_max=13, Cth_factor=1.0, noise_strength=0.001):
super().__init__()
self.batc... |
db95e667be7636e2334b4dfa4a01b0ee1365363c674e9e41b2ec4225b1effdbf | Python | 2,838 | 89 | from convex_optim_base.unconstrained_optim import UnconstrainedSolverParams, FistaSolverParams
from convex_optim_base.prox_optim import ProxFISTASolverParams
class UnconstrainedSolverParameterGenerator:
def __init__(self,
first_niter: int = 500,
subsequent_niter: int = 1):
... |
9a2cfbb6d7574796c26af28825ebf669060ef9d185914b24fa4b1f03cb9f2ad0 | Python | 2,839 | 104 | """Check that saving and loading works with accelerate.
Especially, pay attention that both the initial model, as well as the loaded
model, could be either wrapped with accelerate or not, i.e. there are 4 possible
combinations.
"""
import numpy as np
import torch
from accelerate import Accelerator
from sklearn.datas... |
2ab488ae0a4fd4cac398a2b15323c6f5018c65cd27111b94299521d86b50bb14 | Python | 2,840 | 83 | import unittest
import numpy as np
import pytest
import torch
from pfrl.nn import empirical_normalization
class TestEmpiricalNormalization(unittest.TestCase):
def test_small_cpu(self):
self._test_small(gpu=-1)
@pytest.mark.gpu
def test_small_gpu(self):
self._test_small(gpu=0)
def _... |
e5f18fa331629e6a76b5b1fc8abae29d1521cf35c2486b5924ae5ab0726db8e2 | Python | 2,840 | 87 | import torch
from ..distances import CosineSimilarity
from ..reducers import AvgNonZeroReducer
from ..utils import common_functions as c_f
from ..utils import loss_and_miner_utils as lmu
from ..losses.generic_pair_loss import GenericPairLoss
class CircleLoss(GenericPairLoss):
"""
Circle loss for pairwise lab... |
4b7660663574f2087cd36677d26be5789e2df8ce4b5cdb8b95a5ee01d8433ba6 | Python | 2,841 | 111 | """
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.
Script for updating ase pkl and db files from v3.19 to v3.21.
Run it with ase v3.19.
"""
from __future__ import annotations
import pickle
fro... |
7e22200a2db393fc34c80b116e1be915009eeca908b68c91a93484233efc13b5 | Python | 2,841 | 87 | """
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 dataclasses
import torch
@dataclasses.dataclass
class GraphAttentionData:
"""
Custom ... |
c9c4c5aa6dddc837fec81f93dff80213b7b400041369cc94ee0fd7d060b0117a | Python | 2,841 | 63 | import os
import unittest
from tempfile import TemporaryDirectory
import numpy as np
import SimpleITK as sitk
from nnunetv2.imageio.simpleitk_reader_writer import SimpleITKIOWithReorient
# LAS storage: index x runs towards the patient's left, y towards anterior, z towards superior
LAS_DIRECTION = (1., 0., 0., 0., -1... |
dce30c67cabf0f5642c987115a8e1ed040129a1ff0583f22936bdada114c7531 | Python | 2,842 | 89 | import numpy as np
import torch
from sklearn import metrics
import dgl
import networkx as nx
def caculate_metrics(real_score, pre_score):
y_true = real_score
y_pre = pre_score
fpr, tpr, thresholds = metrics.roc_curve(y_true, y_pre, pos_label=1)
auc = metrics.auc(fpr, tpr)
precision_u, ... |
f249e6d761ae126af93c933329a4a050bb028efa46b3b9b1723952d494728006 | Python | 2,842 | 89 | """
This file serves as a documentation example and CI test.
Structure:
1. Monkeypatch setup: Ensures serve.run is non-blocking and removes accelerator requirements for CI testing.
2. Docs example (between __prefix_aware_example_start/end__): Embedded in Sphinx docs via literalinclude.
3. Test validation (deployment s... |
8b2bc9b55d396cf6398aa8e65e499218d55e72d0d87a33b3e0a9a59db7a7af78 | Python | 2,843 | 90 | import logging
import os
from typing import List, Optional, Tuple
from ray._private.accelerators.accelerator import AcceleratorManager
logger = logging.getLogger(__name__)
CUDA_VISIBLE_DEVICES_ENV_VAR = "CUDA_VISIBLE_DEVICES"
NOSET_CUDA_VISIBLE_DEVICES_ENV_VAR = "RAY_EXPERIMENTAL_NOSET_CUDA_VISIBLE_DEVICES"
class ... |
c6fa05b6d51f77e4fe9ee657d7280bc0fdaf359766e3df702f515f5875048178 | Python | 2,843 | 86 | # Vendored from `decoupler` (https://github.com/scverse/decoupler) by
# omicverse for in-tree GPU acceleration work. Original copyright by
# the decoupler authors, redistributed under decoupler's GPL-3.0
# license. Cross-module imports rewritten from `decoupler.*` to
# `omicverse.es.*` (see scripts/vendor_decoupler.py)... |
1759d3e0d226bade494e4b6a5bc9a9dec49b1a49576d4ee18bdadd2928254dda | Python | 2,845 | 58 | proj_dir = "/path/to/main_project_folder/" # edit this line
import numpy as np
import pandas as pd
import xarray as xr
import dask.array as da
import matplotlib.pyplot as plt
import glob as glob
from functools import partial
import sys
sys.path.append(proj_dir)
from project_fxns import load_region
from project_fxns im... |
63b8e27dee3f89aeadccc909dbb7848a9a2b75fee975e5ef5538f9815e9eccf2 | Python | 2,845 | 69 | import os
import numpy as np
import multiprocessing as mp
def mean_trace(nn, fn_video, video_dtype, video_shape, fn_masks, mask_shape):
''' Calculate the traces of the neuron, background, and outside region for a neuron.
Inputs:
nn (int): The index of the neuron of interest.
fn_video (str): ... |
83d5e95a3f5e92fc1d17333c2ca96653e0375f8a6db754a6e60e2cfc8d3e163c | Python | 2,845 | 80 | """Generic package-version helpers.
Small, dependency-light utilities for querying and comparing installed package
versions. Use these to gate an optional backend behind a minimum version — e.g.
so an outdated wheel with a known-bad code path can't silently degrade or stall
a pipeline. Reusable anywhere in omicverse a... |
a6c541f17bc119d99466a317217528f665bb9478766b00b8e8cca835f8051809 | Python | 2,846 | 114 | import timeit
from logging import getLogger
import numpy as np
import pytest
import torch
from torch import nn
from pfrl.utils import clip_l2_grad_norm_
def _get_grad_vector(model):
return np.concatenate(
[p.grad.cpu().numpy().ravel().copy() for p in model.parameters()]
)
def _test_clip_l2_grad_no... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.