sha256 stringlengths 64 64 | language stringclasses 27
values | size int32 1 491k | lines int32 1 21.8k | content stringlengths 1 200k |
|---|---|---|---|---|
d96ec144553b4d322eec0ffe9a6b4a4fed6ec23975b6f578f9fe3770eff4622e | Python | 2,176 | 60 | import numpy as np
from sklearn.model_selection import GridSearchCV, KFold
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeRegressor
from sklearn.svm import SVR
from sklearn.metrics import make_scorer, mean_squared_error
try:
from xgboost import XGBRegressor
_HAS_XGB = Tr... |
fc9e0c1522d41b586221f8a27e0948d270fefa54b70aac088ca28cde2b344ba4 | Python | 2,176 | 72 | """Provide class for testing in French locale
"""
import sys
import locale
import pytest
__ALL__ = ['CommaDecimalPointLocale']
def find_comma_decimal_point_locale():
"""See if platform has a decimal point as comma locale.
Find a locale that uses a comma instead of a period as the
decimal point.
R... |
80143764b219cf9232c93b2efd3cd5e827b765b9b862fc7c6a5fd587542d81f0 | Python | 2,177 | 84 | import numpy as np
from dp5.nmr_processing.helper_functions import generalised_lorentzian as p7
def p7residual(params, x, picked_points, y_data, region, differential):
"""
- params: lmfit Parameters object
"""
y = np.zeros(len(x))
for peak in picked_points:
y += p7(x, params['mu' + str(p... |
7ab791552f209e2058f4959071aeef31e42711dcd9042542e0be4bf5ef96cd17 | Python | 2,179 | 85 | # !/usr/bin/python
# -*- Mode: Python; tab-width: 4; py-indent-offset: 4; -*-
#
# An OpenGL movie class with buffer (buffermovie.py)
#
# 01-09-2009: sn
# A movie class with buffer
#
import sys, os
from string import *
import pygame
from pygame.locals import *
class buffermovie:
"""
A class to load and store mov... |
e2a21ab26571bf99f7262d7c423f3c23eb3f66290c2f6ecfd69bdc11dc8511c4 | Python | 2,179 | 54 | import os
import nibabel as nib
from nilearn.input_data import NiftiLabelsMasker
import numpy as np
atlas = 'AAL' #AICHA, AAL
if atlas == 'AAL':
atlas_path = r'path_to\AAL3v1.nii'
else:
atlas_path = r'path_to\AICHA.nii'
tr = 0.72
bandpass = (0.01, 0.1)
def extract_roi_signals(fmri_path, atlas_path, save_path,... |
60d35fc0f4525937ee7902f96a2325eb1bfc90d00e9f1c3e3f7f0403ebd42ad2 | Python | 2,181 | 69 | """
Git Utility helpers for CLI tasks.
"""
import logging
from pathlib import Path
from cli.lib.common.path_helper import remove_dir
from git import GitCommandError, RemoteProgress, Repo
logger = logging.getLogger(__name__)
class PrintProgress(RemoteProgress):
"""Simple progress logger for git operations."""
... |
ecd3b74c8b13fef4308aa3d7adafaba113731b69f9790cf7469c518519e188b2 | Python | 2,181 | 65 | """
Example demonstrating how to use cotengra's strip_exponent = True
to avoid overflow and underflow in large tensor network contractions.
"""
import numpy as np
import tensornetwork as tn
import tensorcircuit as tc
# Set backend to JAX for JIT and potential large scale simulation
tc.set_backend("jax")
tc.set_dtype(... |
975b822634b1b5575255e863a94e20f241dd9f6a633eda3598bf041b86796533 | Python | 2,182 | 101 | # %%
from importlib import reload
import mne
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
import seaborn as sns
import pickle
jitters = [f"j{i}" for i in range(8)]
ch_picks = ["Fz", "F1", "F2", "AF3", "AF4", "AFz", "F3", "F4", "FC1", "FC2", "FCz"]
topo_times = np.arange(0.1, 0.35, 0.05)
... |
a78bd6f6b24414b3c1a84207311e5f0a6a3653e2414ef8270cd77be18ec316e2 | Python | 2,182 | 72 | from __future__ import annotations
from typing import TYPE_CHECKING
from pandas._libs import lib
from pandas.compat._optional import import_optional_dependency
from pandas.util._validators import check_dtype_backend
from pandas.core.dtypes.inference import is_list_like
from pandas.io.common import stringify_path
i... |
7817689d4e67f73b1b0bce80b1c1c22f117af17aa2aa1596c81255fbb60239d0 | Python | 2,183 | 62 | import numpy as np
import pytest
import pandas as pd
@pytest.fixture
def data():
"""Fixture returning boolean array, with valid and missing values."""
return pd.array(
[True, False] * 4 + [np.nan] + [True, False] * 44 + [np.nan] + [True, False],
dtype="boolean",
)
@pytest.mark.parametri... |
b4dd9560ed6cb40f3a0f264afcf29374990cb825892ce70d12cd622b08a3f180 | Python | 2,184 | 63 | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 18 13:01:00 2020
@author: SHEN WANXIANG
"""
import warnings
warnings.filterwarnings("ignore")
import matplotlib.pyplot as plt
import seaborn as sns
def imshow(x_arr, ax, mode = 'dark',
color_list = ['#ff0c00','#25ff00', '#1300ff','#d000ff','#e2ff00'... |
0bf85ba3952bb66abe7b1b03c1be14d4a4ffb82f9edff2071397786bf686414e | Python | 2,187 | 94 | #!/usr/bin/env python3.7
"""Use this script to run a convergence study.
The copyrights of this software are owned by Duke University.
Please refer to the LICENSE.txt and README.txt files for licensing instructions.
The source code can be found on the following GitHub repository: https://github.com/wmglab-duke/ascent.... |
b04a69c0c83c05b46aea513eb064750e31e973964b3b56e39961fa55908f3d25 | Python | 2,190 | 89 | """Use this script to run a convergence study.
The copyrights of this software are owned by Duke University.
Please refer to the LICENSE.txt and README.txt files for licensing instructions.
The source code can be found on the following GitHub repository: https://github.com/wmglab-duke/ascent.
Threshold error will be ... |
2e32ccabc1a436bb0854d7d3aee8cbbff4e52a8efda00fd76e935416cfa9a954 | Python | 2,191 | 62 | import pytest
from pandas import (
CategoricalIndex,
Index,
)
import pandas._testing as tm
class TestAppend:
@pytest.fixture
def ci(self):
categories = list("cab")
return CategoricalIndex(list("aabbca"), categories=categories, ordered=False)
def test_append(self, ci):
# a... |
cdc69c6cef818b16936de45e85006119e48464da50cef353b02daf0b4c664d62 | Python | 2,191 | 90 | """Use this script to run a convergence study.
The copyrights of this software are owned by Duke University.
Please refer to the LICENSE.txt and README.txt files for licensing instructions.
The source code can be found on the following GitHub repository: https://github.com/wmglab-duke/ascent.
Threshold error will be ... |
142b4fee0df8015b8c21aa90947f005756417485176e4e46ede05e7934abd731 | Python | 2,192 | 63 | import os
from distutils.msvc9compiler import MSVCCompiler as _MSVCCompiler
from .system_info import platform_bits
def _merge(old, new):
"""Concatenate two environment paths avoiding repeats.
Here `old` is the environment string before the base class initialize
function is called and `new` is the string... |
59fbce0b1023098db16a97f26f751c8cc1cce8cf87614f659a7b8fb989088aff | Python | 2,192 | 72 | # %%
import glob
import os
import numpy as np
species_list = ['hsapiens',
'ptroglodytes',
'mmulatta',
'mmusculus',
'btaurus',
'dnovemcinctus',
'sharrisii',
'oanatinus',
'ggallus',
... |
0d1142d59a8ae35a2d0be78fd7a90edf1bd6a79039ff9c6d24e4bce9e53b010d | Python | 2,197 | 55 | import bisect
import math
from typing import List
from omegaconf import DictConfig
import torch
class LRScheduler:
def __init__(self, cfg: DictConfig, optimizer_cfg: DictConfig):
self.lr_config = optimizer_cfg.lr_scheduler
self.training_config = cfg
self.lr = optimizer_cfg.lr
ass... |
195018a96965d236dea5faed21c668e97efa3e38f4ca42260cbe9e8cd848d7c5 | Python | 2,197 | 71 | import re
import math
import time
import random
from pathlib import Path
import numpy as np
from torch import nn
def set_random_seed(index: int):
seed = int(time.time() * 1000.0) + index
random.seed(seed)
np.random.seed(seed % (2 ** 32 - 1))
def get_lr(base_lr: float, batch_size: int, base_batch_size:... |
d40926a25413b4c6115a6d213dcdce765e335587d96f0416f27d0a916aec9a8d | Python | 2,199 | 93 |
# parse the arguments
import argparse
import torch
from datetime import datetime
from utils import Option, metricSummer, calculateMetrics, dumpTestResults
parser = argparse.ArgumentParser()
parser.add_argument("-d", "--dataset", type=str, default="abide1")
parser.add_argument("-m", "--model", type=str, default="b... |
031ce40efeb04f25002bd9295d71fe9635e677c2e1ce37c39e8ef22de0c8e6ed | Python | 2,202 | 69 | """
VQE optimization over different parameter initializations and different circuit structures
"""
import tensorflow as tf
import numpy as np
import tensorcircuit as tc
K = tc.set_backend("tensorflow")
n = 6
lattice = tc.templates.graphs.Line1D(n, pbc=False)
h = tc.quantum.heisenberg_hamiltonian(
lattice, hzz=1,... |
31d5323c5f186e49f735b343053d8c370260274d06f4592ea3d08fb62c402aa0 | Python | 2,202 | 64 | import pandas as pd
import sqlite3
import os
from multiprocessing import Pool
import numpy as np
import sys
output_dir=sys.argv[1]
db_dir=sys.argv[2]
processors=int(sys.argv[3])
fun_db_file=sys.argv[4]
anno_type=sys.argv[5]
mapping_taxa_df=pd.read_csv(output_dir+'/mapping_taxa_df.csv',sep=',',header=0)
taxonomyInfoD... |
cf6b8cd355a75d2288ee9c8898564b57e99a89c989e64a6e243693389d967eb7 | Python | 2,203 | 59 | import sys
sys.path.append('.')
import seaborn as sns
from plotting.utils import load_results, mesh_name, sim_name, set_plotting_defaults, efcolor, pvscolor, ecscolor, occolor, dpi
import matplotlib.pyplot as plt
if __name__ == '__main__':
sim_names = sys.argv[1::2]
mesh_names = sys.argv[2::2]
ns = len(sim_na... |
67ab248d5a5518bfd6788bc60f94323f9a25fc3daaecbc08c4565b416c74effc | Python | 2,204 | 52 | from wordfreq import tokenize
def test_apostrophes():
# Test that we handle apostrophes in French reasonably.
assert tokenize("qu'un", "fr") == ["qu", "un"]
assert tokenize("qu'un", "fr", include_punctuation=True) == ["qu'", "un"]
assert tokenize("langues d'oïl", "fr") == ["langues", "d", "oïl"]
a... |
147a6aa165d69ffa40846748dbe7ec575c267090f3c7bd42fed8d0cab08cfc7d | Python | 2,207 | 57 | # License: GNU Affero General Public License v3 or later
# A copy of GNU AGPL v3 should have been included in this software package in LICENSE.txt.
""" A collection of functions for running muscle.
"""
from tempfile import NamedTemporaryFile
from typing import Dict
from antismash.common.fasta import read_fasta, writ... |
6de640cac1495d26cb17ef1d259f905bde9ed6a00c3538e94a1222d6ed28e192 | Python | 2,210 | 71 | import scipy
import numpy as np
import pandas as pd
import scanpy as sc
# Load in AnnData
adata = sc.read_h5ad(snakemake.input.merged_rna_anndata)
# Plot the first round of rough cell typing
sc.pl.umap(
adata,
color='cell_type',
legend_loc='on data',
show=False
)
plt.savefig(snakemake.output.course_ce... |
2c92e736ab8977d0cc17cb01400d804cc06d6c69b186414f84802b3238798097 | Python | 2,213 | 44 | # License: GNU Affero General Public License v3 or later
# A copy of GNU AGPL v3 should have been included in this software package in LICENSE.txt.
# for test files, silence irrelevant and noisy pylint warnings
# pylint: disable=no-self-use,protected-access,missing-docstring
import os
import tempfile
import unittest
... |
c1de983ef1faea0d731ee1e032ee7d9e745b1f583d1a39532b82201369ef48fd | Python | 2,213 | 61 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 25 19:50:23 2019
@author: sychoi
"""
import os
import sys
import scipy.io as spio
import numpy as np
from tqdm import tqdm
bfp_path = '/home/sychoi/Documents/MATLAB/bfp/'
sys.path.append(os.path.join(str(bfp_path), 'src/BrainSync/'))
from brainsyn... |
6e649e5305082b9fe93457baaf1463e0b6cf910f83232941ed2b6c2e030edce8 | Python | 2,215 | 58 | import numpy as np
import pandas as pd
import scanpy as sc
import polars as pl
import pyranges as pr
# Read in rna observation data
rna = sc.read_h5ad(snakemake.input.merged_rna_anndata)
# Port cell data from final RNA atlas to cisTopic pseudobulked
cell_df = rna.obs
# Metadata specific column names
sample_value = s... |
231a18e183614ded8e6d588339f22938eae7b3398c046139363a5acd338f9de2 | Python | 2,216 | 75 | import argparse
import logging
import os
from nmf_analysis import data
from nmf_analysis import settings as s
from nmf_analysis import transformers as t
logger = logging.getLogger(__name__)
logging.getLogger().setLevel(logging.INFO)
def generate() -> None:
"""
Load the dataset, generate vectors and store in... |
a172fd58fac65ed356c37dcef3169df40f2ef273b67a63b90bf66b936f19142a | Python | 2,218 | 81 | import time
import optax
import tensorcircuit as tc
tc.set_dtype("complex64")
K = tc.set_backend("jax")
# jax is more GPU friendly for this task,
# while tf is more CPU efficient for this task
tc.set_contractor("cotengra-1024-8192")
# more trials for better contraction path
n, m, nlayers = 4, 4, 6
coord = tc.template... |
e5b562c961fbd30f2f31b50712e40de3bde89ef5981fb75f1425b19fdb9ae6c5 | Python | 2,218 | 98 | # _*_ coding: utf-8 _*_
import itertools
import random
from csv_io import write_to_csv as writeToFile
import cPickle
'''
Sequences will be generated as lists, containing all possible combinations of intersections (4), directions (4) and targets (2)
The sequences are encoded as follows: (intersection, direction (sta... |
f123692e6516679c21c5ddb94da82bb1176fcca944d623820a69ef164cd1274a | Python | 2,220 | 62 | # Copyright 2024 RADar-AZDelta
# SPDX-License-Identifier: gpl3+
import logging
from pathlib import Path
from ..import_vocabularies import ImportVocabularies
from .etl_base import SqlServerEtlBase
class SqlServerImportVocabularies(ImportVocabularies, SqlServerEtlBase):
"""
Class that imports the downloaded v... |
98866d099f0f10839dea9c4ba9d530b37c0c7d7523b153b7bce13dbcae583ddf | Python | 2,221 | 54 | from numpy.testing import assert_
import numbers
import numpy as np
from numpy._core.numerictypes import sctypes
class TestABC:
def test_abstract(self):
assert_(issubclass(np.number, numbers.Number))
assert_(issubclass(np.inexact, numbers.Complex))
assert_(issubclass(np.complexfloating, ... |
fd5113db6cfa8df44b8e0e034ddc8679c2f26e48ea347617fc8352d566fdc1e5 | Python | 2,221 | 63 | # -*- coding: utf-8 -*-
import numpy as np
import os
import pandas as pd
import sys
import torch
from tqdm import tqdm
from source.data.base import read_data, get_windowed_data
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
class BloodGlucoseCSVDataset(torch.utils.data.Dataset):
def __init__(self, ... |
904668970651562738203466a22789a84a1ba7191f176347f4ffa4e93f06ece9 | Python | 2,222 | 74 | """Configuration file.
All static variables can be assigned in this settings.py file
"""
import logging
import logging.config
import sys
from pathlib import Path
import pretty_errors # NOQA: F401 (imported but unused)
from rich.logging import RichHandler
# Directories
ROOT_DIR = Path(__file__).parent.parent.absolut... |
e1cd479a32f93094b197b19d3a1be367abc23d470d412073c8c09cdb2abd6201 | Python | 2,222 | 96 | from __future__ import annotations
import pytest
from .. import resources
from textstat.backend import selections
@pytest.mark.parametrize(
"text, syllable_threshold, lang, expected",
[
(
"The quick brown fox jumps over the lazy dog",
2,
"en_US",
[],
... |
7b408145e96088048219d07534544c4abd3805b6a0823c8701962f994521d6c3 | Python | 2,223 | 72 | import numpy as np
from pandas import (
DataFrame,
MultiIndex,
Series,
)
import pandas._testing as tm
class TestDataFramePop:
def test_pop(self, float_frame, warn_copy_on_write):
float_frame.columns.name = "baz"
float_frame.pop("A")
assert "A" not in float_frame
floa... |
d2666f9cc61f944153a3181c5be2ffc2cb1e77021594d9326fb757b747358357 | Python | 2,223 | 65 | # Run: pytest tests/test_all.py
# All functions to be tested should start with test_ prefix
import warnings
import os
import subprocess
import pytest
import numpy as np
import opm_unshear.gpu
import opm_unshear.cpu
from opm_unshear import gpu_available
if not gpu_available:
warnings.warn("No GPU detected. Skipp... |
1dcb3fa38c5829920e025168575fd7d88235f64a55a740d3339e07a4526fafbd | Python | 2,224 | 87 | from typing import TYPE_CHECKING, Any, List, Optional
from napari.layers import Image
from .base import IMCFileTreeItem, ModelBase
if TYPE_CHECKING:
from .imc_file import IMCFileModel
class IMCFilePanoramaModel(ModelBase, IMCFileTreeItem):
imc_file_tree_is_checkable = True
def __init__(
self,
... |
c23e7c5b70db131797aa4f010301ad8c82d9793aa5f76a7cb1dab1d56651b42c | Python | 2,226 | 56 | # License: GNU Affero General Public License v3 or later
# A copy of GNU AGPL v3 should have been included in this software package in LICENSE.txt.
# for test files, silence irrelevant and noisy pylint warnings
# pylint: disable=no-self-use,protected-access,missing-docstring
from unittest import TestCase
from Bio.Seq... |
3350595669927cceb41c8859044c6d242f30326b62ae02f03063dbf00d2774f2 | Python | 2,227 | 73 | """
ThresholdCell
This class implements a single neuron whose activity is determined by applying a sigmoid activation function to its net excitatory input received from other modules. The neuron does not have intrinsic connections; all input arrives through inter-modular feedback connections.
The neuron's dynamics fo... |
6d05dcae0e829789163d9885009d4cce73cbe8bdc2c0d39566a7913bacbd66c1 | Python | 2,227 | 60 | from tensorflow.keras.models import load_model
from tensorflow.keras.utils import get_custom_objects
import argparse
import tensorflow as tf
import numpy as np
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Cropping1D, add, Conv1D, GlobalAvgPool1D, Dense, Add, Concatenate, Lambda, ... |
a5210e21a58811de90fb55043d81056ac94676d3b45f02aa35ac02bdfdd9a70a | Python | 2,227 | 92 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 17 16:54:12 2019
@author: wanxiang.shen@u.nus.edu
@usecase: statistic features' distribution
"""
import numpy as np
import pandas as pd
from joblib import Parallel, delayed
from tqdm import tqdm
from molmap.utils.multiproc import MultiProcessU... |
5d35b34dbb5a2d118576b8df453247dd34de743f18d2e0964738e2d6a9eb764e | Python | 2,228 | 91 | """
Tests that work on both the Python and C engines but do not have a
specific classification into the other test modules.
"""
import csv
from io import StringIO
import pytest
from pandas import DataFrame
import pandas._testing as tm
from pandas.io.parsers import TextParser
pytestmark = pytest.mark.filterwarnings(... |
9ae8a72838435adf7317be00693f207b719fd507049f20771e0b47d79de308c9 | Python | 2,229 | 60 | import utils
import numpy as np
from acc_predictor.factory import get_acc_predictor
class AdaptiveSwitching:
""" ensemble surrogate model """
""" try all available models, pick one based on 10-fold crx vld """
def __init__(self, n_fold=10):
# self.model_pool = ['rbf', 'gp', 'mlp', 'carts']
... |
d34d8d376d3b43117121be8f31fc9938cc9cf55e49b10a4cd33c27edff33239d | Python | 2,238 | 54 | # Load packages for data analysis
import pandas as pd
# Load packages for Big Query
from google.cloud import bigquery
import os
# Define configurations for Big Query - Stride Datalake
project_id = 'som-nero-phi-boussard' # Location of stride datalake
es = "som-nero-phi-boussard.ES_ACU_Oncology"
client = bigquery.Cli... |
f26b4d0baa8ea67427c008987c5e939d5ecd71e1d43d05af40f461608599c997 | Python | 2,239 | 52 | import argparse
from tqdm import tqdm
import numpy as np
from src.submission import evaluate_folds_predictions, make_submission
from src.data import get_mouse_data
from src import constants
def parse_arguments():
parser = argparse.ArgumentParser()
parser.add_argument("-e", "--experiments", required=True, ty... |
4637169751842f0892614f158736b45970d46ded9831851afa1bea1da8cef11b | Python | 2,241 | 82 | """
Boost the Monte Carlo noise simulation (specifically the staging time)
on general error with circuit layerwise slicing: new paradigm,
essentially the same as v1, but much simpler
"""
import time
import tensorcircuit as tc
tc.set_backend("jax")
n = 6 # 10
nlayer = 5 # 4
def precompute(c):
s = c.state()
... |
85514141ecd0df38f813276859b1508ff69f3d4a6932deebf493c0958db653a6 | Python | 2,244 | 66 | import logging
from optparse import Values
from pip._internal.cli.base_command import Command
from pip._internal.cli.status_codes import ERROR, SUCCESS
from pip._internal.metadata import get_default_environment
from pip._internal.operations.check import (
check_package_set,
check_unsupported,
create_packag... |
64e8cb6ff058a6050ab5721a543d7d40d4d9054cd4f62b18221d580279b5852b | Python | 2,249 | 78 | import itertools
from operator import itemgetter
import os
import tempfile
import numpy as np
import pytest
from yass.batch import RecordingsReader
@pytest.fixture
def path_to_long(request):
temp = tempfile.NamedTemporaryFile(delete=False)
path = temp.name
def delete_file():
os.unlink(path)
... |
8e2a97600fe6873550b130ac87e98ce88e34ac19cdf915a805a2688f617a954e | Python | 2,252 | 80 | """
Optimization for performance comparison for different densities of two-qubit gates
(random layouts averaged).
"""
import tensorflow as tf
import numpy as np
import cotengra as ctg
import tensorcircuit as tc
K = tc.set_backend("tensorflow")
optr = ctg.ReusableHyperOptimizer(
methods=["greedy"],
parallel=Tr... |
0764f8bc4b7d52a7f2eda7f2173285227ccb5027599682f2b63311a9de4bfa17 | Python | 2,254 | 76 | import heapq
import numpy as np
import jax.numpy as jnp
def lowest_energy_vectors(omegas, K, max_occupancy):
"""
omegas: list of harmonic frequencies
K: number of lowest energy occupation vectors to return
max_occupancy: scalar maximum for each v_i (uniform)
Returns:
List of (energy, matr... |
6f5a654a05fed336db9b241568cebf5bc10c513549bd82f63c82633b70a548e3 | Python | 2,254 | 79 | #!/usr/bin/env python3
"""
run_biogpt.py
Simple script to run BioGPT locally on GPU.
Requirements:
pip install torch transformers sacremoses protobuf
"""
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
def load_model(use_fp16: bool = True):
"""
Load BioGPT model and t... |
63b835107241cbf374e15aa879435cae1f0417ff3c3955e498299f76c9402c5d | Python | 2,255 | 70 | import numpy as np
from typing import List, Tuple
from asap.dataloader import bw_to_data
from asap.dataloader.base import BaseDataset
class BoundedDataset(BaseDataset):
def __init__(
self,
genome: str,
signal_files: str,
chroms: List[int],
window_size: int,
margin_s... |
b36c10f0cca4a0be53a9eb4502a9c94fde3903c82c8e22b4bd251abcd9524000 | Python | 2,257 | 94 | import numpy as np
from cali.extraction._oasis_suite2p import (
oasis,
oasis_trace,
preprocess,
)
def test_oasis_trace() -> None:
"""Test oasis_trace low-level function."""
# Create a simple trace with a spike
T = 100
tau = 1.0
fs = 30.0
# Create synthetic calcium trace
# Spi... |
0fe4bc41b5bacd5c13bad661c0f86632f861d435dfd5d15c6f74aa4354641c32 | Python | 2,259 | 82 | #!/usr/bin/env python
from __future__ import division
from __future__ import print_function
import os
import sys
import argparse
script_path = os.path.realpath(__file__)
root_dir = os.path.dirname(os.path.dirname(script_path))
sys.path.append(root_dir)
from bfx import getreads
ARG_DEFAULTS = {}
USAGE = "%(prog)s [opti... |
970d1d4cef9a65f2d77e65964014f897401ba665e79013ff8df5eaad660c61b7 | Python | 2,259 | 70 | import math
import cv2
import numpy as np
def average_channels(image: np.ndarray) -> np.ndarray:
# Convert to grayscale by averaging the channels
# (height, width, num_channels) -> (height, width, 1)
return np.mean(image, axis=2, keepdims=True)
def resize_image_keep_aspect_ratio(image, target_width, ta... |
a3d5c5f601e542010e1dbba30dfb2769a0a60b2b1ea681886de52ca045a014e5 | Python | 2,260 | 86 | import time
from window import Window
from environment import *
class ManualControl(object):
"""ManualControl of HumanVatGoalEnv Class"""
def __init__(self, env=HumanVatGoalEnv()):
self.env = env
self.window = Window(env.descr + "[manual]")
self.window.reg_key_press_handler(self._key_... |
ccd0501ea333176d7003d557ceeb4430e978fecf6f95795b2acd83c69e8c4763 | Python | 2,260 | 63 | # implementation based on
# https://github.com/yn-sun/e2epp/blob/master/build_predict_model.py
# and https://github.com/HandingWang/RF-CMOCO
import numpy as np
from sklearn.tree import DecisionTreeRegressor
class CART:
""" Classification and Regression Tree """
def __init__(self, n_tree=1000):
self.n_... |
bc07547c65e5d2ee1cdabd3e7b9e32c88185cc54edd73ca7a133a0f5e2550348 | Python | 2,261 | 91 | import time
import numpy as np
from Models.BolT.run import train
from utils import Option
from Models.SVM.model import Model
from Models.SVM.util import corrcoef, ledoit_wolf_corrcoef
from Dataset.dataset import getDataset
def calculateFC(timeseries):
FCs = []
for timeseries_ in timeseries:
timeser... |
73c710bff837776d8913a03886fec53663219b8c2aea207f13eb68a2ba6a25cc | Python | 2,263 | 68 | #
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
"""The debug module contains utilities and functions for better
debugging Gunicorn."""
import sys
import linecache
import re
import inspect
__all__ = ['spew', 'unspew']
_token_spliter = re.compile(r'\W+')
clas... |
433f5b0b9c00ffb025fcb85d56cc9f62a1d7d2cae19e905430460c9e77028f4c | Python | 2,266 | 75 | """
Cloud provider from local machine
"""
from typing import Any, Dict, List, Optional, Union, Sequence
from uuid import uuid4
import time
from .abstraction import Device, sep, Task
from ..utils import is_sequence
from ..abstractcircuit import AbstractCircuit
local_devices = ["testing"]
task_list: Dict[str, Any] = ... |
837f8ed1ae3af0135972e4e53c591bc849bc9eabae3417747d72ddcc8b1d0dbd | Python | 2,267 | 73 | import numpy as np
from app.dataflow.qqueue import QQueue, IQueue
from app.process.queue_process import QueueProcess
import logging
from grimace.pose_model import PoseModel
from util.trace import Trace
logger = logging.getLogger("grimace_box."+__name__)
class TopPoseEstimatorV1(QueueProcess):
@Trace.trace(log... |
846acd12ffcee91fa73f027467c884e711fd6bc7f9b99d1b6819206d13d2266c | Python | 2,270 | 62 |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import sklearn
from sklearn.metrics import hamming_loss, accuracy_score
from sklearn.metrics import multilabel_confusion_matrix
from sklearn.metrics import classification_report
from neptune.new.types import File
from config.definitions import D... |
c6c7f5fc5569c41046d38d92d5f016c7cf844f9eb1613ad7dea6183218399322 | Python | 2,270 | 97 | """Internal utility functions for FOOOF."""
import numpy as np
###################################################################################################
###################################################################################################
def group_three(vec):
"""Takes array of inputs, gr... |
34b83336a6b08c1e1bba11e27f7bb8acbe14a4a86b45713d89e15b6921529ddc | Python | 2,271 | 70 | """
Example for creating a custom YASS pipeline
"""
import logging
import numpy as np
import yass
from yass import preprocess
from yass import detect
from yass import cluster
from yass import templates
from yass import deconvolute
from yass.preprocess.experimental import run as experimental_run
from yass.detect impo... |
f1e8e838d0e83e5f37fb7f2e0bf6ffceb12d0c111cbd2628b2c880723eb820ed | Python | 2,271 | 65 | #!/usr/bin/env python
# License: GNU Affero General Public License v3 or later
# A copy of GNU AGPL v3 should have been included in this software package in LICENSE.txt.
"""
(Re)builds an importable python dictionary from a PFAM database, mapping PFAM
name to accession (e.g. CbiA -> PF01656).
By default looks for the... |
241793ac18d07345d81bb399de047cf431a7d9a627dcf2c85b20552265d45c09 | Python | 2,273 | 61 | #!/usr/bin/env python3
"""
Verify that it is possible to round-trip native_functions.yaml via ruamel under some
configuration. Keeping native_functions.yaml consistent in this way allows us to
run codemods on the file using ruamel without introducing line noise. Note that we don't
want to normalize the YAML file, as ... |
45f65b290835c191b502b4cc95decddd24abee6891103ace1a190474e83fa930 | Python | 2,273 | 56 | """
Created on Jun 28, 2024
@author: mning
"""
from typing import Dict
import numpy as np
import pandas as pd
from numpy.typing import NDArray
def save_Perf_CSV(
perf_csv_fn: str,
scores_df: pd.DataFrame,
err_df: pd.DataFrame | NDArray,
mdlDict: Dict,
scoring: Dict,
) -> None:
with open(perf... |
6f000c5dae1a4b3543518d6ddc79b32b8cbe8cee632306db46ef392666fcf94d | Python | 2,274 | 85 | import numpy as np
import pytest
import pandas as pd
import pandas._testing as tm
@pytest.fixture(params=[["inner"], ["inner", "outer"]])
def frame(request):
levels = request.param
df = pd.DataFrame(
{
"outer": ["a", "a", "a", "b", "b", "b"],
"inner": [1, 2, 3, 1, 2, 3],
... |
8885d93d706055023f0cd2a5be2f1ab861b52e3cb602282bbdfb34f47903f66f | Python | 2,274 | 88 | """ Bin a series by the values in another series
Author: Drew B. Headley
"""
"""
MAKE BINTEMP A NUMPY ARRAY OF NANS
CHANGE RANGE(EDGES.SIZE) TO RANGE(1,EDGES.SIZE)
"""
import numpy as np
def bin_serser(val_ser, bin_ser, edges, func=np.mean):
"""
A series of values are binned together based on shared c... |
d851c6db7b1ca1c96c7d96409e02bdb1eb276bfdf181b8e048aa14ce53311eba | Python | 2,274 | 67 | import pytest
from pandas import (
Interval,
Timedelta,
Timestamp,
)
@pytest.fixture(
params=[
(Timedelta("0 days"), Timedelta("1 day")),
(Timestamp("2018-01-01"), Timedelta("1 day")),
(0, 1),
],
ids=lambda x: type(x[0]).__name__,
)
def start_shift(request):
"""
... |
3764f7974b13be2c926324a5a0302bfdd2797715a4db739267343b148483ece4 | Python | 2,275 | 71 | import os
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
# Required constants.
TRAIN_DIR = '/content/drive/MyDrive/ResNetModel/input/Test'
VALID_DIR = '/content/drive/MyDrive/ResNetModel/input/Validation'
IMAGE_SIZE = 224 # Image size of resize when applying transforms.
BATCH_SIZ... |
2165b895ca0504f715bec97af6748af7b2c0a9c72cb9a9516255a3147675a0c2 | Python | 2,284 | 78 | import numpy as np
import torch,os,sys
from torch import nn
from torch.nn import Parameter
import abc
import math
from abc import ABC
import numpy as np
import torch
from torch import nn
from torch.nn import Parameter
import torch.nn.functional as F
import matplotlib.pyplot as plt
from braincog.base.s... |
b5dab70dad3c0cf03a6a19291dd9508dc10357e15c19cf78d42935cf8b743d33 | Python | 2,284 | 68 | import snapatac2 as snap
import anndata as ad
import scipy
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import scanpy as sc
import episcanpy as epi
import decoupler as dc
# Load in the celltype atac object
cell_type_atac = sc.read_h5ad(snakemake.input.atac_anndata)
# Re... |
082fea25f9866b1818e259c2ed19c06b72ef0174944bec1a3097643377823814 | Python | 2,285 | 68 | from atomate.openmx.fireworks.core import OpenmxScfFW
from atomate.openmx.powerups import add_additional_fields_to_taskdocs, set_execution_options
from pymatgen.core.structure import Structure # fixed: import from core
from pymatgen.io.vasp.inputs import Kpoints
from fireworks import LaunchPad
from fireworks import W... |
cbd8357f376c2bcc64d3ed30d679d75277ac29cd043d350129932a5bddf41dfd | Python | 2,285 | 121 | """Functions for loading, viewing, filtering, saving and exporting videos."""
from ..image import normalize
from ._edit import (
crop,
flip_left_right,
flip_up_down,
pad,
resize,
rotate_left,
rotate_right,
collage
)
from ._export import (
alpha_blend_videos,
export_video,
ex... |
45339b734108370859b8063c7efae397cb6fd92506c3cdb9efa5fb62e965dbe8 | Python | 2,286 | 83 | from __future__ import annotations
from ..utils._typed_cache import typed_cache
from ..counts._count_syllables import count_syllables
from ..counts._count_sentences import count_sentences
from ..selections._list_words import list_words
from ..transformations._remove_punctuation import remove_punctuation
@typed_cach... |
a727e754927b669ae30b61044c1ea214760c91078ab196ead63550477708af0b | Python | 2,287 | 90 | # Kanged out of numpy.f2py.tests.util for test_build_ext
from numpy.testing import IS_WASM
import textwrap
import shutil
import tempfile
import os
import re
import subprocess
import sys
#
# Check if compilers are available at all...
#
_compiler_status = None
def _get_compiler_status():
global _compiler_status
... |
325c24af5afa9ebb4d91f3e4f6c0f6de9857b17dc8176b6c69a71939761abfa2 | Python | 2,289 | 77 | """Set up full source space so that nondeterministic ANTs registration is mocked.
Resulting source space is saved to a pickle file.
This script can be utilized in testing. Created source spaces can be compared with
`compare_source_spaces.py`. Furthermore, the final segmentation
NIfTI files can be compared with `compa... |
df2e46ae4414f0daa5ffc5acbcef58638a1bba1828baf57c8bdac458ab8e399c | Python | 2,290 | 88 | """ Bin a series by the values in another series
Author: Drew B. Headley
"""
"""
MAKE BINTEMP A NUMPY ARRAY OF NANS
CHANGE RANGE(EDGES.SIZE) TO RANGE(1,EDGES.SIZE)
"""
import numpy as np
from ppc import
def bin_serser(val_ser, bin_ser, edges, func=np.mean):
"""
A series of values are binned together b... |
33f5cf8a768acfcb368ac8d6720a86691bb95e599f6bfb2259637490a0296c2a | Python | 2,295 | 54 | """
This script generate snapshots of brain activity for the different tasks across subjects
"""
import os
import matplotlib.image as mpimg
from nilearn import plotting
import matplotlib.pyplot as plt
import pandas as pd
from nistats.second_level_model import SecondLevelModel
import numpy as np
db = data_parser(deriv... |
f238e69515f960f7306b481bab8d37a071ed8b75e5222899b432bfd6814981ea | Python | 2,296 | 64 | import torch.nn as nn
from braincog.base.node import LIFNode
from braincog.base.node.node import LIFNode, DoubleSidePLIFNode, PLIFNode
from braincog.base.strategy.surrogate import AtanGrad
import torch
class AtanLIFNode(LIFNode):
def __init__(self, tau=0.5, *args, **kwargs):
super().__init__(tau, *args, ... |
c258bf0aaf45ae85a0f679ce66994601df4be4e5f8f61fd9f9ef0fc95567934c | Python | 2,299 | 81 | import pytest
import textwrap
from . import util
from numpy.testing import IS_PYPY
@pytest.mark.slow
class TestModuleFilterPublicEntities(util.F2PyTest):
sources = [
util.getpath(
"tests", "src", "modules", "gh26920",
"two_mods_with_one_public_routine.f90"
)
]
# we... |
6f25d3e80c38d8f4febc6e57fa09ea3b41250e042ed3d72fcab118bde7921b8e | Python | 2,300 | 77 | import jax
import jax.numpy as jnp
import optax
from optax._src import transform
def scale_by_CoRe(beta1_init=0.99, beta1_final=0.5, beta1_scale=200, beta2=0.999, epsilon=1e-8, total_steps=1000):
"""
Custom transformation for momentum and adaptive scaling with time-dependent beta1.
"""
def beta1_sche... |
c2178e91d396381cb49efea331a71a4a88fd98e9c9bebe0266ffafa372c2fe62 | Python | 2,300 | 65 | import copy
from PySide6.QtWidgets import QDialog, QFileDialog, QDialogButtonBox, QMessageBox
from app.layout.configure_video_files_dialog import Ui_DConfigureVideoFiles
from app.model.grimace_recorder_model import GrimaceRecorderModel
from app.validation.config.video_files_validator import VideoFilesConfigValidator
... |
3ee0f25d848e83846567c8f7820c059deefc6622e3c76d4ba52677b584383bdf | Python | 2,301 | 69 | """HDF5/xarray serialisation helpers for cedalion I/O."""
import h5py
import xarray as xr
import numpy as np
def _has_string_dtype(array):
"""Return True if *array* contains string-typed elements."""
if array.dtype.kind in {"U", "S"}:
return True
elif array.dtype.kind == "O":
return any(is... |
f295a028c9ea86ef5cb57592882e4789bc6d4d3b35c8f126be1a8b5b6d0c185d | Python | 2,301 | 76 | import logging
import os
import time
import torch.multiprocessing as mp
from AIMD import arguments
from AIMD.preprocess import Preprocess
from AIMD.protein import Protein
from AIMD.simulator import SolventSimulator, NoSolventSimulator
from Calculators.calculator import patch_check_state
from utils.pdb import fix_atom... |
127df4c2f78d54d51487a4f0b4cf90a791d80ab6a208b74276858f305e92aa4e | Python | 2,303 | 78 | # Copyright 2021 AlQuraishi Laboratory
#
# 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 agr... |
8100acff2c4fc2f6d73068c668ee3e39294bedc723984dbc1dea093b0b371a5b | Python | 2,306 | 71 | import itertools
import numpy as np
# The following internal methods are used in the get_points_in_sphere method.
def _compute_cube_index(coords: np.ndarray, global_min: float, radius: float
) -> np.ndarray:
"""
Compute the cube index from coordinates
Args:
coords: (nx3 arr... |
534c602024ecc38ab3d9b46a8ca3fda0d7b9da46f9452ea6564f2f349aecfe9a | Python | 2,307 | 55 | #!/usr/bin/env python3
"""C23 Test A — lane dissociation on the VR-spider open dataset (Zenodo 20796399).
Preregistered (frozen before data access, see prereg/RRHM_compatibility_audit_
preregistration_v2.md case C23): (1) |r|(mean SUDS, physiological reactivity) <= 0.70;
(2) both discordant quadrants >= 15% by median ... |
ccd4edef418cf9516d7a99525655ea66dbf64b31ef600a0e64eabd67ef391162 | Python | 2,308 | 85 | """
Magic state distillation example using StabilizerTCircuit (ZX-calculus).
Aligned with tsim implementation.
"""
import numpy as np
from tensorcircuit.zx.stabilizertcircuit import StabilizerTCircuit
def post_select(samples):
"""
Post-select on the [1, 0, 1, 1] distillation syndrome for the last 4 qubits.
... |
f0ed91c26cee708aa7246fb0a012688dbd1e8a045a593be70f4c6a2a33f0fe67 | Python | 2,309 | 67 | # -*- coding: utf-8 -*-
# =============================================================================
# Inputs sequence for the IBC language protocol:
# create a random sequence of sentences per block for all blocks according to
# a pre-specified order of condition and probe type
#
# Author: Ana Luísa Pinho
#
# emai... |
6d84b0b98bab844e33e2b190a8f69ec66e29ea00a2a40e7bf5f70b02bcc55219 | Python | 2,310 | 53 | from pathlib import Path
# Path('PATH/TO/REPO')
PROJECT_DIR = Path("/mnt/disks/gmiller_data1/pnet-simu-private/")
DATA_DIR = PROJECT_DIR / "data" # where to find data
RESULT_DIR = (
PROJECT_DIR / "results"
) # where to save results (performance metrics, processed outputs, etc.)
FIGURE_DIR = PROJECT_DIR / "figure... |
3108a843a8f399d8d9cf8044ceb89090edf27513f3b279d6d1d16179019475ec | Python | 2,311 | 85 | import torch
import numpy as np
from scipy.interpolate import interp1d
def calc_fwhm(kernel):
"""Calculates the full width at half maximum (FWHM) using linear interp.
Args:
kernel (numpy.ndarray): The kernel whose FWHM to be calculated.
Returns
-------
fwhm: float
The calculated ... |
3a4b99ede14245b38d197b81b0d63ed711b73b8fbbdac381485c9d475162e1e2 | Python | 2,312 | 80 | import numpy as np
import pint
import pytest
import xarray as xr
from numpy.testing import assert_allclose
import cedalion.dataclasses as cdc
import cedalion.data
import cedalion.nirs
def test_get_extinction_coefficients_notexistant():
wavelengths = [750, 850]
with pytest.raises(ValueError):
cedalio... |
6a72b0b702dbb7d871262b2662b3ce00f97ddc107e4aefbe59e4868405a98ee1 | Python | 2,312 | 71 | """ Binned dendritic events with respect to an ongoing rhythm
Author: Drew B. Headley
"""
import numpy as np
import pandas as pd
from .load_dendevt_csv import load_dendevt_csv
from .load_spike_h5 import load_spike_h5
from .seg_dendevt import seg_dendevt
from .ser_seg_dendevt import ser_seg_dendevt
from .bin_rhym_dende... |
8b5fc3795a62ffc3b3ead7c18bd7941fe4f6c04a37de5d88173651cf8bdd0120 | Python | 2,312 | 82 | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 28 15:28:12 2016
@author: ajoshi
"""
from mayavi import mlab
import numpy as np
# from scipy.special import sph_harm
import math
def rotation_matrix(axis, theta):
"""
Return the rotation matrix associated with counterclockwise rotation about
the given axis ... |
1b4c744db2692b1a43999b593f2ffc14b08fc6186c69b268ccf55b8af7f7331d | Python | 2,316 | 59 | #!/usr/bin/env python3
"""Recalibration-law calculators (RRHM v13+, exact rationals).
Ledger: p_hat = (nC + a) / (nC + nH + a + b) [clean typing]
Lesion: p_bad = (nC + a) / (nC + nH + nE + a + b) [censored tallied as outcomes]
Dose: n* = floor( (rho*b)/(1-rho) - a ) + 1 (clamped >= 0), rho = ta... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.