sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
cac394bea46d6f8d1514eb6b35255a5b552952efe13efe470f3c6b3c03cb9a11 | Python | 784 | 22 | """ Remove silent part at the beginning of the stimuli. """
import numpy as np
from scipy.io import wavfile
from pathlib import Path
from speech_utils import cut_wav_from_cue
from helpers import load_config
if __name__ == '__main__':
config = load_config('speech_config.yaml')
wav_dir = Path(config['raw_stimu... |
ec86bc0aaf3a1fd717df2c8def345a467a3db9a23f21387b7241b4259b92235e | Python | 786 | 30 | import pickle
import numpy as np
import torch
from mnist import MNIST
from utilities.Dataset import *
class MNISTDataset(torch.utils.data.Dataset):
def __init__(self, subset:str, path="./MNIST/raw"):
assert subset=="TRAIN" or subset=="TEST", "subset should either be TRAIN or TEST"
mndata= MNIST... |
07ee1990ef69c66adf3abbeca31d89fa4b1a07bf7bc07ab750097937b8f605fa | Python | 788 | 27 | from __future__ import annotations
import numpy as np
from bayes_opt.util import ensure_rng
def test_ensure_rng():
"""Test that ensure_rng properly handles different inputs."""
# Test with None (should return a new RandomState)
rng1 = ensure_rng(None)
assert isinstance(rng1, np.random.RandomState)
... |
212f76d20a49b354ae02ba12886a422ff1aef2552fe1c994e75b5d1163aa4688 | Python | 788 | 31 | import torch
import torch.nn as nn
class PTGWAS(nn.Module):
def __init__(self, G, F=None):
super(PTGWAS, self).__init__()
if F is None:
F = torch.ones((G.shape[0], 1))
self.G = G
self.F = F
self.FF = torch.mm(F.T, F)
self.A0i = torch.inverse(self.FF)
... |
9884943fc80b62c15b4bb6f6f551a65f27f3937fdd469e7d7d8440ed8c9b4228 | Python | 788 | 24 | # morphoglia/morphometrics/engine.py
from __future__ import annotations
from typing import Dict, List
import numpy as np
class MorphometricEngine:
"""
Applies a list of calculator instances to ROIs.
Each calculator is a callable(roi) -> dict[str, float].
"""
def __init__(self, calculators: List):
... |
cc74206bf60dce3f9db7234301511287a16c5e47b2b655ece98934e88ebff548 | Python | 788 | 25 | from .MPQSupport import MPQSupport as MPQSupport
from .Observers import (
GlobalMinMaxObserver as GlobalMinMaxObserver,
)
from .Observers import (
LocalMinMaxObserver as LocalMinMaxObserver,
)
from .Observers import (
MovingAverageMinMaxObserver as MovingAverageMinMaxObserver,
)
from .QParams import (
A... |
3a303a702aa585ff41aab1a876b539a21bde8269f0802e76ef9c0847c4fa265f | Python | 789 | 23 | import pandas as pd
import numpy as np
import io
import os
import gc
df_testset_names = pd.read_csv('labels_very_large_data/test_labels.csv')
df_conf_pred = pd.read_csv('pred.csv', names = ['prob_TD','prob_ASD'])
df_pred = pd.read_csv('class_preds.csv', names = ['pred'])
df_truth = pd.read_csv('truth.csv', names = ['... |
74080eec42643f3f4e622a53d9e55c2cc1fe1c624004e07dc760585a3c18b8a8 | Python | 790 | 22 | import numpy as np
from skimage.transform import resize
__all__ = ['resize_padded']
def resize_padded(img, new_shape, fill_cval=None, order=1, anti_alias=True):
if fill_cval is None:
fill_cval = np.max(img)
ratio = np.min([n / i for n, i in zip(new_shape, img.shape)])
interm_shape = np.rint([s *... |
b427c7162f4b8a4e6b8e7f7d1534e36907611b83144d201dff81494896963835 | Python | 790 | 24 | """
Registration module - Brain image registration pipeline.
This package contains all registration-related code:
- core/ : Registration algorithms (ANTs, Elastix, Laplacian refinement)
- pipeline.py : CLI registration pipeline
- gui.py : PyQt5 GUI for registration
- launch.py : Standalone ... |
17c752e0d26cc4a4d5c9bb4a1242afda6d358299445531da78869f0ecbadb273 | Python | 791 | 35 | base_architecture = 'resnet152'
img_size = 224
num_classes = 2
add_on_layers_type = 'regular'
experiment_run = 'resnet152_lr_addonlayer_1e-4_11-10-2022'
data_path = '../QA_project/'
train_dir = data_path + 'train_cropped_augmented/'
test_dir = data_path + 'validation_cropped/'
train_push_dir = data_path + 'train_crop... |
82ec03b6342324849c8eb5e4fe59170d28591fa68dff3437fc1b0883631f49d5 | Python | 791 | 19 | from typing import Optional
from cog import BaseRunner, File, Input, Path
class Runner(BaseRunner):
def run(
self,
text: str = Input(description="Required string"),
# PEP 604 style optionals
opt_str: str | None = Input(description="Optional string", default=None),
opt_int:... |
c565f77492ebbca485ace08e17078e81fef8fb658e2983b10073d5fdd30ca672 | Python | 791 | 22 | import time
from pddlstream.language.constants import is_plan, Certificate
from pddlstream.utils import elapsed_time, INF
def restart(problem, planner_fn, max_time=INF, max_restarts=0):
# TODO: iteratively lower the cost bound
# TODO: a sequence of different planner configurations
# TODO: reset objects an... |
9233944e910a5876242fb4b205cc94e49fa30aa15500fedc489696869b266a65 | Python | 792 | 22 | from setuptools import setup
setup(
name = 'soundsig',
version = '3.1',
packages = ['soundsig'],
description = 'Sound and Signal Analysis Tools for Bioacousticians and Auditory Neurophysiologists',
author = 'Frederic Theunissen',
author_email = 'theunissen@berkeley.edu',
url = 'https://gith... |
0e0166e64bdd056e82705be99fdb92ca1b233cc87c5fd2286710a7e7e6135db8 | Python | 793 | 26 | """Active drag-tool mode enum for the CCF boundary editor.
Lives in its own module so non-GUI code (tests, future headless
helpers) can import it without dragging in pyqtgraph + Qt.
"""
from __future__ import annotations
import enum
class ToolMode(enum.Enum):
"""Active drag-tool mode on the canvas.... |
a3e41154c1a210dad3271c377c0840eeec69744770e8ce354e31d8b52551adc8 | Python | 795 | 35 | """A helper module that injects SecureTransport, on import.
The import should be done as early as possible, to ensure all requests and
sessions (or whatever) are created after injecting SecureTransport.
Note that we only do the injection on macOS, when the linked OpenSSL is too
old to handle TLSv1.2.
"""
import sys
... |
d777339e504a9ae245dfbec36ceedb0fd3889cacdef1c83762df80aa4157558e | Python | 795 | 22 | # 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... |
d3b644190d8db41feb728451455823c05527978fc2a8fd7cdf96d9b9799bd442 | Python | 796 | 27 | from glob import glob
import argparse
from pyrelimri import similarity
warnings.filterwarnings("ignore")
# input arguments
parser = argparse.ArgumentParser(description="Script to run similarity estimate between func/anat masks")
parser.add_argument("--anat", help="path to anatomy MNI mask")
parser.add_argument("--func... |
5af02ad3d6190c0379819c20aa60c7bde991004bb9d389dbc4263124e764625a | Python | 797 | 31 | from __future__ import annotations
import pytest
pytest.importorskip("pymatgen.analysis.defects")
pytest.importorskip("shakenbreak")
from ase.build import bulk
from quacc.recipes.emt.defects import bulk_to_defects_flow
def test_bulk_to_defects_flow(tmp_path, monkeypatch):
monkeypatch.chdir(tmp_path)
atoms... |
636aa85a546fd155420ea41781b3c6838642362a6ffe5f0ff6056a91a852767c | Python | 797 | 29 | import pandas as pd
def rename_rows(pandaDF):
"""
this function renames the columns in the data frame so that is easier
to call them. This is due to the fact that I wasn't able to properly rename the variables
coming out of Bonsai.
There is probably a better way of doing this using Bonsai
... |
a0f91bcfe2d9cb2fe7cb4170148f3b63cabcef69e538f6537b0e28fbe3bf71b5 | Python | 797 | 32 | # SPDX-FileCopyrightText: 2024 Blue Brain Project / EPFL
#
# SPDX-License-Identifier: AGPL-3.0-or-later
'''
Compute a rewiring of the V5 circuit according to input config
Author(s): Daniela Egas S.
Last updated 12.2023
'''
import json
import time
import sys
import numpy
sys.path.append('/gpfs/bbp.cscs.ch/home/egas... |
2aec6e10a66eb4ce6da60b7e54828a9b9f1138c1395da30ebde38d99e0a48a32 | Python | 798 | 26 | import torch
import math as m
import numpy as np
class Six_hump_camel_func:
def __init__(self):
self.name = 'Six_hump_camel'
self.formula = r'$\min\ f(x_1,x_2)=(4-2.1x_1^2+x_1^4/3)x_1^2+x_1x_2+(4x_2^2-4)x_2^2$'
def function(self, x):
f = (4 - 2.1 * x[0] ** 2 + x[0] ** 4 /... |
5f059468b903eb1ceda6104d6e977bfb9158148e4d22520ceed7bab07487114e | Python | 798 | 41 | # from cx_Freeze import setup, Executable
# import pkg_resources
from setuptools import setup
build_exe_options = {
'excludes': [
'jupyter',
'ipython',
'test',
'html',
'http'
]
}
setup(
name='ABFbot',
version='1.5',
description='Automated... |
e03c67dada22cb66387fc3afbd2e2267aa759097a1e5e4c8dc4bf97713dcb443 | Python | 798 | 27 | import pyclesperanto_prototype as cle
from skimage.io import imread, imsave
# initialize GPU
cle.select_device("GTX")
print("Used GPU: " + cle.get_device().name)
# load data
image = imread('https://imagej.nih.gov/ij/images/blobs.gif')
print("Loaded image size: " + str(image.shape))
# process the image
inverted = cl... |
29f86e90137f01005e8a95defae910fb8bed820788f9ec9230340ecb144211f7 | Python | 799 | 42 | # set QT_API environment variable
import os
import sys
import argparse
os.environ["QT_API"] = "pyqt5"
import qtpy
# qt libraries
from qtpy.QtCore import *
from qtpy.QtWidgets import *
from qtpy.QtGui import *
# Qt style sheets
from aqua.qsshelper import QSSHelper
# app specific libraries
import control.gui_tracking... |
36dc08b34e38c064a8e7ae62147a7f4f90afe627ae2c10a92cb474683fc1eaa1 | Python | 799 | 24 |
import pytest
import os
from cobolt.utils import MultiomicDataset
from cobolt.model import Cobolt
from cobolt.tests.test_load_data import load_test_data
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
class TestModel:
def test_model(self):
ja, jb, sa, sb = load_test_data()
multi = Multiomi... |
b4d87586b451d5a9aa910c3bda011227a7e3c81538225c35dbcd6a1b176daeb6 | Python | 799 | 17 | from utils.api.mygene_api import get_gene_annotation, get_gene_annotations
from utils import set_random_seed
SEED = 1126
set_random_seed(SEED)
if __name__ == '__main__':
print(get_gene_annotation(ensembl_id='1017'))
print(get_gene_annotation(ensembl_id='ENSG00000123374'))
print(get_gene_annotation(ensembl... |
f475012dbe18033b0e5508b7d72b87f1c087c1fde0b23ef5df0ce3b6578f88c3 | Python | 799 | 33 | """
Library using tensorflow model to predict sequence data
"""
import numpy as np
import tensorflow as tf
def predict(model_file, weights_file, data):
strategy = tf.distribute.MirroredStrategy(devices=None)
with strategy.scope():
json_file = open(model_file, 'r')
loaded_model_json = js... |
1b059a704a50f821f22adf2cf310aff06580118f8e26a60404ad53e220e31a02 | Python | 800 | 35 | from setuptools import setup, find_packages
version = "0.2.0"
with open("./README.md") as fd:
long_description = fd.read()
setup(
name="pystripe",
version=version,
description=
"Stripe artifact filtering for SPIM images",
long_description=long_description,
install_requires=[
"nump... |
44b57c25f5ec3c3de13ad65c2b572119918d18429a6e111e9d3df2b9dd18cef3 | Python | 800 | 25 | import scipy.stats
import autograd.numpy as np
from autograd.extend import defvjp, primitive
from autograd.numpy.numpy_vjps import unbroadcast_f
from autograd.scipy.special import gamma
cdf = primitive(scipy.stats.chi2.cdf)
logpdf = primitive(scipy.stats.chi2.logpdf)
pdf = primitive(scipy.stats.chi2.pdf)
def grad_c... |
8d69d6971356b5cfaa7573d464624aea1736fc580e9eac7809fdc1cc89483044 | Python | 800 | 19 | """
Point Reorient
==============
Interactive tool for reorienting cellpose output points relative to a 2D or 3D
image dataset. When cellpose runs on a volume that was saved with a different
axis convention than the downstream pipeline expects, the resulting centroid
points end up rotated / flipped relative to... |
307b2b3f3dcb64d15c91e1d8fce9f8d9fd3dadf46b982a94a69e1a755e269321 | Python | 801 | 26 | # Open parameters for optimization and bounds
##################################################
# Choose which parameters are going to optimized #
##################################################
# Specified here because params_net needs to be loaded first
params = {}
# Set lower and upper bounds for parameter typ... |
f4cbe405e3010c086613293a9a73713cd4a6e1c907975793ae38123125ce3c68 | Python | 801 | 22 | from pupil_recording_interface.pipeline import Pipeline
from pupil_recording_interface.process.recorder import VideoRecorder
class TestPipeline:
def test_from_config(self, pipeline_config, mock_video_device):
""""""
pipeline = Pipeline.from_config(
pipeline_config, mock_video_device, f... |
f78f0ff967502460a12929ca3e8cd0e74a2e6bcc6e09b699e2c9eb74ec089c52 | Python | 801 | 32 | """ Setup config
"""
from setuptools import find_packages, setup
setup(
name="bifrost",
version="0.1",
author="Andrew Berger",
author_email="a5b@stanford.edu",
description="Template building and cross-modal registration.",
url="https://github.com/ClandininLab/bifrost",
packages=find_packag... |
17a9944e43df60bbc8a1fd1676425c3f084777db4bb6107e72fe6f31d8c665e3 | Python | 803 | 35 | # Importing core packages
import numpy as np
import matplotlib.pyplot as plt
import os
from Library import Characterize2 as ch
import sys
import time
import datetime
import shutil
import pathlib
from PIL import Image
import cv2
import h5py
def generateStim(layerout):
stim = np.array(layerout).reshape((2000,100))
... |
b843743bc2bba3fea7637d2a4f1e8453d8ae7c754ff777dacf5a8db23f3851f1 | Python | 803 | 24 | from .hashencoder import HashEncoder
from .freqencoder import FreqEncoder
def get_encoder(encoding, input_dim=3,
multires=6,
degree=4,
num_levels=16, level_dim=2, base_resolution=16, log2_hashmap_size=19,
**kwargs):
if encoding == "None":
r... |
adf92079494141ac9ff237bd642c2e0e58316b1fe7fe36540487244a2f2021ed | Python | 804 | 39 | from __future__ import print_function
# -*- coding: utf-8 -*-
import contextlib
import os
import sys
import time
class Timer(object):
def __init__(self):
self.start_time = time.time()
self.start_clock = self._clock()
def _clock(self):
times = os.times()
return times[0] + tim... |
8f75598376e5ae57c19a4720b268649f44238b2a961093853b78bc239e00605e | Python | 805 | 26 |
# coding: utf-8
# In[2]:
import socket
import sys,re
import PoseTools
if re.search('verman-ws1.hhmi.org',socket.gethostname()):
#sys.path.append('/groups/branson/home/kabram/bransonlab/pose_estimation/caffe/python')
#bdir = '/localhome/kabram/poseTF/'
bdir = '/groups/branson/bransonlab/mayank/PoseTF/'
elif ... |
8e17d4b5bba5a579951377d4ea661ee8056f04078c16a7274e2b56d2b9329b6a | Python | 806 | 28 | import unittest
from torcheeg.datasets import TSUBenckmarkDataset
from torcheeg.datasets import SanDiegoSSVEPDataset
class TestSSVEPDataset(unittest.TestCase):
def test_tsu_benchmark_dataset(self):
kwargs = {
'record': 'fake_record',
}
kwargs.update(TSUBenckmarkDataset.fake_re... |
bc8792634b88c707055fecd0e30f5adfddcf8356222898a335f5c5a3dbbfde87 | Python | 806 | 29 | # SPDX-FileCopyrightText: 2018, 2024 Sergiu Deitsch <sergiu.deitsch@gmail.com>
#
# SPDX-License-Identifier: Apache-2.0
from PIL import Image
import numpy as np
import os
def load_dataset(fname=None):
if fname is None:
fname = os.path.join(os.path.dirname(__file__), 'data', 'labels.csv')
data = np.ge... |
faee04c8eb1df11c90b8d9c9a355eedb639de6f41e478af4ea5b6ec96e5af46d | Python | 806 | 24 | # from .transformer import TransformerModel
from config import decoder_list
from .rnn_decoder import DecoderRNN
from .tree_decoder import TreeDecoder
from .transformer import TransformerDecoder
def get_decoder(params, *args):
if not params.decoder_type in decoder_list:
raise NotImplementedError(
... |
1be5885e1b256fca88e30bca1782a8058b16314dd7dc1070cac848e4982017f5 | Python | 807 | 26 | """Shared matrix utilities for workflow scripts."""
import numpy as np
from scipy import sparse
def row_normalize(mat, mode="prob"):
"""Normalize a sparse CSR matrix row-wise.
Parameters
----------
mat : scipy.sparse.csr_matrix
mode : {"prob", "norm"}
"prob" normalizes each row to sum to ... |
5b41d482c5ad039380496a93dd7a51838d20e3d1caac6477dc4dc7426bb8849f | Python | 807 | 35 | # built-in
from fractions import Fraction
from math import isclose
# external
import pytest
# project
import textdistance
ALG = textdistance.arith_ncd
@pytest.mark.parametrize('left, right, expected', [
('test', 'test', 1),
('test', 'nani', 2.1666666666666665),
])
def test_similarity(left, right, expected... |
81c2dcdac48c9b818734f004ad26aca4b63f80c20785ea6f88b30565f787b74a | Python | 807 | 29 | from enum import Enum, auto
class SopaEdgeFeature(Enum):
'''Enum class for the different SOPA edge features to be used.'''
# Stabilisation energies
STABILISATION_ENERGY_MAX = auto()
STABILISATION_ENERGY_AVERAGE = auto()
DONOR_NBO_TYPE = auto()
DONOR_NBO_ENERGY = auto()
DONOR_NBO_MIN_MA... |
474f76298bad7a384a83fe0418e7a2ad222bd233de773d128346c5679e3bb6eb | Python | 808 | 25 | """Testing module tree."""
from treem import Tree
def test_tree_traversal():
"""Tests tree traversal."""
tree0 = Tree()
tree1 = tree0.add(Tree())
tree2 = tree1.add(Tree())
tree3 = tree1.add(Tree())
pre = list(tree0.preorder())
post = list(tree0.postorder())
level = list(tree0.levelord... |
8dd58a90af9e86c4393bbd00fcf2941a0cdb4c628cfdc0d37643c01a25dec5ac | Python | 808 | 26 | import numpy as np
import pytest
from sleeplab_format.models import *
from pydantic import ValidationError
def test_samplearray_values(dataset):
for _, subj in dataset.series['series1'].subjects.items():
for _, sarr in subj.sample_arrays.items():
assert np.all(sarr.values_func() == sarr.value... |
fb97a4a56180c7818c8946929f538d500b892bde93b7e538052cdedc16179909 | Python | 808 | 33 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
from downward import suites
import configs
import common_setup
REVS = ["issue436-base", "issue436-v2"]
LIMITS = {"search_time": 1800}
SUITE = suites.suite_optimal_with_ipc11()
configs_optimal_core = configs.configs_optimal_core()
CONFIGS = {}
for name in ['astar_merge... |
10837764af2e370f9865028675677f88f3d56e03e93529d72fef8ae8491e48fa | Python | 809 | 24 | """
Created on Mon Jun 7 23:59:58 2021
@author: Haotian Teng
"""
old_pore_f = "/home/heavens/twilight/CMU/Xron/xron/pore_models/control_hye.1.5mer_level_table.txt"
new_pore_f = "/home/heavens/twilight/CMU/Xron/xron/pore_models/5mer_level_table.model"
title = '\t'.join(['kmer','level_mean','level_stdv','sd_mean'])
wi... |
19769cd9209eb29ef0db1822e2eb7922948613f8359b4d7847a7a137dac4a5ec | Python | 809 | 30 | import pytest
import numpy as np
from .poly_factory import poly_factory
@pytest.mark.parametrize("dim,order", [(1, 1), (2, 2), (10, 5)])
def test_poly_factory(dim, order, eta=1e-6, atol=1e-4):
rng = np.random.RandomState(1)
tol = dict(atol=atol, rtol=eta**2)
my_poly = poly_factory(dim, order)
x0 =... |
f0a8bb0cb34fe09c94a781d0297eec0373c4f4f4217fa45e461a60a0427443ae | Python | 810 | 38 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
from downward import configs, suites
from downward.reports.scatter import ScatterPlotReport
import common_setup
SEARCH_REVS = ["issue528-base", "issue528-v3"]
SUITE = suites.suite_optimal_with_ipc11()
CONFIGS = {
"astar_lmcut": ["--search", "astar(lmcut())"]
}
ex... |
14b1bd2c530ac1871625aad5bc56a4d620714fab801682c47c240dba9df73434 | Python | 811 | 24 | import argparse
import model as module_arch
from parse_config import ConfigParser
from utils import set_random_seed
SEED = 1126
set_random_seed(SEED)
def main(config):
Model = config.init_obj('arch', module_arch)
print(Model)
if __name__ == '__main__':
args = argparse.ArgumentParser(description='PyTorch... |
efa310fa44bd931d8e3d29f64bb80838a8458702df8445a863edb1b083f274d2 | Python | 811 | 31 | from src.data_analysis import Assessment
class Person:
def __init__(self, person_id, cheater_score):
self.__id = person_id
self.__assessments = {}
self.__bad = False
self.__cheater_score = None
if cheater_score != "NA":
self.cheater_score = float(cheater_score)... |
ca9f2300331dc0c8209d909caae23961ae490291d0d812ecdd4960fcb05c7f6f | Python | 812 | 37 | # pylint: disable=too-many-function-args, invalid-name, unused-argument
""" ABIDE ROI dataset loading script"""
import numpy as np
import pandas as pd
from omegaconf import DictConfig
from src.settings import DATA_ROOT
def load_data(
cfg: DictConfig,
dataset_path: str = DATA_ROOT.joinpath(
"abide_ro... |
3d4532de227f314e85f63aaaa4529c6d3e3b90707511a6e114ed8c2ab36ee972 | Python | 813 | 28 | # 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... |
d447820c2ec18beaaee221dfdb40ffcccaf2c964ecce277093c42208b95a46aa | Python | 813 | 21 | """ AgentVars: Initialization of the forgetting model """
import numpy as np
class AgentVars:
""" This class specifies the task parameters of the retroactive interference task """
def __init__(self):
""" this function defines the instance variables unique to each instance """
self.beta = -... |
f5b5a35e10ca836cb95b58f50e5f3012f317550d11400f3133d9f2648a2ba62f | Python | 813 | 20 | TIA_BL_Table = (58, 13, 42, 29, 26, 45, 10, 61,
7, 49, 23, 33, 39, 17, 55, 1,
59, 16, 43, 32, 27, 48, 11, 64,
6, 50, 22, 34, 38, 18, 54, 2,
60, 15, 44, 31, 28, 47, 12, 63,
5, 51, 21, 35, 37, 19, 53, 3,
57, 14, 41, 30, ... |
1642e8922648affa9fb6662dac0f4d72022135be28c79803e87140bda8dcb34a | Python | 814 | 32 | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
dependencies = ["torch"]
from esm.pretrained import (
esm1_t34_670M_UR50S,
esm1_t34_670M_UR50D,
esm1_t34_670M_UR100,
esm1_t12... |
8e6330e000ae3c1ff01676075afbcbbd4a2ead5541a670984ee72f4f5d4341d8 | Python | 814 | 28 | # Run XGBoost from CSV file. Each training/validation example should be
# a single line containing the label as the first value. The model is
# saved as .json
# Modified from https://xgboost.readthedocs.io/en/stable/get_started.html
import xgboost as xgb
import numpy as np
# Read in training and validation data
dt... |
0c9d3059fb304c69d041447041e9536bc8d00b58b55c8ec87d943e53664a05fb | Python | 815 | 19 | """Package to transform the Data.
The modules in this package are classes (and maybe functions) that transform
the data into data again (all the classes defined in datatype.py). Do not
use this package to transform to other classes. If you want to transform to
basic elements, use the package "detect" for example.
"""... |
1e2e986d94d419ed331680c4bf7d52586f1b09aa099520512f398b21f32efe84 | Python | 815 | 21 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
#
# 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
#
# ht... |
537591be9c527684c467c6372412274965f1dff0b97334082b585d64abfac9cd | Python | 815 | 21 | # Merge all the tot_df.csv coming from transform_log_to_csv.py
import argparse
import pandas as pd
parser = argparse.ArgumentParser()
parser.add_argument('-indir', nargs=1, type=str, default='0')
parser.add_argument('-modeldir', nargs=1, type=str)
parser.add_argument('-modelname', nargs=1, type=str)
args = parser.p... |
71817af74fd13b944e892316974072c0bbfc49d071a171088155757b1009df97 | Python | 815 | 25 | import torch
from hotpp.model import GroundEnergy
from hotpp.model.base import MultiAtomicModule
m1 = torch.load("based.pt")
m2 = torch.load("delta.pt")
assert (
m1.cutoff == m2.cutoff
), "Cutoff for two models must be the same (maybe can be different in future)"
assert torch.equal(
m1.all_elements, m2.all_e... |
04bfaaa9c9a928c98784871ad959ddac7e93ca30bbe6ace9a15d87a6e5c8ec42 | Python | 817 | 19 | import unittest
from shapelearningtheory.colors import *
class TestRedXORBlue(unittest.TestCase):
def test_red_or_blue(self):
colors = [RedXORBlue() for _ in range(10)]
red_values = [color.color[:, :, 0] for color in colors]
blue_values = [color.color[:, :, 2] for color in colors]
r... |
10b26d9ca987e818a9f959b9afa5bd0db65f76f7f51f46439264814048a12a11 | Python | 817 | 35 | from numpy.testing import assert_array_equal
from pytest import raises
from wonambi import Dataset
from wonambi.ioeeg import fieldtrip
from wonambi.utils import create_data
from .paths import (fieldtrip_file,
hdf5_file,
)
def test_write_read_fieldtrip():
data = create_dat... |
6c309222da7b64e4267c494b9ae8f48f33d4a38f023d19fe0a63e25b9ebe3ade | Python | 817 | 32 | import numpy as np
from sklearn.feature_selection import f_classif
def f_score(X, y):
"""
This function implements the anova f_value feature selection (existing method for classification in scikit-learn),
where f_score = sum((ni/(c-1))*(mean_i - mean)^2)/((1/(n - c))*sum((ni-1)*std_i^2))
Input
--... |
620ff826fc2555ef81ca86457d20b5c3cbd642c34af5068e3077d301fe257a7c | Python | 818 | 14 | """
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... |
e02135f078a8f669e12610c593a51d59a85de149daa66fd4a166ac038f345168 | Python | 818 | 17 | import os
import scipy.io as sio
from src.BSA_Phantoms.utils import *
from src.BSA_Phantoms.src_nn.main import NOEMRFReconstruction
def main(args):
acquired_data, checkpoint = generate_param_for_main(args)
model_phantoms = NOEMRFReconstruction()
checkpoint = torch.load(os.path.join(os.getcwd() ,'src/BSA_... |
02625f02cf1fda734709c84f51f9fd87b5d5a38af39f203b0132f3152deef81d | Python | 819 | 23 | from torch.autograd import Function
class SimQuant(Function):
@staticmethod
def forward(ctx, x_r: float, x_r_QParams) -> float:
x_q = x_r_QParams.quantize(x_r).to(x_r.device)
min_float = x_r_QParams.min_float.to(x_r.device)
max_float = x_r_QParams.max_float.to(x_r.device)
# ct... |
84d8b3923cd81944f50ab91b2822e76dbb6b8eb081d84378a15824b7efe2b5c2 | Python | 819 | 31 | from elasticai.creator_plugins.combinatorial.language import Port, VHDLEntity
def test_can_generate_entity():
expected = [
"library ieee;",
"use ieee.std_logic_1164.all;",
"entity my_entity is",
"generic (",
"A : int;",
"B : positive",
");",
"port ("... |
51fd02e866054f7bd82d93fcb6f576708e880d3384db15f52f7b1955370bb7b5 | Python | 820 | 33 | import torch
mean = (0.485, 0.456, 0.406)
std = (0.229, 0.224, 0.225)
def preprocess(x, mean, std):
assert x.size(1) == 3
y = torch.zeros_like(x)
for i in range(3):
y[:, i, :, :] = (x[:, i, :, :] - mean[i]) / std[i]
return y
def preprocess_input_function(x):
'''
allocate new tensor l... |
7f42a573af3e3b955a15963b4081d6b54de1bdfe4b434029221d7f32dc29954f | Python | 820 | 27 | import numpy as np
from utils import sa_stats, pickle_dump
conns = {}
for res in ['125']:
conns['Lausanne{}'.format(res)] = np.load('../../data/original_data/'
'consensusSC_{}_wei'
'.npy'.format(res))
niter_arr = [1000, 2... |
6c744a93f8fb412fad1e5a0eb84d00540cd2ffcef0672c431ad54780ca120d35 | Python | 821 | 27 | import torch.nn as nn
def initialize_decoder(module):
for m in module.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_uniform_(m.weight, mode="fan_in", nonlinearity="relu")
if m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.B... |
9fed89c78153741da8d38bb86a3f9a8fb54ba0d5ecf59e1879ff53a37de05385 | Python | 821 | 23 | import numpy as np
import wfdb
import _pickle as pickle
def prepare(NSTDBPath='data/mit-bih-noise-stress-test-database-1.0.0/'):
bw_signals, bw_fields = wfdb.rdsamp(NSTDBPath + 'bw')
em_signals, em_fields = wfdb.rdsamp(NSTDBPath + 'em')
ma_signals, ma_fields = wfdb.rdsamp(NSTDBPath + 'ma')
for key in ... |
a2562f56427185e736e0f7ebad2b8b4652eace13f7db56457764d616b61b3669 | Python | 822 | 20 | # 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... |
fd8cc6bdb76aff9a22083cf9f0a3059a137fa7ce4c11612a18e6072fc569d09a | Python | 822 | 21 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
#
# 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
#
# ht... |
4536aed8675ad9089519ec7f82ca660971c3fb87fb97742fbfce1d409e65bb54 | Python | 823 | 28 | import random
import molecularnodes as mn
from .constants import data_dir
from .utils import NumpySnapshotExtension
def test_ss_label_to_int():
examples = ["TURN_TY1_P68", "BEND64", "HELX_LH_PP_P9", "STRN44"]
assert [3, 3, 1, 2] == [
mn.entities.molecule.pdbx._ss_label_to_int(x) for x in examples
... |
46512de5209c849bc5bda371e36bb22b9d702ac1d000fe73d0b0da2d23d35a2d | Python | 823 | 36 | import numpy as np
import syncopy as spy
def generate_noisy_harmonics(nSamples, nChannels, samplerate):
f1, f2 = 20, 50 # the harmonic frequencies in Hz
# the sampling times vector
tvec = np.arange(nSamples) * 1 / samplerate
# define the two harmonics
ch1 = np.cos(2 * np.pi * f1 * tvec)
ch2... |
4baf6bd2435464d2a8e3fee372f0b41a242760c4e63be129ef2172c4533835c1 | Python | 823 | 37 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import os
from downward import suites
from lab.environments import LocalEnvironment, MaiaEnvironment
from common_setup import IssueConfig, IssueExperiment, is_test_run
REVS = ["issue551-base", "issue551-v5"]
BENCHMARKS = os.path.expanduser('~/downward-benchmarks')
SUI... |
c70c5540a01837fe24d39b921e086e580a78a176570c6a8059a5d3e0c53ebe9f | Python | 823 | 22 | from elasticai.creator.base_modules.relu import ReLU as ReLUBase
from elasticai.creator.nn.design_creator_module import DesignCreatorModule
from .design import ReLU as ReLUDesign
class ReLU(DesignCreatorModule, ReLUBase):
def __init__(self, total_bits: int, use_clock: bool = False) -> None:
"""Quantized ... |
1ba40cec139895c75dc4cd29b2afe30ece18968f10a683b4080a7626f5bfebd8 | Python | 824 | 17 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
#
# 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
#
# ht... |
7a842152837842286f49aeb4ad7603cdca13bdcc94614af8c5e2c68e74b6ab54 | Python | 824 | 35 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
from downward import suites
from relativescatter import RelativeScatterPlotReport
import common_setup
REVS = ["issue560-base", "issue560-v1"]
SUITE = suites.suite_all()
# We are only interested in the preprocessing here and will only run the first steps of the experime... |
551f4571b3fabe9185e40abeb05a2c25758faa860cc0987177c5da6a18496b3a | Python | 825 | 38 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
from downward import configs, suites
from downward.reports.scatter import ScatterPlotReport
import common_setup
SEARCH_REVS = ["issue528-base", "issue528-v1", "issue528-v2"]
SUITE = suites.suite_optimal_with_ipc11()
CONFIGS = {
"astar_lmcut": ["--search", "astar(l... |
98f965fe42fe2cb66bcda13930cada5830f32efc4f5a225c8c6e12ce99f39657 | Python | 825 | 23 | from typing import cast
import torch
from elasticai.creator.base_modules.conv1d import MathOperations as Conv1dOps
from elasticai.creator.base_modules.linear import MathOperations as LinearOps
from elasticai.creator.base_modules.lstm_cell import MathOperations as LSTMOps
from .binary_quantization_function import Bin... |
a0ea72b8acc572ed80d543be4ead1775fdf7b99752627cf9d917d3e9827955b9 | Python | 825 | 31 | from typing import Optional, List, Union
from .utils import dataset_mapping
from .md17 import RevisedMD17
from .asedata import ASEData, ASEDBData
from .dpmd import DeePMDData
from .ptdata import PtData
from .data_interface import LitAtomsDataset
__all__ = ["RevisedMD17", "ASEData", "ASEDBData", "DeePMDData", "PtData",... |
acbd1fe906946ac45e92da90364317a5b18a638d83fc0e11760c5844253e6fe7 | Python | 825 | 26 | import torch
import torch.nn as nn
import torch.nn.functional as F
dtype = torch.float32
class DDIPredictor(nn.Module):
def __init__(self, encoder, latent_dim=128, num_tasks=1, **kwargs):
super().__init__()
self.encoder = encoder
self.predictor = nn.Sequential(
nn.... |
f6f00eb36b4be51b82944b324d2f0a8088c7d5ccbda2811a2afe92ef59e5a643 | Python | 825 | 29 | import collections.abc
from itertools import repeat
def _ntuple_same(n):
def parse(x):
if isinstance(x, int):
return tuple(repeat(x, n))
elif isinstance(x, collections.abc.Iterable):
assert len(set(x))==1, 'the size of kernel must be the same for each side'
retur... |
9627c6e757762823aa9adbada3c3d4fc0cf69be27f986600adf25ad7a38213fa | Python | 826 | 27 | import pandas as pd
def init_file_pandas(filename: str, columns: list):
"""
A general purpose function for quickly initialising csv files using pandas.
:param filename: The path leading to the file.
:param columns: The desired column names.
:return: No return value.
"""
data = pd.DataFrame... |
5f9a1743093abd70828869e1cf28bafd5c198e57ab6f4f1d08498279e93916eb | Python | 827 | 30 | """
Stitching module for brain section tile assembly.
Provides the stitching pipeline, GUI, and core algorithms as a self-contained
module package, mirroring the structure of regtools/registration/.
Structure
---------
- core/ : Stitching algorithms (tile assembly, deformation correction, etc.)
- gui.py ... |
a914bc7fcb500477010ce025782701059e3703df17eb6c7ef3c517ebc8c1db46 | Python | 827 | 24 | import os
import os.path as op
from neurosynth.base.dataset import download
from nimare.io import convert_neurosynth_to_dataset
def neurosynth_download(ns_data_dir=None):
if ns_data_dir is None:
raise Exception('A valid directory is required for downloading Neurosynth data!')
dataset_file = op.join(... |
fb5e5b4aaf4d631fee95c50df30b4b5846fadb64a12a26702a8ce27f1cedc5e5 | Python | 827 | 20 | #!/usr/bin/env python
# config: same with train config, but only needs data section and target section
import argparse
parser = argparse.ArgumentParser(description='Analyze the dataset and give the detailed analysis of prediction target')
parser.add_argument('config', type=str, metavar='CONFIG', help='Config file for ... |
35c5957cae3540fbc5ae673d8f77e4efd36886c5dab0552cc7f3b64013219fb5 | Python | 828 | 24 | import pytest
import torch
from elasticai.creator.arithmetic import FxpParams
from elasticai.creator.nn.fixed_point.mac.layer import MacLayer
@pytest.mark.parametrize(
"x1, x2, expected",
[
# 00001 * 00010 + 00100 * 00001 -> 00000 00010 + 00000 00100 -> 00000 00110
((0.25, 1.0), (0.5, 0.25), ... |
5e7a3f09c71c595f6f0158eac03310a40fe67a0ae377a496a070400863e326ed | Python | 828 | 33 | # built-in
from itertools import islice
from pathlib import Path
from sys import argv
# project
from textdistance import EntropyNCD
# read files
licenses = dict()
for path in Path('choosealicense.com', '_licenses').iterdir():
licenses[path.stem] = path.read_text()
# show licenses list if no arguments passed
if ... |
de55b6d0f99f5bd65ae72f595d08073bfcedf69ddfa72a17b9a17b968dd0dd02 | Python | 828 | 23 | def all_within_tolerance(result: list[int], expected: list[int], tol: int = 1) -> bool:
if len(result) != len(expected):
raise ValueError("Length mismatch")
return all(abs(r - e) <= tol for r, e in zip(result, expected))
def is_mae_within_tolerance(
result: list[int], expected: list[int], tol: flo... |
bb2c9ff217fae1f54c111c780c5bc64bd5fd20bff55610dd8e2758bbd6e6ace8 | Python | 829 | 33 | import sys
from pybioshell.core.data.io import find_pdb, write_ss2
if len(sys.argv) < 2 :
print("""
Extracts amino acid (or nucleotide) sequence from a PDB file.
USAGE:
python3 pdb_to_ss2.py input.pdb [input.ss2]
EXAMPLE:
python3 pdb_to_ss2.py 2gb1.pdb 2gb1.out
python3 pdb_to_ss2.py 2kwi.pdb
CATE... |
1a87546ee0745fb462fd00ffe1e97178fa4ae157e8e54856bc0917cfc855869f | Python | 830 | 26 | from ._binarize_activations import binarize_activations
from ._precomputation import PrecomputationStrategy, make_precompute_rule
from ._precomputation_impls import precompute_linear
from ._remove_redundant_layers import remove_redundant_layers
from ._reorder import reorder
from ._shape_inference import (
AttachFil... |
2123bea42c4cfecb8017e6a854b8a3c62a1787efafb992a0af7e99c287867c4b | Python | 830 | 32 | from __future__ import annotations
import pytest
jf = pytest.importorskip("jobflow")
from pathlib import Path
from quacc import get_settings, job, redecorate, strip_decorator
def test_strip_decorators():
@job
def add(a, b):
return a + b
stripped_add = strip_decorator(add)
assert stripped_a... |
b20c6b4910ce28bdb8d0c6829e129d2afe380ac38b93de9d85a152f11deb4667 | Python | 830 | 38 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import os
from downward import suites
import common_setup
DIR = os.path.dirname(os.path.abspath(__file__))
REPO = os.path.dirname(os.path.dirname(DIR))
REVS = ["issue414-base", "issue414"]
LIMITS = {"search_time": 1800}
SUITE = suites.suite_satisficing_with_ipc11()
... |
623dc5a5b5abe533ab8ef40896e07ec914eb7f3344902193cf9ff86be728928b | Python | 831 | 26 | import unittest
from neurolib.utils.loadData import Dataset
class TestDatasets(unittest.TestCase):
def test_dataset_gw(self):
ds = Dataset("gw", fcd=True)
self.assertTupleEqual(ds.Cmat.shape, (80, 80))
self.assertTupleEqual(ds.Dmat.shape, (80, 80))
self.assertTupleEqual(ds.FCs[0].... |
a1ce5c9caa0762cab0be57f737ec129a6112cf2462b8e0899239f9eea2400cc7 | Python | 831 | 28 | import cv2
import numpy as np
"""
This module contains code for performing filtering operations on images
"""
def high_pass_filter(image: np.ndarray,
windowSize: int,
sigma: float) -> np.ndarray:
"""
Args:
image: the input image to be filtered
windowS... |
a6647184b8cdda812a76cf48bb18823bb90308bd4c438d862aee193e47b5bcd2 | Python | 831 | 25 | """msfeature — microsaccade selectivity feature extraction and decoding.
Implements the Engbert & Kliegl (2003) microsaccade detection algorithm
with the monocular / 1° amplitude cap / 30 ms refractory merge / 2.5 SD
amplitude-outlier rejection variants used in Nouri et al. 2025 (iScience).
References:
Engbert R,... |
e08ee0a066930e25962230a970bc7625bf88559519ea06d72df792e56a660259 | Python | 831 | 33 | from __future__ import annotations
from pathlib import Path
from shutil import rmtree
import pytest
TEST_SCRATCH_DIR = Path(__file__).parent / "_test_scratch"
@pytest.fixture
def jobflow_output():
"""Return the latest stored output for a Jobflow job."""
def get_output(responses, job):
indexed_resp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.