sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
1e85c0d4c100ba5c1d03795e47699ab023e2a2dc7267a4d94524b64a41c57adf | Python | 879 | 38 | from numpy import isnan
from pytest import raises
from wonambi import Dataset
from .paths import ns2_file, ns4_file, nev_file
def test_blackrock_ns4_00():
d = Dataset(ns4_file)
data = d.read_data(begsam=10, endsam=11)
assert data.data[0][0, 0] == 3463.0878627887814
def test_blackrock_ns4_01():
d = ... |
f7f151ae22ba1b5dd2901c390dcff6bff1b54dae4d451fc05e3ec40a9fc52769 | Python | 879 | 11 | #----------------------------------------------------------------------------------------------------------------------------
# Author: Brandon S Coventry CAP Lab Purdue University Weldon School of BME
# Date: 09/02/20
# Revision History: N/A
# Purpose: This is the setup file to get spiking reinforcement learni... |
a42cf788ee0f5d6708d852c358e3962bbcfea711f669bf5fc25b6d5873e77169 | Python | 880 | 34 | """
Generate the code reference pages and navigation.
You never have to run this manually!
"""
from __future__ import annotations
from pathlib import Path
import mkdocs_gen_files
nav = mkdocs_gen_files.Nav()
for path in sorted(Path("src").rglob("*.py")):
module_path = path.relative_to("src").with_suffix("")
... |
f2165a422d9e9eaab40558e30964c055159f3b8370c70ccfc83a14d011951b21 | Python | 880 | 33 | import torch
import pandas as pd
import lightning.pytorch as pl
from datamodule import SeqDataModule
from pathlib import Path
def save_predict(trainer: pl.Trainer,
model: pl.LightningModule,
data: SeqDataModule,
save_dir: Path,
pref: str = ""):
... |
f352a8ae08fa4a68858d8ad52b9a3a89eed91b46c9886a3a872da364dc8f044e | Python | 880 | 29 | from __future__ import division, print_function
from ast import arg
import numpy as np
from topaz.utils.star import threshold_star_particles
name = 'star_particles_threshold'
help = 'filter the particles in a .star file by score threshold'
def add_arguments(parser):
parser.add_argument('file', help='path to inp... |
5ae2add0a2743228f50b6e2d19574479951fa05bb4c4e8fe1ba05f507f3b1530 | Python | 881 | 35 | import torch
import torchvision
from pycox.models.loss import CoxPHLoss
from data.constants import NUM_CLASSES
def CoxPH(log_h, events, duration):
loss = CoxPHLoss()
return loss(log_h, events, duration)
def focal_binary_cross_entropy(logits, targets, gamma=2):
l = logits.reshape(-1)
t = targets.resha... |
9eda3a889213af072f25d8b473e7b6e2c4334a28f3e7d9f06286d6cb9c0a7e2b | Python | 881 | 30 | import json
import zarr
from cirrocumulus.abstract_backed_dataset import AbstractBackedDataset
from cirrocumulus.anndata_util import dataset_schema
class ZarrDataset(AbstractBackedDataset):
def __init__(self):
super().__init__()
def get_suffixes(self):
return ["zarr"]
def is_group(self... |
d1b467940a4a036747620f78bc89af09cee9dbdb9f137c93486a7baad08f73f0 | Python | 881 | 28 | from plantsegtools.utils.io import smart_load, create_h5, create_tiff
import os
import argparse
def parse():
parser = argparse.ArgumentParser()
parser.add_argument("--seg-path", type=str, help='path to segmentation file')
parser.add_argument("--seg-dataset", type=str, default='segmentation', help='interna... |
46e56ab08d354d69b7d5d806a4b8b60cd2bf5e3eecb51e1531ac84eb28d221c4 | Python | 882 | 21 | """
Copyright (C) 2020 Intel Corporation
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 wri... |
7145c9e7f5063cf4c00c46210f00d75481b1d12cdc55be036d758bc677c5b6c6 | Python | 882 | 30 |
# coding: utf-8
# In[1]:
# constant for different versions of opencv
from builtins import object
import cv2
class cvc(object):
x = cv2.__version__.split('.')
major = x[0]
if major == '2':
FRAME_COUNT = cv2.cv.CV_CAP_PROP_FRAME_COUNT
FRAME_WIDTH = cv2.cv.CV_CAP_PROP_FRAME_WIDTH
FRA... |
d544d4045b30ca8cf5062090fa87d5947341a45610d5e88d8eb690b004689259 | Python | 882 | 33 | from typing import Callable, Iterable, Iterator, TypeVar, Union, overload
import setuptools.extern.jaraco.text as text
from setuptools.extern.packaging.requirements import Requirement
_T = TypeVar("_T")
_StrOrIter = Union[str, Iterable[str]]
def parse_strings(strs: _StrOrIter) -> Iterator[str]:
"""
Yield re... |
f37a9da295ef4543d0f5cd2dd25e19cfd4d0232590415da2ca150644a3ffbe2c | Python | 882 | 21 | import numpy as np
import os
import torch
from src.Liver_Glycogen_Phantoms.utils import *
from src.Liver_Glycogen_Phantoms.src_nn.deep_reco_py import NOEMRFReconstruction
def main(args):
acquired_data = preprocessing(args)
model_phantoms = NOEMRFReconstruction()
checkpoint = torch.load(os.path.join... |
1e7a65b1bbb1983bbefb8dbaefc4d6002d82b90e67a1d3164baf90b953364887 | Python | 883 | 31 | import os
import setuptools
CLASSIFIERS = [
"Development Status :: 4 - Beta",
"Natural Language :: English",
"Operating System :: POSIX",
"Operating System :: Unix",
"Operating System :: MacOS :: MacOS X",
"License :: Restricted use",
"Programming Language :: Python :: 3.6",
"Topic :: ... |
3346d8b4922c3bd9905f0502e5267670c25a90e8b2ba26e5e60e59f7f7b3306d | Python | 883 | 41 | """Distributional and single-time calibration metrics."""
from .distributional import (
aj_calibration,
aj_calibration_per_event,
coverage_ic,
cr_d_calibration,
cr_d_calibration_per_event,
d_cal_ic,
d_calibration,
km_calibration,
ksd_cal_ic,
ksd_calibration,
residuals,
)
fro... |
5428781a09f42ca7e3c8012b48b7c0a17f5106bd5dbd96562a6bc47e11789cf2 | Python | 883 | 28 | from __future__ import annotations
from unittest.mock import Mock
import numpy as np
import pytest
from quacc.calculators.qchem.io import write_qchem
@pytest.mark.parametrize("coefficients", [[0.1, 0.2], np.array([0.1, 0.2])])
def test_write_orbital_coefficients(tmp_path, coefficients):
qc_input = Mock()
... |
75a6bada615020ba099dbcd9357ad1ff7cfd0f2b9250dab718dac8a448682db2 | Python | 883 | 38 | import numpy as np
import scipy
from scipy import stats
import matplotlib.pyplot as plt
output_file="../results/merged_00_100p_20k_autocorr_input_5M_set3.npz"
output_obj = np.load(output_file)['preds']
dorado_score = np.array(output_obj[:, 3], dtype=float)
preds_y = np.array(output_obj[:, 4], dtype=float)
sr, _ =... |
cc03f7e70ce33020adb16e144bb39807ecd963dfab597df6062f0e968e635b92 | Python | 883 | 42 | """
OXASL - Misc utility functions
Copyright (c) 2008 University of Nottingham
"""
import six
class Tee(object):
"""
Output stream which keeps a string record of everything
written to it, and also sends it on to any number of
sub-streams
"""
def __init__(self, *streams):
self._stream... |
ea12432d6f80b22e2bdc17d8041a8c776509c96b09575a0dc5240ea686e55a9a | Python | 883 | 27 | import pytest
import elasticai.creator.nn.fixed_point as nn_creator
from elasticai.creator.arithmetic import FxpArithmetic, FxpParams
from tests.integration_tests.nn.fixed_point.precomputed_routine import (
routine_testing_precomputed_module,
)
@pytest.mark.ghdl
@pytest.mark.parametrize(
"total_bits, frac_bi... |
0bf4c64108dcbc39c840b4fafbb6a91dd7aa5b6067d8c1843d7280d881a4060f | Python | 884 | 42 | # import numpy as np
import jax.numpy as np
from jax import jit
# @jit
def exponential(x, slope: float = 1, offset: float = 0):
return np.exp(slope * x) + offset
# @jit
def linear(x, slope: float = 1, bias: float = 0):
return slope * x + bias
# @jit
def identity(x):
return x
# @jit
def rectifier(x, min... |
582749d46b3f90d170284372206ed33b4638df82160aed338d5552b126d9c14f | Python | 884 | 35 | from itertools import filterfalse
from typing import (
Callable,
Iterable,
Iterator,
Optional,
Set,
TypeVar,
Union,
)
# Type and type variable definitions
_T = TypeVar('_T')
_U = TypeVar('_U')
def unique_everseen(
iterable: Iterable[_T], key: Optional[Callable[[_T], _U]] = None
) -> ... |
d6b37782940c3da6c7afc99d2d18e9a6b7c06349d67610b29e1c28880a0ee41a | Python | 884 | 45 | """Import tests of the main module treem and it's submodules."""
# ruff: noqa: F401
def test_import_treem():
"""Tests importing treem."""
import treem
def test_import_node():
"""Tests importing Node from treem."""
from treem import Node
def test_import_morph():
"""Tests importing Morph from t... |
1786b81605f1ab7665ce1850d42f3b6799fc299d8630d0e4a2c923a26c6b477f | Python | 885 | 35 | """
Reduce the tilt series or micrographs within a stack
Input: - Micrographs stack
- *.order file with two columns; tilt angle, dose in e-/A**2
- Range of valid angles
Output: - Stack with some micrograph extracted
- *.order file with only the tilt angles selected
... |
7c8dc83df073cc48205a41ce7fab1590751ff0a9e2eed262aa9e962c2a66d66c | Python | 885 | 34 | import torch
from torch_geometric.data import InMemoryDataset
class GNNDataset(InMemoryDataset):
def __init__(self, root, train=True, transform=None, pre_transform=None, pre_filter=None):
super().__init__(root, transform, pre_transform, pre_filter)
if train:
self.data, self.slices = to... |
113edc39e90c0eb2220aeafe88aa7cc2fcd5c915b9837d839d15638267857b53 | Python | 886 | 27 | import pytest
import elasticai.creator.nn.fixed_point as nn_creator
from elasticai.creator.arithmetic import FxpArithmetic, FxpParams
from tests.integration_tests.nn.fixed_point.precomputed_routine import (
routine_testing_precomputed_module,
)
@pytest.mark.ghdl
@pytest.mark.parametrize(
"total_bits, frac_bi... |
add7c3291b3d6a35353b405a820d5ce6bc2d4f4330dbe333b4443446389c96c5 | Python | 886 | 29 | from typing import Callable, List, Dict, Optional
import torch
from torch import nn
from .base import AtomicModule
from ..layer.embedding import AtomicOneHot
from ..utils import _scatter_add, EnvPara
class GroundEnergy(AtomicModule):
def __init__(
self,
atomic_number: List[int],
ground_en... |
23b3ea5bedbf753a0e0acc0a025f84b1b3bef3a2f9bdab0daf56154d96ffac31 | Python | 887 | 24 | import setuptools
with open("./prosper_nn/README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
requirements = []
with open("requirements.txt", "r", encoding="utf-8") as f:
packages = f.read().split("\n")
for pack in packages:
requirements.append(pack)
setuptools.setup(
name=... |
4ddcffd7ba34f7ee3889ee5b9c79e2b5c6ddb040afbf2507533e056b347028c2 | Python | 887 | 32 | from __future__ import absolute_import, print_function, division
import warnings
import torch
def _format(message, category, filename, lineno, line=None):
w = '{}: {}\n'.format(category.__name__, message)
return w
warnings.formatwarning = _format
class CudaWarning(UserWarning):
pass
def set_device(dev... |
d61ef9d82a903640fdc175c01b1c4e44a79d6712330520008d3970d4adf69b08 | Python | 887 | 24 | import setuptools
with open("./prosper_nn/README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
requirements = []
with open("requirements.txt", "r", encoding="utf-8") as f:
packages = f.read().split("\n")
for pack in packages:
requirements.append(pack)
setuptools.setup(
name=... |
08fe126539095ca5a8b0d4f57e9ae8afe5ab9b8252f9cc2fd99e71467dac3901 | Python | 888 | 34 | import boto.sqs
from boto.sqs.message import Message
import time
import json
import os
import sys
def get_connection():
secrets_subpath = ".cloudvolume/secrets/aws-secret.json"
secret_path = os.path.join(os.path.expanduser('~'), secrets_subpath)
with open(secret_path) as f:
aws_secrets = json.load(f)
retu... |
9a8d62a7dacf64fb11dbeb4aeddb3ffe33355049bffe72abd36a8cedd7cba63e | Python | 888 | 28 | # pip3 install git+https://github.com/elerac/polanalyser
# pip3 install numba
import cv2
import numpy as np
import polanalyser as pa
def pol2color(image):
img_demosaiced = pa.demosaicing(image)
# Calculate the Stokes vector per-pixel
angles = np.deg2rad([0, 45, 90, 135])
img_stokes = pa.calcStokes(img_demos... |
de66f67ad73bf7ccb82ca99aebf1a0c2aa1366e40eecb017dc2b2d1f25b8fb46 | Python | 888 | 36 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
from downward import suites
from downward.experiment import FastDownwardExperiment
from downward.reports.compare import CompareConfigsReport
import common_setup
REPO = common_setup.get_repo_base()
REV_BASE = 'issue585-base'
REV_V1 = 'issue585-v2'
SUITE = suites.suite_op... |
58073551cc43fb5280403d21a6f437c96dbe9795b788c7a55bcca156533bc3a4 | Python | 889 | 32 | # run in coloc directory
import subprocess
import os
import pandas as pd
pheno_file = "../np_phewas/shared/nacc_rosmap_act_np_dichotomized.pheno"
pheno_data = pd.read_csv(pheno_file)
phenos = ["caa"]
for pheno in phenos:
cmd = [
"python", "coloc_qtl.py",
"--out_pref", "../np_phewas/output/coloc/me... |
78c707058ef1a411c95631e6815d5a2829f5829194493e3cf49a68d8052f7f58 | Python | 889 | 32 | import numpy as np
from matplotlib import pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
def plot3d_against_fan_ins(filters, fn, name):
np.linspace(0, 1, 256)
np.linspace(1, 0, 256)
np.linspace(0, 0, 256)
LinearSegmentedColormap(
"fan_in",
{
"red": [(0.... |
b0389cd04f22e74d8acb48aa6721c482c69d79bf40dfb97e65e76a6fae8eabe6 | Python | 889 | 32 | # -*- coding: utf-8 -*-
"""Setup logging configuration"""
import logging
import sys
def setup_logging(log_level, log_file=None):
""" Setup logging configuration"""
# Check level
level = getattr(logging, log_level.upper(), None)
if not isinstance(level, int):
raise ValueError(f"Invalid log le... |
26c5c4c824d7481dfdbd630be21c6c2fc9701213996defd17c379642a9450543 | Python | 890 | 33 | import torch
def all_pairs_gaussian_kl(mu, sigma, eps=1e-8):
'''
'''
sigma_sq = torch.square(sigma) + eps
sigma_sq_inv = torch.reciprocal(sigma_sq)
term1 = torch.mm(sigma_sq, torch.transpose(sigma_sq_inv, 0, 1))
r = torch.mm(mu * mu, torch.transpose(sigma_sq_inv, 0, 1))
r2 = mu ... |
024ef0d3afa33637388dea6af0fe34aad9bcf19430ef67fde42caea3da9dbe72 | Python | 891 | 35 | """Calibration metrics and helpers for complete survival distributions."""
from .aj_calibration import aj_calibration, aj_calibration_per_event
from .coverage import coverage_ic
from .distribution_calibration import (
cr_d_calibration,
cr_d_calibration_per_event,
create_censor_hist,
create_interval_c_h... |
3387e80686c2070d1b32fe8a0030296ad10880750fef582bbb41675fe6ed5732 | Python | 892 | 29 | # coding=utf-8
# Copyright 2026 The Google Research Authors.
#
# 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 applicab... |
4b60e50bad3d358f4518ea6e48a573f21c82485eb4ee63300a37c66116b34638 | Python | 892 | 30 | import unittest
import os
import random
import shutil
from torcheeg.model_selection import train_test_split
from torcheeg.datasets import DEAPDataset
class TestTrainTestSplit(unittest.TestCase):
def setUp(self):
shutil.rmtree('./tmp_out/')
os.mkdir('./tmp_out/')
def test_train_test_split(sel... |
848c0da3c57917c1dd3db374b0f6371743f63f84a33e4448d2374e8b75b537b2 | Python | 892 | 25 | import pytest
@pytest.fixture(scope="module")
def _qapp():
try:
from PySide6.QtWidgets import QApplication
except Exception as exc: # pragma: no cover
pytest.skip(f"PySide6 unavailable: {exc}")
return QApplication.instance() or QApplication([])
def test_card_is_focusable_and... |
513f0790db358437fe0f8371e59f2af082c1fa48b3616432aa764b46510fc7ea | Python | 893 | 33 | from setuptools import setup
setup(
name='cddd',
version='1.2.2',
packages=['cddd', 'cddd.data'],
package_data={'cddd': ['data/*', 'data/default_model']},
include_package_data=True,
url='https://github.com/jrwnter/cddd',
download_url='https://github.com/jrwnter/cddd/archive/refs/tags/1.2.2.... |
81f9f8ef327aa37d56a762369e5be40f388cf2849584c9ffd087760c112c93c3 | Python | 893 | 25 | # coding=utf-8
# Copyright 2026 The Google Research Authors.
#
# 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 applicab... |
b80a7b1f375516388112f4d9d5aa5c45ee4537c8cbe7eb4725096082e7a7e76e | Python | 893 | 30 | pytest_plugins = ["elasticai.creator.testing"]
def pytest_sessionstart(session):
from elasticai.creator.file_generation import find_project_root
from shutil import rmtree
folders = ["build_test", "build_sim"]
for folder in folders:
path2temp = find_project_root() / folder
if path2temp... |
21c2a22268faa7d03998865832a1e2f16c523395ce2b16a75292250b8d9b10a7 | Python | 894 | 32 | import torch
from prosper_nn.models.deep_feed_forward.deep_feed_forward import DeepFeedForward
# Set model and data parameter
input_dim = 10
hidden_dim = 15
output_dim = 1
n_batches = 100
batchsize = 5
deepness = 3
# Initialise Deep Feedforward Neural Network
deepff = DeepFeedForward(input_dim=input_dim,
... |
33c0ec047590b2f2a5c9ad3a468c96edcc2e542f343678afe75923043d87dc60 | Python | 894 | 15 | """
toposampling - Topology-assisted sampling and analysis of activity data
Copyright (C) 2020 Blue Brain Project / EPFL & University of Aberdeen
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation... |
7972dce382308bf5f53b6ca32cd93e7f4d278c643f10c75508f0ebe1dd42d0eb | Python | 894 | 38 | import torch
import scipy
import numpy as np
import pandas as pd
from typing import ClassVar
from torch.utils.data import Dataset
class UnlockDNASeqDatasetProb(Dataset):
""" Sequence dataset. """
def __init__(self,
ds: pd.DataFrame):
self.ds = ds
def __getitem_... |
a6b2129b4135b6e2bc9c76c2584cf2a5eab338426431ebdc1e3455ccd5d2af07 | Python | 894 | 22 | #!/usr/bin/env python3.9
# train an AI model, track runtime for epochs and save the best models (loss/accuracy)
from ownutil import ParseArgs, PrepareData
# read command line arguments (data set, epoch number, train/validation size)
args = ParseArgs()
#model specific wired setup
args.modelnum = 2 # model 2
arg... |
e8c9be6e2c02f31e8b4f8e7dfd1a0486d699ce19aa4af8aaf7c1079f322fed92 | Python | 894 | 36 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
from downward import suites
from downward.configs import default_configs_optimal
from downward.reports.scatter import ScatterPlotReport
import common_setup
REVS = ["issue214-base", "issue214-v5"]
CONFIGS = {"blind": ["--search", "astar(blind())"]}
TEST_RUN = False
if... |
572938588b5159d897fa07c3dec3557f579d4dc1b4b56d3146dea0d9c98f6864 | Python | 895 | 35 | extensions = dict(
set_required_params="""
parms$training_frame <- training_frame
args <- .verify_dataxy(training_frame, x, y)
if( !missing(weights_column) && !is.null(weights_column)) args$x_ignore <- args$x_ignore[!( weights_column == args$x_ignore )]
parms$ignored_columns <- args$x_ignore
parms$response_column <... |
b70841d0ccb44055fd9ae11c0799208f242bfa5864f512deebaa139ea9c393ae | Python | 895 | 30 | # By Shuran Liu, 2023
import random
import numpy as np
from torch.utils.data import Dataset
import h5py
import cv2
class TestDataset(Dataset):
def __init__(self, h5_file, scale):
super(TestDataset, self).__init__()
self.h5_file = h5_file
self.scale = scale
def __getitem__(self, idx):
... |
cec2fbb3d42187fd4196f94d603cd90a0f561524e412472798a77b99b8a542a4 | Python | 895 | 36 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: usingh
"""
import orfipy_core as oc
seq='ATGTTTATGAAATAGAACTAAATGCCCATG'
seq_rc='CATGGGCATTTAGTTCTATTTCATAAACAT'
#start_search(seq,seq_rc,seqname,minlen,maxlen,strand,starts,stops,table,include_stop,partial3,partial5,find_between_stops,out_opts)
def test_or... |
4ff7dca1f958d582dd59f76eda60ae772b1b7602434ccae2594c9f57d57c24d7 | Python | 896 | 33 | """Provide a convenient way to link to GitHub issues and pull requests.
Link to any issue or PR using :gh:`issue-or-pr-number`.
Adapted from:
https://doughellmann.com/blog/2010/05/09/defining-custom-roles-in-sphinx/
"""
from docutils.nodes import reference
from docutils.parsers.rst.roles import set_classes
def gh_... |
4ad08695ee78b85eb706f802b90a9414366dd557f9e1b76838f544e3bce377f5 | Python | 897 | 22 | #!/usr/bin/env python3.9
# train an AI model, track runtime for epochs and save the best models (loss/accuracy)
from ownutil import ParseArgs, PrepareData
# read command line arguments (data set, epoch number, train/validation size)
args = ParseArgs()
#model specific wired setup
args.modelnum = 4 # model 4
arg... |
6f0cca9f149d3a8f7418c9ae1e7a82a8a4cc6e6b383b6de9e603d0f23b83e426 | Python | 897 | 16 | # this file must be run if changes are made to the model.py file
from numba.pycc import CC
from ednm.model import Model
cc = CC('aot_residual')
@cc.export('residual', '(float64, int32, float64, int32, int32, float64[:,:], float64[:,:], float64[:,:,:], float64[:,:,:], float64[:,:], float64[:,:], \
float64[:,:... |
d27431729b845adf49520f992fe546eb884cd8fcb55fb97849455441180c766e | Python | 897 | 20 | # -*- coding: utf-8 -*-
OPTIMAL = True
CONFIGS = [
(175, ["--search",
"astar(merge_and_shrink(merge_strategy=merge_precomputed(merge_tree=linear(variable_order=reverse_level)),"
"shrink_strategy=shrink_bisimulation(greedy=true),"
"label_reduction=exact(before_shrinking=true,before... |
85d9b8a7ad9eb74d3407c353856a5d0b7da8cfd700bed7b5193d12f4a4a8db0f | Python | 898 | 30 | from elasticai.creator.arithmetic import (
FxpArithmetic,
FxpParams,
)
from elasticai.creator.file_generation.savable import Savable
from elasticai.creator.nn.fixed_point.math_operations import MathOperations
from .design import MacDesign
class MacLayer:
def __init__(self, vector_width: int, fxp_params: ... |
71691991256c0def5db14f7613bc02fccc6943d30c669c8200a7ddc1e82d0b71 | Python | 899 | 37 | from scipy import stats
import matplotlib.pyplot as plt
import numpy as np
import torch
from scipy.io import loadmat
from sklearn.model_selection import StratifiedKFold
from sklearn.model_selection import KFold
def train_val_test_split(kfold = 5, fold = 0):
n_sub = 1035
id = list(range(n_sub))
import ra... |
228d41dd80fd32a9ebc8aeea3b93781062af54d09d1f706fb0d2e3ce03a74978 | Python | 901 | 33 | from pathlib import Path
import numpy as np
from pycudadecon import make_otf
from pycudadecon.util import imread, is_otf
DATA = Path(__file__).parent / "test_data"
PSF_PATH = str(DATA / "psf.tif")
OTF_PATH = str(DATA / "otf.tif")
def test_make_otf(tmp_path):
"""Test that it can make an otf file from a psf."""
... |
b4c4cb5e492a386843a33a8c0c8568f7e78908e7bf73419930da1ab377a64050 | Python | 901 | 26 | import os
import os.path as op
import nibabel as nib
import numpy as np
import nipype.interfaces.fsl as fsl
from nilearn.datasets import load_mni152_brain_mask
def make_sphere(x, y, z, output_dir):
mask = load_mni152_brain_mask()
mask_img = mask.get_data()
xyz_img = np.dot(np.linalg.inv(mask.affine), [x, ... |
2dc1104b79697166fb102d8447683902938fe04ec9dd0a8ea1a999e973166682 | Python | 902 | 29 | import pytest
import elasticai.creator.nn.fixed_point as nn_creator
from elasticai.creator.arithmetic import FxpArithmetic, FxpParams
from tests.integration_tests.nn.fixed_point.precomputed_routine import (
routine_testing_precomputed_module,
)
@pytest.mark.ghdl
@pytest.mark.parametrize(
"total_bits, frac_bi... |
7a58035c5be9809bc411976ebfd75e9ea243eada948ea6be99838e316109d45b | Python | 902 | 35 | """Apply given weights for custom linear combination."""
from xarray import DataArray
from hmp.projectors.base import Projector
class Custom(Projector):
"""Project data using custom weights.
Attributes
----------
weights : xr.DataArray
DataArray with dimensions [channel, component] and coord... |
f4c95ec4870c58fecfd49d11b7728c459a731fcddb51c5c1bcc7024e30c1f8ce | Python | 902 | 41 | """
Set of tests that are as explicit as possible, in case the test helpers like
autograd.test_util break and start letting everything pass
"""
import numpy as onp
import pytest
import autograd.numpy as np
from autograd import deriv, grad, holomorphic_grad
def test_grad():
def fun(x):
return (x + np.sin... |
25a88a54f06395dd24e7284b851dacdbb8582d593f64f13d1c4da06959560937 | Python | 903 | 35 | from psychopy import visual, event
import numpy as np
from psychopy.visual.filters import makeGrating
def make_gratings(win,
red_cycles = 10, red_phase = 0.,
blue_cycles = 3, blue_phase = 0.,
grating_res = 256,
pos = (0, 0)
):
red_grating = makeGrating(
res = grating_res,
ori =... |
f135b81ee6b11ce069bfe6c14b6b94499d36f518d05a12f15bccebc8f12fa93e | Python | 903 | 34 | """
Depth Nerfstudio Field
Currently this subclasses the NerfactoField. Consider subclassing the base Field.
"""
from typing import Literal, Optional
from torch import Tensor
from nerfstudio.field_components.spatial_distortions import SpatialDistortion
from nerfstudio.fields.nerfacto_field import NerfactoField # f... |
118a4412ccb78ceb3f3be54fb76683c1ca70acdfa51819298e1c13716dc920ae | Python | 904 | 43 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
from downward import suites
import common_setup
REVS = ["issue544-base", "issue544-v1"]
LIMITS = {"search_time": 1800}
SUITE = suites.suite_satisficing_with_ipc11()
CONFIGS = {
"eager_greedy_add": [
"--heuristic",
"h=add()",
"--search",
... |
f0519b347cb5b61baf3d4c2e9d2076c574f2ff5a98e41b5bf73457285fe53921 | Python | 904 | 25 | """A BIDS time series tabular file."""
from hed.models.base_input import BaseInput
class TimeseriesInput(BaseInput):
"""A BIDS time series tabular file."""
HED_COLUMN_NAME = "HED"
def __init__(self, file=None, sidecar=None, extra_def_dicts=None, name=None):
"""Constructor for the TimeseriesInpu... |
0a3a8818e833e497bf498da8d7f1a38bfb6670cd409c6815674b6506069aa44e | Python | 905 | 42 | from numpy import genfromtxt, empty
from re import search
from json import load
from .find import walk
def get_json(path, values, ending):
# read keys starting from the higher directory to the lowest directory
d = {}
for filename in reversed(walk(path, values, ending)):
with filename.open() as f... |
18b0a3c490ec533a6a3d76d76af156f80be0fc640653075f233242e806084600 | Python | 905 | 29 | import pytest
import elasticai.creator.nn.fixed_point as nn_creator
from elasticai.creator.arithmetic import FxpArithmetic, FxpParams
from tests.integration_tests.nn.fixed_point.precomputed_routine import (
routine_testing_precomputed_module,
)
@pytest.mark.ghdl
@pytest.mark.parametrize(
"total_bits, frac_bi... |
48b9dc234d200d24cffed266b99660fec8081c3c94f44ece906bc7ccc3f143fd | Python | 905 | 24 | from cloudvolume import CloudVolume
import numpy as np
from scipy import ndimage
mip = 6
src = CloudVolume('gs://neuroglancer/pinky100_v0/image_single_slices', mip=mip)
dst = CloudVolume('gs://neuroglancer/pinky100_v0/image_single_slices/roicc',
cdn_cache=True, mip=mip)
# Get bounding box of a total sli... |
5425964e38f0ec251748f765aabbc21095bcd8cdbc4f5dd792aab47ad35ce58a | Python | 905 | 25 | import setuptools
with open('README.md', 'r', encoding='utf-8') as fh:
long_description = fh.read()
setuptools.setup(
name='mnp',
version='0.0.1',
author='Miguel García-Ortegón',
author_email='mg770@cam.ac.uk',
description='Source code for models from paper "Graph neural processes for molecule... |
12f38c55505c9ed9b6219963606953e297309dde8263e3e977da7a36e412bc95 | Python | 906 | 31 | import os
import setuptools
CLASSIFIERS = [
"Development Status :: 4 - Beta",
"Natural Language :: English",
"Operating System :: POSIX",
"Operating System :: Unix",
"Operating System :: MacOS :: MacOS X",
"License :: Restricted use",
"Programming Language :: Python :: 3.8",
"Topic :: ... |
161af1030920ce43ca4611508f5a4e3209be6978dd9a0adf3fa83eacd11de99a | Python | 906 | 27 | from torch import nn
import torch.nn.functional as F
class se_module(nn.Module):
def __init__(self, channel, reduction=16):
super(se_module, self).__init__()
# NOTE: change to nn.functional.adaptive_avg_pool2d without the need for creating a layer object,
# which can help avoid the issue w... |
53c36ba04b6dfc2549ac90cc118e7e5d8b35e990d25a3f66a09fff76951f5d22 | Python | 906 | 36 | import sys
from pybioshell.core.data.io import find_pdb
# change that setting to False to include ligands in the output sequence
IF_EXCLUDE_LIGANDS = True
if len(sys.argv) < 2 :
print("""
Extracts amino acid (or nucleotide) sequence from a PDB file.
Note, that by default ligands are not included in the output se... |
002eaca27d5a885721c533566ee6126b901fb121f42ea1f005edbf9239c719df | Python | 907 | 27 | # coding=utf-8
# Copyright 2026 The Google Research Authors.
#
# 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 applicab... |
e11349b6d3c3a902cd002102fee39bec50dde7c3945f0826422b74f2a39dc37f | Python | 907 | 22 | #!/usr/bin/env python3.9
# train an AI model, track runtime for epochs and save the best models (loss/accuracy)
from ownutil import ParseArgs, PrepareData
# read command line arguments (data set, epoch number, train/validation size)
args = ParseArgs()
#model specific wired setup
args.modelnum = 8 # model 8
arg... |
e31f088f3a6722c2831f709365064dd76f5dda09e1f3360f0da4bfdc944180d3 | Python | 907 | 22 | #!/usr/bin/env python3.9
# train an AI model, track runtime for epochs and save the best models (loss/accuracy)
from ownutil import ParseArgs, PrepareData
# read command line arguments (data set, epoch number, train/validation size)
args = ParseArgs()
#model specific wired setup
args.modelnum = 9 # model 9
arg... |
2475305de750f01da6c79d6711472115f6b5f8b2be5f1cdf60e253e70639fd5e | Python | 908 | 22 | #!/usr/bin/env python3.9
# train an AI model, track runtime for epochs and save the best models (loss/accuracy)
from ownutil import ParseArgs, PrepareData
# read command line arguments (data set, epoch number, train/validation size)
args = ParseArgs()
#model specific wired setup
args.modelnum = 7 # model 7
arg... |
346af70730785aca714828f9ed85cccc58a179e33619f0dc2ab40bae3fca66e6 | Python | 908 | 32 | from setuptools import setup, find_packages
setup(
name="organsegment",
#version="0.1.0",
author="Yazdan Salimi",
author_email="salimiyazdan@gmail.com",
description="Multi Modality Organ Segmentation tools",
long_description=open('README.md').read(),
long_description_content_type="text/mark... |
9001afcf1cde59b5fcd62ef6f81baff06e2e88e3ad62c0366326900f1a8a1231 | Python | 908 | 37 | import numpy as np
from vmdpy import VMD
# VMD default parameters
# bandwidth constraint (the higher, the smaller bandwidth)
ALPHA = 100
# number of modes
K = 12
# noise-tolerance (Lagrangian multiplier)
TAU = 0.0
# DC part: fix w0 = 0
DC = False
# initialize omegas
INIT = 1
TOL = 1e-7
# VMD parameters
VMD_SUM_FROM =... |
cdbb38af677edd17b26eb9d91c43c70aa988f7898ac7d719a71ce3a64923bcb0 | Python | 908 | 22 | import argparse
# Requires these imports even if not being actively used due to linking issue
from segmentation import export_probes_as_obj, segment_electrodes, electrode, point_of_electrode, representative, probe
def export_probes(segmented, probefile, path):
"""
segmented is the segmented by probe file
... |
07f1bbcda1b5936bcf656f71c659f2d0cd48627705ac83b6cf4ba088cfec6239 | Python | 909 | 46 | import numpy as np
from vanhateren import VanHateren
def test_download():
vh = VanHateren()
vh.download_image(8)
def test_image_list():
vh = VanHateren()
print(vh.image_list())
def test_max():
vh = VanHateren()
images = vh.images(vh.image_list())
print(images.max())
def test_image(p... |
58cd3fbe7a540c529bdf359164820536cdf6df2c4982ec2b87fcb26a0515a49e | Python | 909 | 34 | #!/usr/bin/python
##
# \file run_tests.py
# \brief main-file to run specified unit tests
#
# \author Michael Ebner (michael.ebner.14@ucl.ac.uk)
# \date September 2015
#
import unittest
from brain_stripping_test import *
from case_study_fetal_brain_test import *
from case_study_rsfmri_test import *
fr... |
6341b19a9df6c2f143a9942473b001a52b544dd6b7a55b3b41baf9c5ca7168ce | Python | 909 | 41 | import numpy as np
def RSE(pred, true):
return np.sqrt(np.sum((true - pred) ** 2)) / np.sqrt(np.sum((true - true.mean()) ** 2))
def CORR(pred, true):
u = ((true - true.mean(0)) * (pred - pred.mean(0))).sum(0)
d = np.sqrt(((true - true.mean(0)) ** 2 * (pred - pred.mean(0)) ** 2).sum(0))
return (u / d... |
960659f4bad7c61faed1ff0854f6bac31c33ec5b3ef5e33a2acdf8eb535ce99e | Python | 909 | 22 | #!/usr/bin/env python3.9
# train an AI model, track runtime for epochs and save the best models (loss/accuracy)
from ownutil import ParseArgs, PrepareData
# read command line arguments (data set, epoch number, train/validation size)
args = ParseArgs()
#model specific wired setup
args.modelnum = 6 # model 6
arg... |
e7ae41848700a2083744d2707a72d9a8e9eb36397eeaa5065fa8bf28bfcee1ef | Python | 909 | 25 | """Stage-1 directory naming with backward-compatible reads.
Runs used to write ``01_axis_alignment`` (a midsagittal-plane opt-in). New runs
write ``01_affine`` (which also hosts the selectable affine). Readers must accept
both, so old on-disk runs keep resolving.
"""
import os
STAGE1_DIRNAME = "01_affine"
... |
0ebc9ecd3233ed5778f64b456f2a60ce4e020a637d1500467bd1cb29e44ef81e | Python | 910 | 26 | from mahotas.features import haralick
from mahotas.features.texture import haralick_labels
angleList = ['0', '45', '90', '135']
def calcFeatures(img,Distance):
# Remove the 14th (last) feature name since it is not calculated by default
featureLabels = haralick_labels[:-1]
# Return only mean value ... |
277d9648231761f4691a877c6095413f5acb5610b3edc3e6e4b454c21885907f | Python | 910 | 31 | from unittest import TestCase
from codex.utils.number_compacter import number_to_compact_repr, compact_repr_to_number
TEST_CASES = {
0: "0",
1: "1",
10: "A",
36: "a",
62: "10",
3843: "zz",
238327: "zzz",
14776335: "zzzz",
}
TEST_CASES.update({-k: f"-{v}" for k, v in TEST_CASES.items() ... |
2f865a0d0c3c441b903939827c92ebb8244ea444d5e0e402b43307599d7c1628 | Python | 910 | 29 | """
Set of specific utilities for spatial analysis
# Author: Antonio Martinez-Sanchez (Max Planck Institute for Biochemistry)
# Date: 12.06.15
"""
__author__ = 'Antonio Martinez-Sanchez'
# Analysis from coordinates DEPRECATED
from .mb import CMCAnalyzer
from .plane import SetClouds
from .plane import SetClusters
fro... |
3c62d7352842aafa2b3e0ed9c590ebec8e0c2242174c2003c4a5d0251d8f7754 | Python | 910 | 22 | #!/usr/bin/env python3.9
# train an AI model, track runtime for epochs and save the best models (loss/accuracy)
from ownutil import ParseArgs, PrepareData
# read command line arguments (data set, epoch number, train/validation size)
args = ParseArgs()
#model specific wired setup
args.modelnum = 1 # model 1
arg... |
56d3d439ef447a40f932b699559c8ce6cb1d871c5ad3abd74a5ea7074c0ca991 | Python | 910 | 22 | #!/usr/bin/env python3.9
# train an AI model, track runtime for epochs and save the best models (loss/accuracy)
from ownutil import ParseArgs, PrepareData
# read command line arguments (data set, epoch number, train/validation size)
args = ParseArgs()
#model specific wired setup
args.modelnum = 10 # model 10
ar... |
88fa1e9a03113ea5724f886d22fe9b7df712e0d0f6785f7d0ec64adbfc30dea4 | Python | 910 | 31 | # run in coloc directory
import subprocess
import os
import pandas as pd
pheno_file = "../np_phewas/shared/nacc_rosmap_act_np_dichotomized.pheno"
pheno_data = pd.read_csv(pheno_file)
phenos = pheno_data.columns[2:]
for pheno in ["diffuse_abeta"]:
cmd = [
"python", "coloc_qtl.py",
"--out_pref", "..... |
ede7ecca9912c9fef7830f3788eccaf0ca456578dc409d700a0d30f5671ea2ca | Python | 910 | 33 | import unittest
import os
import random
import shutil
from torcheeg.model_selection import Subcategory
from torcheeg.datasets import M3CVDataset
from torcheeg import transforms
class TestSubcategory(unittest.TestCase):
def setUp(self):
shutil.rmtree('./tmp_out/')
os.mkdir('./tmp_out/')
def t... |
5a8d7dd9663adbfd94ef08dc336f02f0550e369dba0ca0b47fadf780f68980cf | Python | 911 | 30 | # coding=utf-8
# Copyright 2026 The Google Research Authors.
#
# 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 applicab... |
c21225c31f661df5d313e6bf5a8935e243a086288eee9ffe38b3eb5b1462555a | Python | 911 | 29 | """实现GAT 类。"""
import torch
import torch.nn.functional as F
import torch.nn as nn
import torch_geometric.nn as pyg_nn
from RGATConv import RGATConv
class RGAT(nn.Module):
def __init__(self, in_c, hid_c, out_c, log_attention_weights=False):
super(RGAT, self).__init__()
self... |
0b0456eac83db66570d3f53238e683ceec49f8a6882d0b868efb7faaf73e9160 | Python | 912 | 35 | import os
import pytest
class Plotter(object):
def __init__(self, request):
self.dirname = 'tests.plots'
self.module_name = request.module.__name__
self.function_name = request.function.__name__
self.ext = 'pdf'
@property
def path(self):
filename = "%s.%s.%s" % (
... |
a64b044df270475354eeefb6fc783068c61c10f0e32938693017b77f0151479b | Python | 912 | 25 | import logging
def define_root_logger(filename='logfile.txt',filemode='a'):
logging.root.handlers = []
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(levelname)-10s: %(filename)-10s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
... |
bae67077053829f7e8090c7ff069cc3441cc8a1f4cae3247fd1ec297368dd741 | Python | 912 | 26 | from typing import Callable
import torch.nn as nn
def create_initializer(mode: str) -> Callable:
if mode in ['kaiming_fan_out', 'kaiming_fan_in']:
mode = mode[8:]
def initializer(module):
if isinstance(module, nn.Conv2d):
nn.init.kaiming_normal_(module.weight.data,
... |
c83bb81e55a154005e13b3b4c6f68cde2b548f88b612aa2cffbdd391c11e538a | Python | 912 | 27 | import pytest
import torch
from elasticai.creator.arithmetic import FxpParams
from elasticai.creator.nn import fixed_point as nn_creator
@pytest.mark.parametrize(
"total_bits, frac_bits, num_steps",
[(4, 3, 4), (6, 4, 32), (8, 5, 64), (10, 6, 16), (12, 7, 128), (12, 11, 64)],
)
def test_relu_compared_torch(t... |
e6564700ae487c24f19cd46e821abb8ef47150e97f98a0d1ec358bb682575b7f | Python | 912 | 26 | import pytest
import torch
from elasticai.creator.arithmetic import FxpParams
from elasticai.creator.nn import fixed_point as nn_creator
@pytest.mark.parametrize(
"total_bits, frac_bits, num_steps",
[(4, 3, 4), (6, 4, 32), (8, 5, 64), (10, 6, 16), (12, 7, 128), (12, 11, 64)],
)
def test_hard_sigmoid_compared... |
23b62a24466469c29f296d8cf1820ac8a6eedc25ae20ecd1ec1fb2db83335834 | Python | 913 | 30 | import os
import shutil
import unittest
from hed.models import TimeseriesInput
# TODO: Add tests about correct handling of 'n/a'
class Test(unittest.TestCase):
@classmethod
def setUpClass(cls):
base_output_folder = os.path.realpath(os.path.join(os.path.dirname(__file__), "../data/tests_output/"))
... |
9b29db21abd72b7a133b9d077febd85b2c4fb71182418b17de5747a89a71054e | Python | 913 | 32 | import os
import time
import apps
FILE_PATH, FILE_FULL_NAME = os.path.split(os.path.realpath(__file__))
FILE_NAME, FILE_EXT = os.path.splitext(FILE_FULL_NAME)
if __name__ == '__main__':
try:
myapp = apps.App()
# Connect the device
myapp.client.connect('101.6.93.189', 5000, 2)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.