sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
e7c2ec123213b2f41f51aebc61965b329dbe44407651aa2e2c5b6fc06657d725 | Python | 3,137 | 80 | """Precompute and store the response normalization constants of an ensemble."""
import argparse
import logging
from flyvis import Ensemble
from flyvis.analysis import response_norms
from flyvis.utils.config_utils import HybridArgumentParser
logging.basicConfig(
format="[%(asctime)s] [%(filename)s:%(lineno)d] %(m... |
08b22ab0fab2f5396e329eb195b9315a973e031082aaf2571ac84928ae70b110 | Python | 3,138 | 91 | #!/usr/bin/env python
from __future__ import print_function
import argparse
import glob
import json
import sys
import numpy as np
import os
EXCLUDED_PARTS = ['merged']
def parse_args():
parser = argparse.ArgumentParser("Consolidates output learned parameters for chunked marginPhase run")
parser.add_argument('... |
704bf22dc93eeea62afe95401e0f9f5451bf1681203a9234c3add759421eb1aa | Python | 3,141 | 92 | import re
import h5py
import torch
import argparse
import numpy as np
import os
from tqdm import tqdm
from src.data.load_data import load_params
from src.tools import load_model
from src.models.predict_model import predict_horizon
SUBS = [f"sub-0{i}" for i in range(1, 7)]
def main(args):
"""Load darts model and... |
7be5184ff6246ca17abf2634da3a04e39e04dd86425ed339454276576922ae56 | Python | 3,143 | 64 | #--------------------------------------------------------------------------------------------------------------------------------------------
# Authors:
# Brandon S Coventry Wisconsin Institute for Translational Neuroengineering
# Date: 03/26/2025 Happy Easter! Wisconsin is finall... |
ff23fa4b459e1384d07c89ebd8c194b63b8443707ea69fe059ea95522cbeb1eb | Python | 3,143 | 80 | ####################################################################################################
# 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 library is fre... |
600e8725eea4a277d1b7e5c157a085838376469b4de052bc87329f789e010778 | Python | 3,144 | 91 | import tensorflow as tf
from sklearn.model_selection import train_test_split
from synthetic_data import generate_example_timeseries
from visualisation import plot_dense_sensordata, plot_learning_curve
from data_scrambling import scramble_timeseries, format_training_set
# this flag allows two options:
# if TRAIN == Tru... |
2d2464c91e112c423d6b7ff6692e12e877d559b802697746180c6f47699c3835 | Python | 3,145 | 121 | from pathlib import Path
import pandas as pd
import numpy as np
from collections import defaultdict
import random
from scipy.stats import multivariate_normal
from scipy.stats import wasserstein_distance
import matplotlib
# matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontP... |
8371f76db10410f3c0e29bf1117eb3a7ba59c0c7740f23559e55d558b6e4b05e | Python | 3,145 | 78 | import pdb
from tqdm import tqdm
import os
import sys
sys.path.append(os.getcwd()) # Fix Python path
from torchEnKF import da_methods, nn_templates, noise
from examples import generate_data, utils
import random
import torch
import numpy as np
from torchdiffeq import odeint
import matplotlib.pyplot as plt
device = t... |
cbfa3031188d3f9324a5a82af671b1ba9b53f9686ae31d07b0682fffa8e03685 | Python | 3,145 | 75 | # 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... |
08776e8345bb4f84ead27cd239e44826d84a9520127ce43806f6823af0c0e612 | Python | 3,146 | 104 | """Utilities for handling AnnData views in dataloaders"""
def handle_adata_view(adata):
"""
Handle AnnData views by converting them to regular AnnData objects.
This avoids COO matrix issues when trying to modify views.
"""
if not adata.is_view:
return adata
import anndata as ad
fro... |
3aca87413af1d98ab136292c51255c223ddd44a87f9116a87d0a1f41a94ea255 | Python | 3,148 | 73 | # Ultralytics YOLO 🚀, GPL-3.0 license
"""
AutoBatch utils
"""
from copy import deepcopy
import numpy as np
import torch
from ultralytics.yolo.utils import LOGGER, colorstr
from ultralytics.yolo.utils.torch_utils import profile
def check_train_batch_size(model, imgsz=640, amp=True):
# Check YOLOv5 training bat... |
9d85db83d38c8fd60e119485dab79cd685dcbf1c32f84186f5e22dcf89f93abc | Python | 3,149 | 53 |
'''
rotation_list = {
0: [(((0,1),1),((1,2),1)), (((0,2),1),((1,2),1))],
1: [(((1,0),1),((1,2),1)), (((2,0),1),((1,2),1))],
2: [(((0,1),1),((1,2),3)), (((0,2),1),((1,2),3))],
3: [(((1,0),1),((1,2),3)), (((2,0),1),((1,2),3))],
4: [(((0,1),1),((1,2),0)), (((0,2),1),((1,2),0))],
5: [(((1,0),1),((1,2),0)), (((2,0),1),((1... |
a236e8e40788e0c165967a6e9f9b60d895ed86be623b01ec7cb3de48a2831853 | Python | 3,150 | 81 | #!/usr/bin/env python
# Runs "mean absolute deviation" QC metrics on two long-RNA-seq gene quantifications
import os, subprocess, json
import dxpy
def divide_on_common(str_a,str_b):
'''Divides each string into [common_prefix,variable_middle,common_ending] and returns as set (parts_a,parts_b).'''
parts_a = [''... |
ac87f1aec060f6512f2a77ef63d555ecfea2f30f5ea4615b2ac4dc2a90014f9b | Python | 3,150 | 94 | import rdkit.Chem as Chem
from mol_graph import bond_fdim, bond_features
import numpy as np
BOND_TYPE = ["NOBOND", Chem.rdchem.BondType.SINGLE, Chem.rdchem.BondType.DOUBLE, Chem.rdchem.BondType.TRIPLE, Chem.rdchem.BondType.AROMATIC]
N_BOND_CLASS = len(BOND_TYPE)
binary_fdim = 4 + bond_fdim
INVALID_BOND = -1
def get_... |
b23b67cbee7b1b1585066a92f5ea86e31485728084bcca62e4dfabd6a87c9ed2 | Python | 3,150 | 110 | #!/usr/bin/env python
"""Fit a beta-uniform mixture model to a list of p-values.
The BUM model is introduced in Pounds & Morris, 2003.
"""
import numpy as np
from scipy.optimize import minimize
def _fpLL(pars, p_values):
"""Return the gradient function of the BUM model.
Parameters
----------
pars ... |
760a471ed9e868dcb679e2061cb0ed417872cfc16b9940735a8b4435bbf5d637 | Python | 3,151 | 82 | import json
import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
def parse_requirements(file_name):
"""Read a requirements file, skipping its blank lines, comments and pip options"""
with open(file_name, "r", encoding="utf-8") as f:
lines = [line.str... |
ca1084f9ea7ed1c926bc241444b566aea3d6b7a90ad0667dc46195d79042debc | Python | 3,151 | 102 | # -*- coding: utf-8 -*-
"""
Created on Fri Aug 20 11:37:52 2023
@author: xzhou
"""
from sklearn.model_selection import ShuffleSplit
from sklearn.metrics import precision_recall_curve,auc, roc_auc_score
import numpy as np
def get_train_index(Y, train_ratio, val_ratio, test_ratio,n_splits,split_index):
... |
4dd192f6e03bcc353a20ffc65a7b3be95510c5c1377605df50c8ffa9047e35df | Python | 3,154 | 83 | # Ultralytics YOLO 🚀, GPL-3.0 license
import json
from time import time
from ultralytics.hub.utils import PREFIX, traces
from ultralytics.yolo.utils import LOGGER
from ultralytics.yolo.utils.torch_utils import get_flops, get_num_params
def on_pretrain_routine_end(trainer):
session = getattr(trainer, 'hub_sessi... |
647294462874b464b04b1143e32f92ca058775f9ddce7ca4195055d5dce5f50e | Python | 3,155 | 88 | 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=... |
6dc03314d12637ab26ed7ed2f731378a5678ef6f8b0e86f6b45b838edb845278 | Python | 3,155 | 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... |
7308f6d5d137941b9bd6a6265911c11af106ff1275a6ad286e5728281dee166f | Python | 3,155 | 106 | import sys
from unittest.mock import MagicMock, patch
import pytest
from ray.dashboard.modules.reporter.jax_profile_manager import JaxProfilingManager
from ray.util.tpu import init_jax_profiler
@pytest.fixture
def mock_profiler_client():
mock_client = MagicMock()
mock_profiler_module = MagicMock()
mock_... |
0ad87d97611cc26d5544a9864465e679c936b86d7e1d9d52ed496e4dbefc07a4 | Python | 3,156 | 93 | THRESHOLD="random"
SEQ_LEN = "800"
HALF_SEQ_LEN = int(SEQ_LEN) // 2
QUATER_SEQ_LEN = int(SEQ_LEN) // 4
def main():
fw = open("../INPUTS/"+SEQ_LEN+"bp/input_neg_"+str(THRESHOLD)+".fa", "w")
fr_donor = open("./NEG_rev_junctions/"+SEQ_LEN+"bp/donor/donor_seq.fa", "r")
fr_acceptor = open("./NEG_rev_junctions/"+... |
95dd0d2ae105919d305e682209d4b14dffe5bb61f13ddab7fb4dff089330e96a | Python | 3,161 | 102 | from typing import Dict, Optional, Tuple
WORKING_DIR = "working_dir"
PY_MODULES = "py_modules"
ZIP_EXTENSION = ".zip"
WHEEL_EXTENSION = ".whl"
JAR_EXTENSION = ".jar"
TAR_GZ_EXTENSION = ".tar.gz"
TGZ_EXTENSION = ".tgz"
TAR_BZ2_EXTENSION = ".tar.bz2"
TAR_XZ_EXTENSION = ".tar.xz"
# These are the user-facing formats acc... |
db64033ad9405142cba63b33dc724985c9af8c5c8765b95363057ab4e8fe8405 | Python | 3,161 | 122 | import ray
ray.init(num_cpus=64)
# __default_scheduling_strategy_start__
@ray.remote
def func():
return 1
@ray.remote(num_cpus=1)
class Actor:
pass
# If unspecified, "DEFAULT" scheduling strategy is used.
func.remote()
actor = Actor.remote()
# Explicitly set scheduling strategy to "DEFAULT".
func.options... |
3c7baefc4c5b54453ee58aa37af6789b670f0c274a01546172afb18d50fb5464 | Python | 3,163 | 109 | ###############################################################################
'''This parser takes as input the .h5 file produced by create_datafile.py and
outputs a .h5 file with datapoints of the form (X, Y), which can be understood
by Keras models.'''
###############################################################... |
7b5b5e24aca6556244673c040fc35271f9d24ddb106f30e90fa1855f098de0c5 | Python | 3,164 | 84 | import sys
import os
from os.path import join as opj
from os.path import dirname as opd
from typing import Dict, Union
import time
from torch.utils.tensorboard import SummaryWriter
import torch
import numpy as np
import random
timestamp = time.strftime("_%Y_%m%d_%H%M%S")
class MyLogger():
def __init__(self, proje... |
cbd5a3f963ee7bc72261fb6a1b424761c5131ae82587efef1d0e799e26407827 | Python | 3,166 | 78 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Python version: 3.10.9
pandas version: 1.5.0
"""
#%% Import Modules
import pandas as pd
import warnings
from pathlib import Path
import glob
warnings.filterwarnings("ignore")
#%% Functions
def retain_quantile(data, percentile=0.9):
percentile_val = data[3].quanti... |
b9ec73c46f645d515a7a852c6e05e53ada8fa97b832271808dca429a9e2dc243 | Python | 3,167 | 106 | """
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.
Functions to run elasticity calculations using ASE + pymatgen
- Compute elasticity tensor
- Compute Bulk modulus
- Compute Shear modulus
"""
... |
70c64dc566bb4767236a3ed8e03c0fc450778605b3ce77488d8a5c58e50a2f3e | Python | 3,168 | 61 | import torch
def scale_pos(pos_cartesian, primitive_vecs):
'''
Calculate scaled positions from Cartesian positions.
'''
return torch.matmul(pos_cartesian, torch.inverse(primitive_vecs)).to(pos_cartesian.dtype)
def wrap_pos(pos_cartesian, primitive_vecs):
'''
R = P * V
R is positions ... |
832e4f89ea6fda8dd461271bcdaf808ccf07ad956d8875b6448dd1b8ff540977 | Python | 3,168 | 94 | import collections
import pickle
from typing import Optional
from pfrl import replay_buffer
from pfrl.collections.random_access_queue import RandomAccessQueue
class ReplayBuffer(replay_buffer.AbstractReplayBuffer):
"""Experience Replay Buffer
As described in
https://storage.googleapis.com/deepmind-media... |
12bac90e8886cc237bcf8839747db50394b1efb7ad21f94df4b11cc68d4e08e4 | Python | 3,169 | 101 | from typing import Callable, Iterator, Optional, TypeVar
from ray.data._internal.block_batching.interfaces import ResolvedBlock
from ray.data._internal.block_batching.util import (
_MappingIterator,
blocks_to_batches,
collate,
format_batches,
)
from ray.data._internal.stats import DatasetStats
from ray... |
c2203885a9941a510246eff85a71578f6808a506c7f572f8cfcfe75567b78ee9 | Python | 3,171 | 78 | """Codegen / tool-dispatch facade mixin — residual compatibility surface.
After task-049 rewired ovagent consumers (TurnController, ToolRuntime,
AnalysisExecutor, SubagentController) to hold direct subsystem references,
the majority of the original ~45-method delegation surface became dead code.
This mixin now retain... |
0b47801317230ec56647da4580fd92669fb1202d65fc30ddc23ebddb6b7c7915 | Python | 3,172 | 85 | # Ultralytics YOLO 🚀, GPL-3.0 license
import torch
from ultralytics.yolo.engine.predictor import BasePredictor
from ultralytics.yolo.engine.results import Results
from ultralytics.yolo.utils import DEFAULT_CFG, ROOT
from ultralytics.yolo.utils.plotting import Annotator
class ClassificationPredictor(BasePredictor):... |
efa592b21974173a4ddc5f232b02375081c6e6add76c687c81819b51b8f7672e | Python | 3,172 | 129 | import torch
import torch.nn as nn
import torch.nn.functional as F
class A2C(nn.Module):
"""a MLP actor-critic network
process: relu(Wx) -> pi, v
Parameters
----------
dim_input : int
dim state space
dim_hidden : int
number of hidden units
dim_output : int
dim acti... |
63159361215502495ebe3615c9eb470509d5d87a6faf1cd9fe5a171e92d3382e | Python | 3,173 | 78 | 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... |
f6e107b44d50fb9633077c799f1a25c4cf8d627dde7c210aba2af860cdb45bc0 | Python | 3,173 | 73 | import sys
import json
import pickle
import argparse
from lop.utils.miscellaneous import *
from lop.utils.plot_online_performance import generate_online_performance_plot
def add_cfg_performance(cfg='', setting_idx=0, m=2*10*1000, num_runs=30, metric='accuracy'):
with open(cfg, 'r') as f:
params = json.loa... |
75d79f43b515c3369a86211aa0540a41e40dbb07f6c7b0d1b445932be1db6a93 | Python | 3,176 | 87 | # -*- coding: utf-8 -*-
from mozaik.storage.datastore import PickledDataStore
from mozaik.controller import Global
from parameters import ParameterSet
import mozaik
from mozaik.controller import setup_logging
import sys
from msa_analysis_plotting import *
from mozaik.storage.queries import *
# Usage:
# If all radii in... |
7c940c3470b9bd6222fccfa4af371a29e86e38669bff8bd646ca9cc85c54926a | Python | 3,176 | 86 | #!/usr/bin/env python3
# Copyright (c) 2020-2022, NVIDIA CORPORATION. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted
# provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright ... |
958d0eee218d601c2f099f56df329eec0f2195eee2e14dbfe08c98ccb1eee024 | Python | 3,177 | 111 | """An executable for finding close-fit boundaries between cortical layer
polygons.
"""
import logging
import copy as cp
from functools import partial
import shapely
from argschema.argschema_parser import ArgSchemaParser
from neuron_morphology.snap_polygons._schemas import (
InputParameters, OutputParameters)
fr... |
9b0b6c8647adb6bdc6a8909aac7e408219a797b20aa9de888b14753a2bfa9a7a | Python | 3,177 | 90 | import tifffile
from magicgui import magic_factory, magicgui
import tifffile
import napari
import os
from napari.utils.notifications import show_info
from inference import InfConfig, get_trained_model_config, get_trained_model, denoise_data
def get_denoised_img_path(noisy_img_path):
path_split = noisy_img_path.... |
d0d6c5c71d33be187b982801b7210c06e592eb7f79c68742f59f1d257b6c7cd7 | Python | 3,179 | 121 | # These are canonical sets of parameters for different types of pipelines.
# They are set on subclasses of `PipelineTesterMixin` as `params` and
# `batch_params`.
#
# If a pipeline's set of arguments has minor changes from one of the common sets
# of arguments, do not make modifications to the existing common sets of a... |
eafc0a2e774babd27ea3411c5e988ca92c96db27abe7114000b1ded4642d3a16 | Python | 3,179 | 99 | r"""
Bulk-to-single-cell deconvolution and mapping utilities.
This module provides comprehensive tools for bridging bulk and single-cell omics data:
- Converting bulk RNA-seq data to single-cell resolution using deep learning
- Deconvolving cell-type proportions from bulk samples
- Mapping single-cell data to spatial ... |
78602fd3063bf4326fef76cee34b3ce35856255d4db51507c4414069a81351c0 | Python | 3,181 | 93 | import glob
import importlib
import os
import shutil
import time
import warnings
import matplotlib
import numpy as np
import torch
import ldctinv.utils.auxiliaries as aux
from argparser import make_parser, use_config
torch.autograd.set_detect_anomaly(True)
import wandb
matplotlib.use("Agg")
os.environ["WANDB_START... |
8fa704fd79f647fc4634322337195bcb6cf8b53796014510e11566073ce26ba4 | Python | 3,181 | 102 | # stdlib dependencies
from typing import List, Union, Any
# 3rd party dependencies
import numpy as np
from numpy.typing import NDArray
# project dependencies
from deepface.models.facial_recognition.tf import VGGFace
from deepface.models.demography.DemographyUtils import find_apparent_age
from deepface.commons import ... |
ceaad3fbcfc13a0deb01044a96b69e4c4f90b53a52750bed4c7eb0d540efb1e5 | Python | 3,183 | 130 | 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_sensor(params, constants, init_conditions, SC, Gain, dt, ts):
nt=ts.shape[0]
nn=SC.shape[0]
ns=Gain.sha... |
1db2f50195bfde132f1c7e034f435e84488f4b046f7d3c8e640c04ccc43ad09a | Python | 3,184 | 94 | from model.attention import *
import torch.nn as nn
def make_model(args, parent=False):
if args.dilation:
import dilated
return ENLCN(args, dilated.dilated_conv)
else:
return ENLCN(args)
class ENLCN(nn.Module):
def __init__(self, args, conv=common.default_conv):
super(ENL... |
904e298801cbe7a348ae722735ed8bf2f4f9be3f147855f273389920f7354818 | Python | 3,184 | 112 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
"""
"""
import numpy as np
class TrainingLabeler:
def __init__(self):
pass
def label(self, metrics):
return metrics.apply(self.label_row, axis=1)
def label_row(self, row):
return 'Unlabeled'
class BAF1TrainingLabeler(TrainingLa... |
ce92a93f81843bed4795e0eabc454fb92f78736cba6384d21b412a0e7ed7a552 | Python | 3,185 | 112 | # Copyright 2023 The HuggingFace Inc. 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 appl... |
28c3c2e4e4e95c99f7e9ae76b9454b16867674cd787b5245e796661c78fc9e85 | Python | 3,186 | 73 | r"""Cell segmentation for spatial transcriptomics — ``ov.space.seg``.
One entry point per input type, so methods can be swapped and compared on the
same sample, as in the Nature Methods 2026 benchmark of segmentation methods
for spatial transcriptomics (Martinez-de-Morentin et al.)::
import omicverse as ov
o... |
51cd99197293cf368e88bf059d220098eaa57b9336cfbb91b8168711b4412834 | Python | 3,186 | 101 | import torch
from ..reducers import DivisorReducer
from ..utils import common_functions as c_f
from ..utils import loss_and_miner_utils as lmu
from ..losses.base_metric_loss_function import BaseMetricLossFunction
class MarginLoss(BaseMetricLossFunction):
def __init__(
self,
margin=0.2,
nu... |
66d9039bd1453ee43e91308016248bfd8e47e163b87d5638d9225152d0070012 | Python | 3,186 | 78 | import os
import cv2
import argparse
import numpy as np
from glob import glob
from tqdm import tqdm
import multiprocessing as mp
from PIL import Image, ImageDraw
from torchvision.transforms import RandomAffine, CenterCrop, Compose, Resize
from joblib import Parallel, delayed
ap = argparse.ArgumentParser()
ap.add_argu... |
8246064e51e523108f41676eeeb2dce794bc66f74162573d56b39e8227db3d18 | Python | 3,187 | 125 | """This file add the console interface to the package."""
import argparse
from pathlib import Path
from typing import Any, List, Optional
from data_profiling.__init__ import ProfileReport, __version__
from data_profiling.utils.dataframe import read_pandas
def parse_args(args: Optional[List[Any]] = None) -> argparse.... |
4b3413a5423dcabfe2809ccffdfa10914b2387ed51b54cb1a9dadd0afa7322dc | Python | 3,189 | 85 | from fractions import Fraction
import numpy as np
import pytest
from stl import mesh
from .test_mesh_mass_conversion import box
from .test_mesh_mass_mixed import subdivide
from .test_mesh_mass_sliver import _unit_cube
def same_winding_parts():
ordinary = subdivide(box([0, 0, 0], [2.0**67] * 3))
narrow, _, ... |
5e0d4299c7d82a81a051d62df90f48fb3b0cf1d20aa3bc2f05976786d567321e | Python | 3,190 | 86 | # -*- coding: utf-8 -*-
# (C) Copyright 2026 IBM. All Rights Reserved.
#
# Licensed under the MIT license. See LICENSE file in the project root for details.
# pylint: disable=invalid-name, no-name-in-module, import-error
"""Tests for the AIHWKIT extension module ."""
from unittest import skipIf
from torch import Te... |
a9d8165dd15752d62c2c90147534cb7919fe4adcfee05a78ea051114b7887c77 | Python | 3,190 | 133 |
import math
import numpy as np
import pandas as pd
import torch
import torch.autograd as autograd
import torch.optim as optim
import matplotlib.pyplot as plt
import pdb
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
class RBF(torch.nn.Module):
def __init__(self, sigma=None):
super... |
aaeafb7079dceda1bb03a5453e4bb37ffae2fa0fc6c53a7f6d6c3605b56fa30a | Python | 3,190 | 92 | # built-in dependencies
import os
import hashlib
import importlib
from typing import List
# 3rd party dependencies
import pytest
# project dependencies
from deepface.modules import modeling
from deepface.commons.logger import Logger
logger = Logger()
# emotion model is small enough to download its weights from ever... |
4a9048be40891aeab17c79bf4c4cd84899dd900e9dc84371d86f217361ff4f02 | Python | 3,191 | 106 | import cv2
import numpy as np
from calibration2 import calib
import open3d as o3d
import matplotlib.pyplot as plt
def getDisparity(img0,img1,stereo):
return stereo.compute(img0,img1)
def loadImg(path0,path1):
img0 = cv2.imread(path0)
img1 = cv2.imread(path1)
#CHECK DATASET
#img0 = cv2.rotate(img0... |
8d5faf2415abb83fffad5c399f8b135eca573248d22ebfacbfb0ed78dfafc4f7 | Python | 3,191 | 91 | #!/usr/bin/env python3
import sys
import mrcfile
args = sys.argv
from IsoNet.util.filter import maxmask,stdmask
import numpy as np
#import cupy as cp
import os
def make_mask_dir(tomo_dir,mask_dir,side = 8, density_percentage=30,std_percentage=1,surface=None):
tomo_list = ["{}/{}".format(tomo_dir,f) for f in os.li... |
2a9b0a5f732eb40d192905cfb5a4a3c931c69042a3d608ef44180e7e2c8839e3 | Python | 3,192 | 79 | 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... |
8edb5103aaed7846f6af774ffeb9808f7e298a0f229b11a3c0da1fb4761e08ad | Python | 3,193 | 85 | import numpy as np
import pandas as pd
import argparse
from model.model import deepires_model
from model.sequence_encode import get_data_onehot
import warnings
from Bio import SeqIO
import os
def read_fa(path):
res = {}
records = list(SeqIO.parse(path, format='fasta'))
for x in records:
... |
0036bdd037d1c1e026a79e3e4411ffd72de5c9e3c1d0c46d958a1feb299ecf6b | Python | 3,194 | 88 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 12 14:15:25 2019
@author: gary
"""
import numpy as np
import matplotlib.pyplot as plt
import skvideo.io
import skvideo.datasets
from skimage.morphology import watershed
from skimage.morphology import skeletonize,medial_axis
from scipy import ndimag... |
70a46c298e340318c493bce2b924ca3601a38b3fc6ff3a93e9105931e502e431 | Python | 3,194 | 100 | from typing import (
Sequence, Set, AbstractSet, List, Optional, Type, Union, Iterable,
Mapping, Any)
import logging
import collections
from neuron_morphology.feature_extractor.mark import Mark
from neuron_morphology.feature_extractor.marked_feature import (
MarkedFeature, Feature
)
from neuron_morphology.... |
84721af033f08f92627e8072b18728447f2b1568882de820d5518f66b5ac4299 | Python | 3,195 | 71 | ####################################################################################################
# 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... |
3cf18301f7374c6d7be8bdee625afd2934c0e597005c57ead2569ffa1d525201 | Python | 3,196 | 89 | import nir
from functools import partial
# from _lava_rnn import from_nir as from_nir_to_lava
import sys
sys.path.append("/Users/steve/Code/NIR/paper")
from nir_to_lava import import_from_nir as from_nir_to_lava_full, ImportConfig, LavaLibrary
import torch
import numpy as np
from torch.utils.data import DataLoader
from... |
9dd51b66f3ae62834cac7e4834cbd2e5fd739dfca99b8854192829eae3782b7f | Python | 3,197 | 88 | import logging
from ray.data._internal.datasource_v2.interfaces.file_manifest import FileManifest
from ray.data._internal.datasource_v2.interfaces.file_partitioner import (
FilePartitioner,
PartitionHints,
)
from ray.data._internal.datasource_v2.interfaces.in_memory_size_estimator import (
InMemorySizeEsti... |
b957f128bf4d50d3d16590c6e0016092f1babc48403bfdaa4d05769e69ee46e2 | Python | 3,198 | 88 | # built-in dependencies
from typing import Any, cast
# 3rd party dependencies
import numpy as np
from numpy.typing import NDArray
import torch
from torch import nn, Tensor
# project dependencies
from deepface.models.Demography import Demography
from deepface.models.facial_recognition.pytorch.VGGFace import VggFaceBas... |
32b96ab3b4b76fcb8856f489ac778402eb674d3e431db31143c20f91cd2ce286 | Python | 3,199 | 87 | # -*- coding: utf-8 -*-
# (C) Copyright 2020, 2021, 2022 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 modif... |
3475d1c47e72ac35542dad0ce433392a00d4c60f9d710c1e8a1a428cb24dedf9 | Python | 3,200 | 107 | import logging
import pytest
from pfrl.explorers import epsilon_greedy
@pytest.mark.parametrize("start_epsilon", [1.0, 0.5])
@pytest.mark.parametrize("end_epsilon", [0.5, 0.1])
@pytest.mark.parametrize("decay", [0.99, 0.1])
@pytest.mark.parametrize("steps", [1, 100])
class TestExponentialDecayEpsilonGreedy:
@py... |
f01cdc1acd9c4f0417836813046f9ae8cbd1d004d79fb127456f59a7c7a627d5 | Python | 3,200 | 83 | import pytest
import torch
from sinabs.backend.dynapcnn.dynapcnn_network import DynapcnnNetwork
from tests.hw_utils import find_open_devices, supported_device_types_for_testing
from .conftest_dynapcnnnetwork import (
args_DynapcnnNetworkTest,
args_DynapcnnNetworkMappingTest,
)
@pytest.mark.parametrize(
... |
5fb15c354d9ec3169519d44d2f669320a0e7b5f54383d4f3acd57df9a5570b31 | Python | 3,201 | 86 | """
Data concatenation.
Input:
1. data
2. patient included
3. length of info of patient (number of visits)
4. visit list
5. feature list
Output:
1. sequential data of patient
2. median of variable
3. median of variable of patient
"""
import pandas as pd
import numpy as... |
e30dc6fe408b5f7d97123f128102a372303b5c5314cedb16cce65a6616aca96b | Python | 3,201 | 79 |
'''
Cropping upsampled UNI image to sphere.
'''
import os
import subprocess
import glob
SUBS = ['sub-05']
DATADIR = '/Users/sebastiandresbach/data/neurovascularCouplingVASO/Nifti/derivatives'
BBOX = {'sub-05': {'RH': {'xlower': 435, 'xrange': 162, 'ylower': 55, 'yrange': 162, 'zlower': 95, 'zrange': 158},
... |
70228ff27046d774fdf1f95c5b9b3cbf191c61a8f2eacce9bc090206012fa81d | Python | 3,202 | 102 | r"""Shared ESM (Evolutionary Scale Modeling) plumbing for the protein layer.
Loads `fair-esm <https://github.com/facebookresearch/esm>`_ models once, caches
them per (name, device), and points the torch-hub download cache at
``~/.omicverse/synbio_weights`` (override with ``OMICOS_SYNBIO_WEIGHTS``) so the
2–3 GB checkp... |
9efaecd17329edf32909b724db6e1b8a4c2d1c83997dffbcf08d407a4527d7c7 | Python | 3,202 | 94 | import warnings
import numpy as np
import pandas as pd
from tqdm import tqdm
from scipy import optimize, stats
def impulse(t, h0, h1p, h2, t1, t2, beta):
''' A parametric impulse function defined by two conjoined sigmoids.
See ImpulseDE2 paper.
'''
return 1. / (h1p + 1) * \
(h0 + (h1p - h... |
e95389916f77efe3f135ed367882249104ef6f44804088e6919e3a3bf32da95a | Python | 3,202 | 113 | # -*- encoding: utf-8 -*-
from setuptools import setup, find_packages, Extension
import glob
import ast
import os
import io
import re
try:
from Cython.Distutils import build_ext as _build_ext
from Cython.Build import cythonize
HAVE_CYTHON = True
except ImportError:
from setuptools.command.build_ext imp... |
f38bfd577a273edde9422a08976dae411262adf2774f794a33ab53bff0839881 | Python | 3,203 | 85 | from pathos.pools import ParallelPool as Pool
from itertools import product
import numpy as np
from lgca import get_lgca
from tqdm import tqdm
PATH = '.\\data\\gog\\nonlocaldensity_5more_reps\\'
def iteration(args):
from pickle import dump
index, kwargs = args
lgca = get_lgca(**kwargs)
lgca.timeevo(kw... |
fa5fdd0b3dc5eeee2274b12530c59ea1ffe1cb6c11b6dcd44958ee1bd1cd0cf6 | Python | 3,205 | 113 | """Plotting utility functions."""
import base64
import uuid
from io import BytesIO, StringIO
from pathlib import Path
from typing import List, Optional, Tuple
from urllib.parse import quote
import matplotlib.pyplot as plt
from matplotlib.artist import Artist
from data_profiling.config import Settings
def hex_to_rgb... |
ff143977ce458e962929aadaafc3740ec0060286f3b8537ce47dbc2a88475294 | Python | 3,205 | 86 | 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=... |
25bba228f86910806699af5bbbc0db5c018c85cefd55d131bd420f601641a045 | Python | 3,208 | 95 | #
# 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... |
29a46add4a41307df2e0ba2de4a1776530b96ba9668d6c508fb0ccaf771d175c | Python | 3,208 | 95 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
"""
"""
import argparse
import pandas as pd
def make_combinations(genic, genelists, noncoding, functional):
# Assign all variants ANY effect and ANY genelist
any_variants = genic.copy()
any_variants['effect'] = 'Any'
any_variants['gene'] = 'Any'
a... |
56ddb78e67603695aa95aed31e687d03d8c312f42f20680600b0d21a6645cb16 | Python | 3,208 | 96 | #!/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... |
580250a75dc7395bf3c7311f0367eb4eca5eeb94bac979e3c74e6a3b1d74800c | Python | 3,208 | 86 | #
# 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... |
60b9041b77c0e673b0dfaf6647726a0a0e7dc7c64271d265e7e5a329e43bd00f | Python | 3,208 | 90 | '''
Because the functional data in upsampled space is a burden to handle, we will
mask it with the sphere that we focused the segmentation on. For this, the sphere
has to be in functional space.
'''
import glob
import os
import subprocess
subs = ['sub-06']
# Define data dir
DATADIR = '/Users/sebastiandresbach/dat... |
918097be2a9aee8fab0bdf87491a79d708a4cd2e70d729f7a2e945c50ada210e | Python | 3,210 | 84 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
"""
Annotate resolved SV with genic effects and noncoding hits.
This tool permits the user to provide a GTF of Gencode gene annotations, a BED
of noncoding elements, or both. The BED of noncoding elements must contain four
columns: (chrom, start, end, element_class).
T... |
516497bd89b0555cf2fc95b5447bd83568d62581e357c0bc56d6685659827dd9 | Python | 3,211 | 94 | # Key to denote the preprocessor in the checkpoint dict.
PREPROCESSOR_KEY = "_preprocessor"
# Key to denote the model in the checkpoint dict.
MODEL_KEY = "model"
# Key to denote which dataset is the evaluation dataset.
# Only used in trainers which do not support multiple
# evaluation datasets.
EVALUATION_DATASET_KEY... |
539466b07109cd1416b1e4046a4de7ad805810bdee6d151d1fa547cbb9ce5c20 | Python | 3,211 | 74 | import argparse
from typing import List
import numpy as np
import lib.dataset_config_parser.dataset_config_parser as dcp
import lib.data_utils.dynamic_data_util as ddu
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Count the number of trials in each data partition')
parser.add_arg... |
667b6face37456df894d230ca169b0d260aa3efd532af9c1ab0fd4d361906cf8 | Python | 3,211 | 87 |
"""
***
built as part of the Russell Ray Lab Breathing And Physiology Analysis Pipeline
***
Breathe Easy - an automated waveform analysis pipeline
Copyright (C) 2022
Savannah Lusk, Andersen Chang,
Avery Twitchell-Heyne, Shaun Fattig,
Christopher Scott Ward, Russell Ray.
This program is free software: you can redis... |
b5457acebd93db2d9d50adeed73640d1bd3e1b19ecf15f962ff9f037c9f60f41 | Python | 3,211 | 103 | """
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 numpy as np
import pytest
import torch
from fairchem.core.modules.evaluator import (
Evalua... |
547c92774aeca3a4a25ca0d061d01bb1115c84a7e475c40f0cc6ebfd759a7580 | Python | 3,212 | 82 | import torch
import torch.nn as nn
import numpy as np
import torch.optim as optim
import itertools
from model.warplayer import warp
import torch.nn.functional as F
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def conv(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1):
... |
82455dc2de5bb7217518d1660a14d87e9581880f3a87b1e4d45ad90b16874e3a | Python | 3,213 | 99 | #! /usr/bin/env python3
"""
Generates Bazel resource flags by cross-referencing cgroup limits with a
RAM-per-job ratio to prevent OOM kills in containerized environments.
"""
import argparse
import math
import os
from pathlib import Path
DEFAULT_RESERVE_MB = 2048
DEFAULT_MB_PER_JOB = 3072
def get_system_ram_mb() ->... |
997b620a6c5b589e0e2203cf76fd0c9648448387cb6b53adaf9b22353bd3bdf4 | Python | 3,213 | 79 | import pytest
import numpy as np
from reval.utils import kuhn_munkres_algorithm, _build_weight_mat, compute_metrics
@pytest.mark.parametrize(
"true_lab, pred_lab, expected_type, expected_output",
(
# standard list
([0, 0, 0, 1, 1, 1], [1, 1, 1, 0, 0, 0], np.int64, np.array([0, 0, 0, 1,... |
47d1d31bc5e7bd216b77008a965d255461d7ca8e51d8717b3e35ccf8fad2a3f6 | Python | 3,214 | 103 | import numpy as np
__all__ = [
'evaluate_unsupervised',
'clustering_coef',
'coverage',
'density',
'conductance',
]
def evaluate_unsupervised(Z_pred, adj):
return {'coverage': coverage(Z_pred, adj),
'density': density(Z_pred, adj),
'conductance': conductance(Z_pred, ad... |
a15263a4de1e9a65b18d0346dc3a139bfb05663d243cf8695527bde122220aa3 | Python | 3,214 | 114 | import argparse
import json
import os
import re
import numpy as np
from tqdm import tqdm
from utils.chemistry_parse import canonical_smiles, clear_map_number
CANON_CACHE = {}
REAL_ANSWER_CACHE = {}
RESULT_FILE_RE = re.compile(r'^\d+-\d+\.json$')
ARG_KEYS_TO_MATCH = (
'model_arch_path',
'data_path',
'che... |
67f4ef25ba633e62ed193ecce98b126002f5575cf1a0a44007843746032b0e49 | Python | 3,215 | 107 | import json
from collections import defaultdict
import tables as tb
def rapppid_to_deepppi(
dataset_path, c_type, train_path, test_path, val_path, metadata_path
):
rapppid_dataset = tb.open_file(dataset_path)
metadata = rapppid_dataset.root.metadata
cols = metadata.colnames
rows = [row[:] for ro... |
d47d06ce7712fb77856e7b3560c14285f442c68891b1fe66ea3cf2c920e1c76a | Python | 3,215 | 86 | import exputils as eu
import numpy as np
import os
from glob import glob
def save_dict_to_numpy_files(data, path='.', mode = 'npy'):
"""
Saves the data in a dictionary to numpy files. Either several npy or one npz (compressed or un-compressed).
:param data: Dictionary with data.
:param path: Path to ... |
77b899a7859f4b83a51f8d1fffb2740a7491f262122e0e07017c6cfda1a9dec8 | Python | 3,217 | 66 | ####################################################################################################
# Copyright (c) 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 free softw... |
76af73d2b531eedad4d17676d29a054e14c8c474104eaf7c921df3ca6aa207e2 | Python | 3,218 | 114 | from argschema.schemas import ArgSchema, DefaultSchema
from argschema.fields import (
InputFile, OutputFile, String, Nested, List, Int, Float, Bool)
from marshmallow import ValidationError
class DepthField(DefaultSchema):
gradient_field_path = InputFile(
description=(
"The path to an xarra... |
b0ef534c558612943a5891b2ef0987267036a1b19dc72ab0018691dc409a90d2 | Python | 3,218 | 88 | # -*- coding: utf-8 -*-
# File : replicate.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 27/01/2018
#
# This file is part of Synchronized-BatchNorm-PyTorch.
# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
# Distributed under MIT License.
import functools
from torch.nn.parallel.dat... |
02de865c8977c9c89b768c0df3370ba3dec9feceb029cbcabe92bb5b8d46b71c | Python | 3,219 | 113 | # 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... |
4b62ae7f30d76a8f6c962a0b7c0d493a939dd1cfbbc6005e839a304463b83fbc | Python | 3,220 | 112 | import numba
import numpy as np
from scipy.sparse import csc_matrix
from tqdm import tqdm
from cellnet.tabnet.tab_network import TabNet
@numba.njit
def _get_nnz_idxs_per_row(x: np.ndarray):
nnz_idxs = []
for ix in range(x.shape[0]):
nnz_idxs.append(np.where(x[ix, :] > 0.)[0])
return nnz_idxs
d... |
9c653099257f6602a5d5edb5b83e6651f856b415dac39c283915a2ed3eb9b3ef | Python | 3,220 | 120 | import os
import numpy as np
import pandas as pd
import scanpy as sc
_ROOT = os.path.abspath(os.path.dirname(__file__))
def get_data(path):
"""Get absolute path relative to package installation for loading static files.
:param path: (str) relative path to items
:return: (str) absolute path to items.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.