sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
191ff4800689c1024db905857e8d3f5fc826cf3e4e61aab80d9fc32384af26c5 | Python | 2,792 | 75 | """Tests for `multimodal_ad.models.evaluation` (no TensorFlow needed)."""
import numpy as np
import pytest
from multimodal_ad.models.evaluation import (
evaluate_predictions,
sensitivity,
specificity,
threshold_probabilities,
)
def test_threshold_probabilities_uses_strict_greater_than_half() -> None... |
f233507aab729c407fde24fb4b59f1b856d179d230c8077caf7b4252821d13cf | Python | 2,794 | 73 | """Tests for MultiEchoSpinEcho signal model."""
from collections.abc import Sequence
import pytest
import torch
from mrpro.operators.models.MESE import MultiEchoSpinEcho
from mrpro.utils import RandomGenerator
from tests import autodiff_test
def test_mese_basic(parameter_shape: Sequence[int] = (2, 1, 3, 4, 2)) -> N... |
f869d46ae7954f885ded6f50a1f452cd6418ac8a8c2ad3839b5f1b504cb66da7 | Python | 2,794 | 88 | import sys, os, re, itertools, argparse
argparser = argparse.ArgumentParser('''
Takes a mixed effects model as input and computes spillover permutations
''')
argparser.add_argument('inform')
argparser.add_argument('outdir')
argparser.add_argument('-m', '--min', type=int, default=0)
argparser.add_argument('-M', '--max'... |
b6cef6d906ea4a6b9881b5211a1012e634f07277179f8157da5bddab660e7e40 | Python | 2,795 | 72 | """Prewhiten k-space data."""
from copy import deepcopy
import torch
from einops import einsum, parse_shape, rearrange
from mrpro.data.KData import KData
from mrpro.data.KNoise import KNoise
def prewhiten_kspace(kdata: KData, knoise: KNoise, scale_factor: float | torch.Tensor = 1.0) -> KData:
"""Calculate nois... |
e3f559bcc214c3564b7fc74afd480673aa6bca669ba152e9174603cc2ecf9190 | Python | 2,795 | 95 |
import os
import subprocess
import math
import shutil
import numpy as np
from os.path import isfile, join
from PIL import Image
import random
import csv
from datetime import datetime, timedelta
path = 'phase_recognition_annotations/'
video_path = 'dataset_videos/phase_recognition/'
case_list = os.listdir(path)
case... |
f520d9eb8207653bb007039b493a043af6f1f2b6b2e8f05282b3125803fa6646 | Python | 2,797 | 69 | ######################################################################################################################################################
# This program generates Lx5120 feature embedding from an input fasta and outputs in npy format #
# Credit: Met... |
251695bdb6863f6b0746c7a50bdd5363e2c92d21b33dda1c70fda170efacd15c | Python | 2,798 | 100 | from pymatch import *
from pymatch.utils import *
def drop_static_cols(df, yvar, cols=None):
if not cols:
cols = list(df.columns)
# will be static for both groups
cols.pop(cols.index(yvar))
for col in df[cols]:
n_unique = len(np.unique(df[col]))
if n_unique == 1:
df.... |
7107fefb647a269e1a5ce92cd732330036d30002e3466273fa56c9a482bc22ce | Python | 2,799 | 85 | """Phase 2 ObjectStore tests.
Covers the LocalFs driver + the factory selection logic. S3 driver is
exercised via mocked boto3 in a separate test once boto3 lands in the
test extras.
"""
from __future__ import annotations
from pathlib import Path
import pytest
from pycaret_server.storage import ObjectStoreError, r... |
e6318eb363b64a9d49e4bc9075ee409949ae558c9757785bcc13c1817fe4e671 | Python | 2,799 | 53 | #!/opt/local/bin/python2.7
from os import path
import glob
import argparse
from base.kernelFunctions import *
from surfaceMatching import *
def main():
parser = argparse.ArgumentParser(description='runs surface matching registration over directories (relative to the template)')
parser.add_argument('template',... |
26586adc41eb85458f5cd365db3af85686d99b21925a2b0d4a627fdf1c17386c | Python | 2,801 | 54 | import torch
import torch.nn.functional as F
def get_lr(optimizer):
"""
Get the learning rate at any given point from the optimizer.
Parameters:
- optimizer: The PyTorch optimizer.
Returns:
- lr (float): The learning rate of the optimizer at the current point.
"""
for param_group in o... |
4a1b2870521e69baf575d2e30cfc5fbf282e13eb380fbe4e9868ce4671253dbd | Python | 2,801 | 77 | import numpy as np
import matplotlib.pyplot as plt
import read_wind_csv as rw
import sys
def plot_data(wind_data, sp='p', sUx='U:0', sUz='U:2'):
fh, ah = plt.subplots(2, 1) # , {'aspect':'equal'})
fh.set_size_inches([5, 8])
p = wind_data.get(sp).values.reshape([rw.WINDNZ, rw.WINDNX])
# x = wind_da... |
7c643c96acae917603abfa7d962d104a28de28398e94229eb09b6c71e80672b6 | Python | 2,801 | 75 | import time
import pandas as pd
import numpy as np
import torch
def series_to_matrix(series):
"""
Converts a pandas series of string repersented arrays to a numpy matrix.
Used because of how we stored our BoW data
:param series: A pandas series where each item is a string of an array e.g. '[1,2,3]'
... |
7be4c406fd72866d8a1cfe8bc65933d6f15c326ffdb187becc4fb043c257978c | Python | 2,805 | 72 | """Test the helpers shared by the video readers."""
import pandas as pd
import pytest
import torch
from lightning_pose.data import _IMAGENET_MEAN, _IMAGENET_STD
from lightning_pose.data.video.utils import (
LitPredictWrapperBase,
PreparePredictBase,
build_batch_dict,
normalize_frames,
)
class TestNo... |
a0035081f6d12ced9f852c2232fc0ab7f176a48a82486038667016f7733efc1f | Python | 2,805 | 87 | """
Linear Regression script for self-paced reading data
Note: This script expects reponse data generatede with the modelblocks pipeline
"""
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score, log_loss
from scipy.stats impor... |
9e220f878882278364b9dc35b5e75314d4c6aaf0c497f369f39aa81b371844b0 | Python | 2,806 | 96 | # -*- coding: utf-8 -*-
import warnings
import numpy as np
import pytest
from emcee import EnsembleSampler, backends
__all__ = ["test_blob_shape"]
class BlobLogProb(object):
def __init__(self, blob_function):
self.blob_function = blob_function
def __call__(self, params):
return -0.5 * np.... |
a1cd6a3e0f60eec352a3980d1983e3fff28c1240354bf572b45fde189b1028d8 | Python | 2,806 | 101 | #%%
#Imports
import numpy as np
import os
from pathlib import Path
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.gridspec import GridSpec
import matplotlib.backends.backend_pdf
plt.style.use('seaborn-talk')
import seaborn as sns
import pandas as pd
from sklearn.preprocessing ... |
bfaff0563c7494434a7188700beb5415768586f66d5d86a99a8020c08327afa7 | Python | 2,807 | 55 | """Tests for KHeader class."""
import torch
from mrpro.data import KHeader
from mrpro.data.traj_calculators.KTrajectoryCalculator import DummyTrajectory
def test_kheader_overwrite_missing_parameter(random_mandatory_ismrmrd_header, random_acq_info) -> None:
"""KHeader can be created if trajectory is provided."""
... |
4d816c0e716a042ded3ad38e8ec58717a815303a386c723a6575777cb49b687c | Python | 2,808 | 72 | # Copyright (c) 2018-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import torch.nn as nn
import torch.utils.data.dataloader
class RNNModel(nn.Module):
"""Container module with an encoder, ... |
78c07aa5f0ed09c6fa7e2eede8efb535dcc37469f5d5cf13a145b05bcd74d770 | Python | 2,808 | 77 | import pytest
from pandas.errors import NullFrequencyError
import pandas as pd
import pandas._testing as tm
class TestTimedeltaIndexShift:
# -------------------------------------------------------------
# TimedeltaIndex.shift is used by __add__/__sub__
def test_tdi_shift_empty(self):
# GH#9903
... |
82634873f6c981d8653618ec22e4ec546e9de4009e080d57bbd955abed014ecd | Python | 2,808 | 145 | from pandas._typing import (
AggFuncType,
AlignJoin,
AnyAll,
AnyArrayLike,
ArrayLike,
AstypeArg,
Axes,
Axis,
ColspaceArgType,
CompressionOptions,
CorrelationMethod,
CSVEngine,
DropKeep,
Dtype,
DtypeArg,
DtypeBackend,
DtypeObj,
ExcelWriterIfSheetExi... |
e13c2f45e9c6bf1dd2a3eea424662664f8ed877c640f3869f2f022b0d357684a | Python | 2,809 | 93 | import pandas as pd
import signal
import numpy as np
import time
import os
import logging
import itertools
import functools
import warnings
from multiprocessing import Pool, TimeoutError
from Bio.PDB import PDBList
from Bio.PDB import PDBParser
from Bio.PDB.mmtf import MMTFParser
from Bio.PDB.PDBExceptions import PDBCo... |
2590576a0d37003649304f3725820e751dd5353884be417f78e15ecb5e4923c2 | Python | 2,810 | 72 | # Copyright 2026 Xanadu Quantum Technologies Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agre... |
98793894e77ba25b00f82cf932fbf08e16048113e7bed02707c9e533c6c0cfa5 | Python | 2,811 | 95 | """
Internal module for console introspection
"""
from __future__ import annotations
from shutil import get_terminal_size
def get_console_size() -> tuple[int | None, int | None]:
"""
Return console size as tuple = (width, height).
Returns (None,None) in non-interactive session.
"""
from pandas.... |
e8b06a9cd4a2bb9386facd24c591499f2379de8136d56fb9b1fe5c03f5d927a6 | Python | 2,811 | 79 | #
# Check the README.md file for more details on how to download the data.
import pandas as pd
import numpy as np
from pathlib import Path
data_dir = Path(__file__).parent.parent / 'data' / '2_confounds'
d = pd.read_csv(data_dir / 'DXSUM_PDXCONV_ADNIALL.csv')
w = pd.read_csv(data_dir / 'UCSFFSX6_08_17_22.csv')
w.r... |
4bac783f04c01a7814f822924741d391d94e87eb5c56ba9313c31857285627d4 | Python | 2,812 | 89 | __all__ = ["GlycoPeptideMS2SpectrumProto", "GlycoPeptideMS2Spectrum"]
import itertools
from typing import Any, Iterable, Optional, Protocol, Tuple
from dataclasses import dataclass
import numpy as np
import numpy.typing as npt
from ..common.spec import IntensityArray, MS2SpectrumProto, MzArray
from ..pep.spec import ... |
566f2a652eeabbe4864f1ff0339acb85dbdae42654c39da815bf7df343d63458 | Python | 2,812 | 77 | import tensorflow as tf
import h5py
import numpy as np
import pandas as pd
import os
import math
import matplotlib.pyplot as plt
def predict_and_plot(model, data_folder, output_folder, plot_folder, batch_size=100):
"""
Performs prediction on test data and plots the results.
Args:
- model: Loaded Tenso... |
731c4e9f1a9aebf990daab4f2b870cd78c5aad00f9735d34d60688ff9c2d4f8b | Python | 2,813 | 94 | from setuptools import find_packages, setup
from torch.utils.cpp_extension import CUDAExtension, BuildExtension
import os
import glob
root_path = os.path.dirname(__file__)
version: dict = dict()
with open("./nesvor/version.py") as fp:
exec(fp.read(), version)
def get_long_description():
if not os.path.exi... |
c60ba84ef803d07e030fbe8fd82b604be2b56d4308dc4a8f4938123e60601b9d | Python | 2,813 | 82 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 27 14:18:43 2021
@author: jeanbaptiste
"""
import os
import time
# Default LSTM-MLP parameters:
defaults = dict(
datasets_folder = os.path.dirname(__file__) + '/../assets/data/experimental/',
training_sets=(
"2022-04-13_TrainingSet2... |
707be93e9bb44ad985f01118504e9f8153076e0c29e1aefccf65fd25c6b80941 | Python | 2,815 | 67 | import pandas as pd
import numpy as np
import tensorflow as tf
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix, classification_report, accur... |
4f416773416bf66f59f370324d3899854c8db796fabf34a425ad1f76a1fe3b57 | Python | 2,816 | 92 | import numpy as np
import scipy as sc
from scipy.stats import gamma, uniform
from scipy.stats import entropy
from msmfcode.models.cann import ContinuousAttractorNetwork
def kl(p, q):
"""Kullback-Leibler divergence D(P || Q) for discrete distributions
Parameters
----------
p, q : array-like, dtype=fl... |
5057cbb3291108f33469cc592cb1501c95e4062283c05e2a96916f8a90476593 | Python | 2,816 | 100 | # helper functions to convert quaternions to read/phase/slice normal vectors
# and vice vectors
# direct translation from ismrmrd.c from the ismrmrd project
import numpy as np
def quaternion_to_directions(quat):
a, b, c, d = quat
read_dir = 3 * [None]
phase_dir = 3 * [None]
slice_dir = 3 * [None]
... |
885e84ccda739852bbc175f85fae97d4eb9da6695533e3fe38e15a568acc4386 | Python | 2,816 | 63 | # Copyright (c) 2018-2023, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of condit... |
ffcca6613ea74b1f0a836001d7fccfdd612a637711d68a7801d927e9f325970f | Python | 2,816 | 106 | from scipy.sparse import csr_matrix
import numpy as np
import faiss
from sklearn.cluster import KMeans
def cluster_qr(M, iclust, iclust0):
NN = M.shape[0]
nr = M.shape[1]
nc = iclust.max()+1
q = csr_matrix((np.ones(NN,), (iclust, np.arange(NN))), (nc, NN))
r = csr_matrix((np.ones(nr,), (np.arang... |
0c68e5831d76b3fe3b11cbdc7c93102784c4dffc5ec4c63bacbf07e7df900381 | Python | 2,818 | 103 | import os
import pysam
import argparse
import sys
def extrack_denovo(input_vcf, min_support=1):
output_vcf = open(os.path.join(input_vcf.replace(".vcf", ".denovo_s{}.vcf".format(min_support))), "w")
input_vcf = pysam.VariantFile(input_vcf)
output_vcf.write(str(input_vcf.header))
for record in inpu... |
3c1c5bf1461feaf23ba1e6f2ff85ea9a87e870c376aac02398b123f4eeff32fa | Python | 2,818 | 82 | """`ClusteringExperiment` — the PyCaret 4.0 clustering engine.
Unsupervised. Verb surface: `fit`, `create_model`, `assign_model`,
`predict_model`, `plot_model`, `save_model`, `load_model`, `pull`, `models`.
Canonical import:
from pycaret.tasks import ClusteringExperiment
# or (backward-compat):
from pyca... |
8e4d241cdf7380f578332f184dcf5b51a1264aa6086437c48b074567472a9360 | Python | 2,818 | 86 | # MIT License
# Copyright (c) 2020 Joseph Auckley, Matthew O'Kelly, Aman Sinha, Hongrui Zheng
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitati... |
0016f51b84e4206fba5d875e8d33647055f772568eae4334c7720659e391ffc8 | Python | 2,822 | 57 | #!/usr/bin/env python
import torch
import torch.nn as nn
import numpy as np
import scipy.ndimage as snd
from torch.autograd import Variable
from dataset import VolumeDataset, BlockDataset
from torch.utils.data import DataLoader
from model import MultiSliceBcUNet, MultiSliceSsUNet, MultiSliceModel, UNet2d
from function ... |
2e138920c3a494ba9f285ff9e3221b3a1913624ec3b6c4b908525be06c6ab98b | Python | 2,822 | 93 | #!/usr/bin/env python
"""
File: utils
Date: 5/1/18
Author: Jon Deaton (jdeaton@stanford.edu)
"""
import os
import pandas as pd
def load_survival(survival_csv):
"""
Loads a survival CSV file
:param survival_csv: The path to the CSV file to load
:return: Pandas DataFrame with the survival information
... |
3ced94a6e5aee06d629373485cf416345e8930eb5145077047cfc1eb045fd660 | Python | 2,822 | 76 | import numpy as np
import random
import os
import matplotlib.pyplot as plt
import matplotlib.colors
from matplotlib import cm
from mpl_toolkits.axes_grid1 import make_axes_locatable
import time
import sys
# import sklearn.linear_model
# from sklearn.model_selection import train_test_split
# from sklearn.linear_model im... |
432bd9867bb69f1c84942e4467a517f29d5b3dc0360340de286b43613bec875e | Python | 2,822 | 108 | from timeit import repeat as timeit
import numpy as np
import seaborn as sns
from pandas import DataFrame
setup_common = """from pandas import DataFrame
import numpy as np
df = DataFrame(np.random.randn(%d, 3), columns=list('abc'))
%s"""
setup_with = "s = 'a + b * (c ** 2 + b ** 2 - a) / (a * c) ** 3'"
def bench_... |
d020b464a55d64386ef268ea0c850682d22da227b92899abbefe29ccce959027 | Python | 2,822 | 59 | '''
Sample start and goal configurations and write them to a file (start_goal_configurations.txt) inside the build folder.
Each line contains one pair in the following format:
x_start y_start z_start yaw_start x_goal y_goal z_goal yaw_goal
While x and y are actually expressed in meter z is the fraction of the distance... |
f554cba02eecf260d9ad6659f5a12cbdbb2e53c6bee14900072819884ed22028 | Python | 2,822 | 70 | import numpy as np, matplotlib.pyplot as plt, sys
import pumpprobe as pp
plt.rc("xtick",labelsize=18)
plt.rc("ytick",labelsize=18)
plt.rc("axes",labelsize=18)
ds_list = "/projects/LEIFER/francesco/funatlas_list.txt"
signal_kwargs = {"remove_spikes": True, "smooth": True,
"smooth_... |
f9bae2803461e1739bfcbd21f9547d7fe9ce5a13d76fc638d77c82b39877e802 | Python | 2,824 | 77 | # MIT License
#
# Copyright (c) 2018 Stefano Nardo https://gist.github.com/stefanonardo
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the... |
6828e1a80860519811628cad84cc2c22966a5029d9073be31c48a3e19a5f0eaa | Python | 2,825 | 86 | # emacs: -*- mode: python-mode; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*-
# ex: set sts=4 ts=4 sw=4 et:
"""
.. _decode_discrete:
============================
Discrete functional decoding
============================
We can use the methods in ``nimare.decode.discrete`` to apply functional
character... |
e258aaee6a82fd205f662affe00bea64f039632b63e70fb38732862493156e41 | Python | 2,825 | 80 | """Tests for scripts/inference-timing/benchmark_single_config.py.
These are lightweight, GPU-free checks on the script's pure helper logic
(argument parsing, hydra overrides, CSV writing) -- not an end-to-end
benchmark run, which needs a real trained model and a real GPU. The goal is
just to catch this script drifting... |
6925cd5b49ae499334a548356f8f1d60953ec7b2ddc9d9081d1fc1a1918cd2e1 | Python | 2,831 | 73 | import torch
from torch import nn
import copy
from ..mlp import MLP
from ..convs import MeshGraphNetsConv
# Typing
from torch import Tensor
from typing import List, Optional, Tuple
class Encoder(nn.Module):
"""ALIGNN/ALIGNN-d Encoder.
"""
def __init__(self, num_species: int, init_bnd_dim: int = 4, init_... |
f0332277cd327f45f825681a054af36fa5a4df50e6bfe0b341a6aa298effc23d | Python | 2,831 | 96 | import functools
import itertools
import logging
from multiprocessing import Pool, TimeoutError
import os
import signal
import time
import warnings
from Bio.PDB import PDBList, PDBParser
from Bio.PDB.mmtf import MMTFParser
from Bio.PDB.PDBExceptions import PDBConstructionWarning
import h5py
import numpy as np
import p... |
287e90834087f35fdd5bcab7ff4c444ed487793730e4574660bc351a4fa234c4 | Python | 2,832 | 62 | """Rank clocks use one cohort median, regardless of inference batch size."""
from unittest.mock import Mock
import anndata
import numpy as np
import pandas as pd
import pytest
import torch
import pyaging as pya
from pyaging.predict._pred_utils import check_features_in_adata, predict_ages_with_model
def _model(cloc... |
62d6d293eb85014784768ce2f505be775f6addceb0f4f9b52dcb09fe2bbd7b7b | Python | 2,833 | 83 | #%%
import pickle
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from sklearn.cluster import MiniBatchKMeans
from sklearn.metrics import pairwise_distances_argmin_min
maskfile = "demodata/mask.npy"
#%%
def flatten_image(v, maskfile=maskfile):
mask = np.load(maskfi... |
761a7b7853df57c91be01100a8158025c799f5e0e00240cc85791cb24bcc1f39 | Python | 2,833 | 75 | #!/usr/bin/env python
"""Get vocabulary coutings from transformed corpora samples."""
from onmt.utils.logging import init_logger
from onmt.utils.misc import set_random_seed, check_path
from onmt.utils.parse import ArgumentParser
from onmt.opts import dynamic_prepare_opts
from onmt.inputters.corpus import build_vocab
fr... |
ebc68a88fc5e93abb338d87df1a751b0614611210acfead62e6c2de48de97e77 | Python | 2,833 | 57 |
from ..file_utils import make_basedir, get_tmp_path, dbsnp_version, get_filepath
from .load_utils import run_script
from .. import conf
import os
import wget
from typing import List
def download_rsids_for_build(hg_build_number:int) -> None:
raw_dbsnp_filepath = get_tmp_path('dbsnp-b{}-hg{}.gz'.format(dbsnp_versi... |
267503161534a3e4d2eaa00860e936bd315fb948949d851cf32ef08fee1f7e30 | Python | 2,837 | 93 |
from torch.nn.modules.loss import _Loss
import torch.nn.functional as F
import torch.nn as nn
def dice_coeff(y_pred, y_true, smooth=1):
assert y_pred.size() == y_true.size()
y_pred = y_pred[:, 0].contiguous().view(-1)
y_true = y_true[:, 0].contiguous().view(-1)
# print(y_pred.device, y_true.device... |
0ef2859e89d900dfba0504635543b9a91936bb7ad01f4397f82b37ad1f264cf0 | Python | 2,838 | 83 | #!/usr/bin/env python
import os
from copy import deepcopy
from nipype.pipeline import engine as pe
from .tractography.base import init_tract_wf
from .tractography.outputs import init_tract_output_wf
from .. import utils
def init_single_ses_wf(subject_id, session_id, parameters):
t1_file = parameters.t1_file
... |
d7eafb38a4d894c0fdfd87e78ebbb15d45fe1e938bf4d35a818d1669df4e204d | Python | 2,840 | 126 | """
offsets benchmarks that rely only on tslibs. See benchmarks.offset for
offsets benchmarks that rely on other parts of pandas.
"""
from datetime import (
datetime,
timedelta,
)
import numpy as np
from pandas import offsets
from pandas.tseries.frequencies import to_offset
try:
import pandas.tseries.... |
60fd80430eb13f56caf7d0ba47b2fda22371ba46a8fcbcd068abc42bc2f31490 | Python | 2,841 | 79 | from torch.utils.data import Dataset
from torchvision.io import read_image
import torch
import json
import pandas as pd
from skimage.io import imread
import numpy as np
from torch.utils.data import DataLoader
from torchvision.transforms import ToTensor
import torch
from torch import nn
from torchvision import dataset... |
dd612436a34c2b76a0f247ad06946c03669f51eec9331e9df066129dcbcdf856 | Python | 2,843 | 72 | # Generate random colormap
# Adapted from https://github.com/delestro/rand_cmap by delestro
def rand_cmap(nlabels, type='bright', first_color_black=True, last_color_black=False, verbose=True):
"""
Creates a random colormap to be used together with matplotlib. Useful for segmentation tasks
:param nlabels: N... |
4340a7afc315db789ef44e18b6931f2f1e81f37300308e141079fa46ab9e600e | Python | 2,846 | 87 | # Copyright 2018-2023 Xanadu Quantum Technologies Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or... |
4f79f76a7c4d42aceb4a4f908bee102de6328c4337b91f00dac1cd55ec2806f6 | Python | 2,847 | 82 | # %% [markdown]
# # B$_0$ Inhomogeneity Correction
# Here, we are going to have a look at how to correct for B$_0$ inhomogeneity in MRI data.
# ## Generate a field map and a simple phantom
# We use an ellipse phantom and a random field map to simulate B$_0$ inhomogeneity.
# %%
import mrpro
import torch
matrix = mrpro... |
824951facc1cb60ce508332c0d8a2f587f2a0c127921651836ca8c60ebceb6e1 | Python | 2,849 | 73 | """
.. module:: tool_brush
:platform: Linux, Windows
:synopsis: Basic round brush tool (2D or 3D)
.. moduleauthor:: Fredrik Nysjo
"""
from tool_common import *
import numpy as np
import scipy as sp
import scipy.sparse
import scipy.sparse.csgraph
import scipy.ndimage
import glm
class BrushTool:
def __init... |
4367aead90531664594093d03d5ad4af6da8b5a38861f0dd4a5574886c23d8a5 | Python | 2,852 | 86 | import numpy as np
import pytest
import pandas as pd
import pandas._testing as tm
class TestToPeriod:
def test_to_period(self, frame_or_series):
K = 5
dr = pd.date_range("1/1/2000", "1/1/2001", freq="D")
obj = pd.DataFrame(
np.random.default_rng(2).standard_normal((len(dr), K... |
05869a55bb0e4779f6ead45648d3a94046ea7b657ed749583557ada06e416e52 | Python | 2,854 | 80 | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import Sequential, Linear, ReLU
from torch_geometric.nn import GATConv
from torch_geometric.nn import global_max_pool as gmp
# GAT model
class GATNet(torch.nn.Module):
def __init__(self, num_features_xd=78, n_output=1, num_features_x... |
7be90bedf629a256d5a95b3eb4653a110dba57e563fbc335bf58f4c19f7efd1e | Python | 2,854 | 96 | # JN 2015-06-19, 2015-12-14
# Convert spikes from Matlab files to our format
from __future__ import division, print_function, absolute_import
import os
from argparse import ArgumentParser
import numpy as np
from scipy.io import loadmat
import tables
NAME_SPIKES = 'spikes'
NAME_TS = 'timestamps'
def convert(fname_in,... |
9f9253b58328ebcb512835089d064fc33664d55cf797b6fd46faa36c6fd1ce81 | Python | 2,856 | 82 | """Utilities for data operations.
This module is the shared home for programming operations (e.g., from NumPy,
pandas, xarray, itertools packages). The goal is to keep the main codebase
focused on Bayesian statistics while moving reusable programming operations
to a shared utility module.
"""
from __future__ import a... |
31031b53dd9d94ef92f23d129e60867b4e0446cd3ba68608e351a5d340cbd8a4 | Python | 2,858 | 82 | import torch
import torch.nn as nn
from darts.api import Model
from darts.modules.mixed_layer import MixedLayer
class ConvBlock(Model):
""" ReLu -> Conv2d """
def __init__(self, c_in, c_out, kernel_size, stride, padding, affine=True):
super(ConvBlock, self).__init__()
self.conv = nn.Conv2d(
... |
ba09af619e223724077b537a7dbd0eaed26c1590ab6bd99d8ce471ef8a0ed427 | Python | 2,858 | 53 | import torch
from torchvision import datasets, transforms
import argparse
def setup_mnist(n_train=50000, n_val=10000, n_test=10000, batch_size=32, data_dir='data'):
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])
train_dataset = da... |
ff6df20a929f06c2d36e8c058e7237249c38f909e9f7a377ed76064c4e60068e | Python | 2,858 | 97 | # Copyright 2018-2021 Xanadu Quantum Technologies Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or... |
a9c08566f2fd6cab5f7ff87e36a3863028f7cbbbbf26690dc13aa311568b6813 | Python | 2,859 | 82 | # coding=utf-8
# Copyright 2021 The rinna, EleutherAI, and HuggingFace Teams. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICEN... |
38f170abc65448424ece04eedb8032a067f168c28cf4180bc9a8f9f25e1e570c | Python | 2,861 | 79 | """Reconcile the ``Awaiting Review`` label across all open pull requests.
Run once a day from the scheduled maintenance job (folded in to share a single
runner boot rather than firing on every push). The label is informational: it
flags PRs sitting in the maintainers' court and awaiting a *review* — a fully
approved P... |
ad8e6ee7e1b6e6dee15d501cf8fe6e1e49dc822df7f7661b3633f3c8d1b3b0a7 | Python | 2,861 | 58 | """Tests for ellipse phantom."""
import pytest
import torch
from mrpro.data import SpatialDimension
from mrpro.data.traj_calculators import KTrajectoryCartesian
from mrpro.operators import FastFourierOp, FourierOp
from tests import relative_image_difference
from tests.phantoms import EllipsePhantomTestData
def test... |
e2323e310c519047f12f1ce957b8010e58877b1ff551385ce3befb8612545928 | Python | 2,861 | 94 | #!/usr/bin/env python
import argparse
import torch
import time
from models.model_MCMG import transformer_RL
from MCMG_utils.data_structs import Vocabulary
from MCMG_utils.utils import seq_to_smiles
import pandas as pd
def Transformer_generator(restore_prior_from='output/Prior.ckpt',
save... |
9ddb83dcefdf9ec77aca173eabb50df56cbc8fc179c4a079220f0886c1acf686 | Python | 2,862 | 105 | # Copyright 2018-2023 Xanadu Quantum Technologies Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or... |
8671a9453cdaebd8b50104352246dfbd448c0d8fefc871c8d96196df73365890 | Python | 2,863 | 73 | #!/usr/bin/env python
import pandas as pd
import os
import scanpy as sc
import argparse
from mudata import MuData
parser = argparse.ArgumentParser(
description="Parameters for generating anndata and mudata"
)
parser.add_argument(
"--assignment",
help="Folder which contains cSV file with demultiplexing assi... |
bccb39af949a10dab465040c46eda0d938be267bcc6bc768c21896f6a2fff51f | Python | 2,863 | 68 | import sys, argparse, pandas as pd
argparser = argparse.ArgumentParser('''
Generates spillover metrics from user-supplied columns in tokmeasures input, skipping over punctuation
''')
argparser.add_argument('cols', nargs='*', help='Names of columns for which to add spillover metrics')
argparser.add_argument('-C', '--col... |
1124117f825ce0ba69f51fec5a336dc42239461a8e21f52da9b33a353f50bf44 | Python | 2,866 | 78 | import math
import os
import random
import argparse
from datetime import datetime
import numpy as np
import tensorflow as tf
from sklearn.metrics import roc_curve, accuracy_score, confusion_matrix
from sklearn import metrics
from utils.structure import getModel
from utils.dataset import gen, get_dataset_from_csv
p... |
c96a6767b90d226ada6dc35bb9b7d0978bd093543d60a3146066aa062c823a8a | Python | 2,866 | 83 | import argparse
import logging
from Bio import SeqIO
def get_args():
"""
Get arguments from command line with argparse.
"""
parser = argparse.ArgumentParser(
prog='Sort-Fasta-Records-by-SAM-BioPython.py',
description="""Sort all entries in a fasta file by order of a read names text file... |
a833723909c0a1d23b54c9ad364ffee6fd340b31674496596c4978da1adf1bf4 | Python | 2,867 | 82 | from base.surfaceExamples import Sphere, Heart
from base.surfaces import Surface
from base.surfaceSection import Hyperplane, SurfaceSection
from base.surfaceMatching import SurfaceMatchingParam
from base.surfaceToSectionsTimeSeries import SurfaceToSectionsTimeSeries
from base import loggingUtils
import matplotlib
matpl... |
cfa8bb6601f239f5cf82a1c39b58cdbbd6f0b9b086439bb7ee7286b77c2685cd | Python | 2,868 | 77 | import numpy as np
from tqdm import tqdm
from loguru import logger
class TPC:
def __init__(self, input_array: np.ndarray, A: np.ndarray, C: np.ndarray, dt: float = 0.5, k1: float = 0.001,
k2: float = 0.008, activation: str = 'nonlinear'):
self.input = input_array
self.input_size ... |
972198aa5235932cfe0db7050084184a84e32b2db47f117da4d0e741617f834b | Python | 2,871 | 65 | # -*- coding: utf-8 -*-
import os
from keras.callbacks import Callback
class SWA(Callback):
"""
This callback implements a stochastic weight averaging (SWA) method with constant lr
as presented in the paper -
"Izmailov et al. Averaging Weights Leads to Wider Optima and Better Generalization"
... |
7e84a666422cd74ef8484020bda07502f09d4a9f1c9bff37000c9aa39bc4f11a | Python | 2,874 | 88 | from torch.utils.data import Dataset
import os
import cv2.cv2
import albumentations as albu
import torch
import numpy as np
class SkinSegmentationDataset(Dataset):
def __init__(self, dataframe, root_dir='', img_path='', mask_path='', transforms=None, color_space='bgr'):
self.df = dataframe
self.i... |
57d9e1c8141d67fc5efb14eac607b8d20bc6159f130e24a9b20c60c4946aeaba | Python | 2,875 | 84 | # Copyright 2021 DeepMind Technologies Limited
#
# 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... |
584dcfe91ff198e34f2cf49d79a51aa8e400f95a9dc053e40065e9e6a36dc977 | Python | 2,875 | 83 | # coding: utf-8
"""Quality trimming.
"""
# Import cythonized functions, defaulting to pure python implementations.
try:
from ._qualtrim import quality_trim_index, nextseq_trim_index
except:
import logging
from atropos.util import qual2int
logging.getLogger().debug("Import failed for cythonized qua... |
2df140b32ee9b64e00b10ded52251544944a2a8d7159eba5bf46ebaac1d0c341 | Python | 2,879 | 96 | # /usr/bin/env python
"""This script is used to get intron regions of a genome from gtf file
"""
from collections import defaultdict
import re
import gzip
from argparse import ArgumentParser
def parse_args():
parser = ArgumentParser(
prog='Getting regions of intron from gtf file')
pa... |
709a1196b517907a291f21b3e77844fefbe61fed2fdff28ab007eb89edc90bee | Python | 2,880 | 71 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: mbejtka
"""
import numpy as np
import h5py as h5
import matplotlib.pyplot as plt
import os
from kcsd import KCSD2D
from numpy.linalg import LinAlgError
from traub_data_kcsd_column_figure import (prepare_electrodes, prepare_pots,
... |
a40df37ce1d2697d1550f784f9a9ef16d300ef68c1bdd320d6b08c76b4d9e22c | Python | 2,881 | 77 |
from tensorflow import keras
import cine
import tube2
import numpy as np
from skimage import util, transform, measure
import glob
import json
def get_batch(video, idx, batch_size=16):
zone = []
for i in range(batch_size):
frame = video.get_ith_image(idx + i)
cropped = tube2.tube_crop1(frame)
... |
e8c19b7ada6a75a0ff80f05e1d6cbb35214361117a81e6fa12da957f5471f60f | Python | 2,882 | 105 | #
# File to split a protein list into training, validation, and testing data
#
from argparse import ArgumentParser
import sys
import Bio.PDB as pdb
import Bio.PDB.mmtf as mmtf
import h5py
import numpy as np
from protein_holography.utils.posterity import get_metadata,record_metadata
import protein_holography.prep... |
f5c2591de40600edc6a24bd08d331f9b546fa7d09c497f1136c095e5e9e0ae37 | Python | 2,882 | 78 | from StimulationProcess.BasicStimulationProcess import BasicStimulationProcess
from psychopy import core, visual, event
import time
class FinishProcess(BasicStimulationProcess):
def __init__(self) -> None:
super().__init__()
def change(self):
if self.controller.endBlock:
... |
3accf28a94113205a4f4ba29a3b6a583ca6d9dd937b71fd5b21ddf348bfd4d14 | Python | 2,884 | 65 | import json
import pandas as pd
import numpy as np
import fire
import text_extensions_for_pandas as tp
import gpmhc.GNN_paper.data as data_utils
import gpmhc.GNN_paper.learner as learner_utils
#Only one GPU inference is currently suppported, cpu inference not supported
def infer(input_model='/gstore/data/gai/pcv/thrif... |
59ca0d54bb97aaddf7badd84048d2fe2e1d7988f470733ea6fdc15349c840d53 | Python | 2,885 | 99 | """
Visualization.py
Created March 2, 2021
Simplifies viewing images (color/greyscale).
"""
import math
from typing import List, Optional, Sequence, Tuple, Union
import cv2
import matplotlib.pyplot as plt
import numpy as np
from numpy.lib.arraysetops import isin
from . import common
from .image import Image, ColorIm... |
af818cbe29e12620c5b5548fd1a538129aa9253b467d744bdc0a632e42802cb5 | Python | 2,886 | 90 | #!/usr/bin/env python
import sys
synopsis = "\n\
join_files_by_NthCol.py <file1> <N> <header_switch> <file2> <output.txt> [e]\n\
- <file1> and <file2> are tab-delimited text files,\n\
- add <file2> to <file1>, by matching values in the 1st column of <file2>,\n\
with the <N>st/nd/th column of the <file1>,\n\
- ... |
d3148bfd6818e1a5a163e791715266a2567dbc690715c29af8f6ca3c726bc9e6 | Python | 2,886 | 85 | # Copyright 2026 Xanadu Quantum Technologies Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agre... |
6eb1da7cc1d2317b553073a05b276d9460676f45821a02d21496b6c67fe73bda | Python | 2,889 | 64 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Additional analysis of the power spectral density of the ROI time series to estimate alpha and beta peak power and peak frequency without removal of the 1/f-component
Vinding, M. C., Eriksson, A., Low, C. M. T., Waldthaler, J., Ferreira, D., Ingvar, M., Svenningsson, ... |
6e7a6ea2f35f31e69bf92b0d698bc13ee2f47dd40ba87e4901a9028b942d375d | Python | 2,896 | 60 | #! /usr/bin/env python
##############################################################################
## DendroPy Phylogenetic Computing Library.
##
## Copyright 2010-2015 Jeet Sukumaran and Mark T. Holder.
## All rights reserved.
##
## See "LICENSE.rst" for terms and conditions of usage.
##
## If you use this wo... |
12b6d9b5240998360df76d92ea41241aa3448878a6866f9f738635d39f3cbde3 | Python | 2,897 | 112 | from __future__ import division
from pymatch import *
import sys
import numpy as np
def drop_static_cols(df, yvar, cols=None):
if not cols:
cols = list(df.columns)
# will be static for both groups
cols.pop(cols.index(yvar))
for col in df[cols]:
n_unique = len(np.unique(df[col]))
... |
34c9abf475026664b996b66102fddba9e98fbe3500b91b8870020e284c634b7c | Python | 2,897 | 119 | import sys
from enum import Enum
from pathlib import Path
from hydra.core.config_store import ConfigStore
from dataclasses import dataclass, field
from omegaconf import MISSING
from typing import Any, Optional
sys.path.insert(0, str(Path.cwd()))
@dataclass
class GeneralConfig:
force_cpu: bool = False
log_wan... |
67d91774be35368de137a5d3831a0895201927a845f1eb31cd8964f0ee47e90a | Python | 2,898 | 81 | import argparse
import pandas as pd
from utils import normal_bracket2ptb_bracket, zen2han
parser = argparse.ArgumentParser()
parser.add_argument(
"--bccwj_eyetrack_path", type=str, default="data/BCCWJ-EyeTrack/fpt.csv"
)
parser.add_argument("--lstm_root", type=str, default="data/aggregated/lstm")
parser.add_arg... |
0b3afb39d2f4280290cdfb378a046b863c907c25198a1bb4f08cc04353c301d9 | Python | 2,899 | 97 | #!/usr/bin/env python3
import sys
import spc
import glob
import os
import subprocess
import argparse
import pandas as pd
from os.path import isfile
from jwslib import read_file as read_jws
import numpy as np
parser = argparse.ArgumentParser()
parser.add_argument("root", type=str, help="Root of directory to work with... |
695346bc6206ebc13ea5aa4568bc4ae75903386c17c663285d9629a227a61645 | Python | 2,900 | 85 | # Copyright 2018-2023 Xanadu Quantum Technologies Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or... |
5d3ec0f814ffb1198d61034b651c35df7027f1e3e02445f04973a2523b9d2a7a | Python | 2,902 | 86 | from pkg_resources import resource_filename
import MeCab
import unicodedata
import os
# MeCab has fixed-sized buffers for many things, including the dictionary path
MAX_PATH_LENGTH = 58
def find_mecab_dictionary(names):
"""
Find a MeCab dictionary with a given name. The dictionary has to be
installed se... |
0e08e9835a57df3d892ba4b287f19c495621242275c9e0ebec05013d8d6e9ee6 | Python | 2,903 | 94 | """`AnomalyExperiment` — the PyCaret 4.0 anomaly-detection engine.
Unsupervised. Verb surface mirrors `ClusteringExperiment`.
Canonical import:
from pycaret.tasks import AnomalyExperiment
# or (backward-compat):
from pycaret.anomaly import AnomalyExperiment
Example
-------
>>> from pycaret.datasets imp... |
1455c753db963e5a2f12047a5212a8026e76cec1e6bf706c616e06d8c36f136a | Python | 2,903 | 101 | # Copyright 2026 Xanadu Quantum Technologies Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agre... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.