sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
c87b0cd61464488cbc21439b1609ccb585e784ea5dc130839c0b81f8a80aac79
Python
3,202
109
""" Shared helper functions for evaluator-related tests (MACE, MSLL, etc.). These utilities are plain functions rather than pytest fixtures so that individual tests can control their parameters directly. """ import numpy as np from pcntoolkit.dataio.norm_data import NormData # Predefined batch-effect configurations...
e158b3e1f72c4dd2c34ba9a274be93e5b709b69fb291201d7391918edb4c070c
Python
3,202
121
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.15.2 # kernelspec: # display_name: .venv # language: python # name: python3 # --- # %% # %load_ext autoreload from pathlib import Path im...
b136b2ac02bb6ae8a10714fd30923b6462dffb62eb23c946731ec29b6075bf48
Python
3,205
101
__all__ = ["MgfReader"] import os import re from typing import Optional, Union, cast import numpy as np from .abs import MassSpectrumReaderBase from .spec import MassSpectrum class MgfReader(MassSpectrumReaderBase): def __init__(self, file): if isinstance(file, str): file = open(file, 'r') ...
a24f6f8a3e1cc64b48bbf466f7037bbac74ead792218ffd8c4e133bbb659f55b
Python
3,206
85
import yaml import os import datetime import getpass import itertools from argparse import ArgumentParser import numpy as np class Config: def __parse_args(self): parser = ArgumentParser() parser.add_argument('parameters', metavar='param', type=str, nargs='*', help='para...
411808be75378aa7ab1d20433db7a81a613de16a4ce04e91f218226208ad10a3
Python
3,210
83
#%% # -*- coding: utf-8 -*- import numpy as np import sys,os sys.path.append('./') from utils.model import * from utils.cal_param import * from utils.move_detector import main from utils.unet import * from env_config import * #=========================set values below========================== # Load models input_sh...
a58d83a167e5588959e5c861bfb2ff585a0fb4dfd6cc21fc6db2ec0328832fa6
Python
3,212
63
import pandas as pd import mne import numpy as np class Epoch(object): def __init__(self, data): """ Creates an 'Epoch' class that applies epoching and averaging functions on the contiuous data via its sub-functions. Functions applied on a given class instance will adjust in-place ...
ca027a4d1d46a1bac50177d6ca07645573934e3deb9e48cdddbb2f334ff03b54
Python
3,212
100
import sys import types import pytest from pandas.compat._optional import ( VERSIONS, import_optional_dependency, ) import pandas._testing as tm def test_import_optional(): match = "Import .*notapackage.*pip.*conda.*notapackage" with pytest.raises(ImportError, match=match) as exc_info: impo...
0c44f57c8afa26af7fce13eb50d1ca98d996d92bc530719af7979219e289e284
Python
3,214
90
''' Created 2016/2017 @author: arco ''' from __future__ import absolute_import import numpy as np import pandas as pd from six import BytesIO import sumatra from model_data_base.utils import silence_stdout from .cell_parser import CellParser def convert_hoc_array_to_np_array(hoc_array): '''converts hoc array to ...
a0becc4db5d24fd67bb95bab26caad7ec83d98c400b01d52ee840476a14be564
Python
3,214
93
# emacs: -*- mode: python-mode; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*- # ex: set sts=4 ts=4 sw=4 et: """ .. _annotations_cogat: =================== The Cognitive Atlas =================== We can download the Cognitive Atlas and extract CogAt terms from text. """ import os import matplotlib.pyp...
0467355430808f6f562e71215e62af3f32556fe6aa845bcca4748b7abb95cd64
Python
3,215
113
# -*- coding: utf-8 -*- """ Created on Mon May 22 13:28:48 2023 @author: Jonas Hartmann @ Mayor lab @ UCL CDB @descript: Potential functions E_pot=f(dist, ...) for use in understanding and specifying simple_cell_sim models. """ # Imports import numpy as np def pot_Hooke(dist, dist0, k): """Hoo...
b09179f000cd3abfeb1b5d703ff7edfa093ce9c2d5379831b5ad5b8852a0a3d1
Python
3,218
84
# -*- coding: utf-8 -*- """ Created on Thu Jul 18 16:39:53 2019 @author: Wladek """ import scipy.stats as st import os import numpy as np import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from figure_properties import * def set_axis(ax, x, y, letter=None): ax.text(x, y, ...
c9121ebcd0f26a7dba55eee0ed8f49d066106b1cf0459220b79bfa0b8379e392
Python
3,218
84
import time import pandas as pd from utils import print_from_history, series_to_matrix from copy import deepcopy import warnings from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier from sklearn.linear_model import SGDClassifier, LogisticRegression import numpy as np from evaluators.calculate...
74f9952f8959d4fe86620a4b7cf961d0b931f5b63bfed00377e59c56befc5525
Python
3,219
98
import numpy as np from scipy.stats import norm from scipy import interpolate from statsmodels.distributions.empirical_distribution import ECDF def estimate_params(values): """ Estimate parameters of a gaussian distribution from values. args: values: values to estimate parameters from returns: ...
86e63921e6d232c37aaf4ae63795e36f2ac82cf61f66536c8015a563b8cfa03e
Python
3,219
94
import torch.nn as nn import torch.nn.functional as F from torch.utils.checkpoint import checkpoint from sequence_models.convolutional import MaskedConv2d, ByteNet2d, ConditionedByteNetDecoder, MaskedConv1d, ByteNet from sequence_models.layers import PositionFeedForward class ByteNetStructureModel(nn.Module): ""...
971609b15d63a5f8729f7954997fdee564cdaf66287cfae0a1694766fc78ed73
Python
3,221
113
import re import pytest from pandas.core.indexes.frozen import FrozenList @pytest.fixture def lst(): return [1, 2, 3, 4, 5] @pytest.fixture def container(lst): return FrozenList(lst) @pytest.fixture def unicode_container(): return FrozenList(["\u05d0", "\u05d1", "c"]) class TestFrozenList: def...
c86c876e4e5386e618bf303afc6bf1e8722b72e420fb95205d308bf32aa6a7c9
Python
3,221
81
import gymnasium as gym import numpy as np from pettingzoo.sisl import multiwalker_v9 class MultiWalker(gym.Env): def __init__(self, name="multiwalker", **kwargs): gym.Env.__init__(self) self.name = name self.env = multiwalker_v9.parallel_env() self.use_central_value = kwargs.pop('...
2f471f1882d08d1cc983f78d4d52305b88e8d21b84831c280d7dc6bbaceb3b33
Python
3,223
125
import os import torch import pickle import matplotlib.pyplot as plt import matplotlib as mpl load_dir = '/Users/elizabethnewman/Desktop/tnn_results/cifar10/tensor/' subdir_names = [] for subdir_name in os.listdir(load_dir): if subdir_name == '.DS_Store': continue subdir_names.append(subdir_name) ...
63d413a9dc2302440135e689dbbe57ad0b3b1e0aeb18efe6b587857ca85375de
Python
3,224
90
from pathlib import Path from unittest.mock import ANY, Mock import pytest import pyaging.data as public_data import pyaging.data._data as data_module @pytest.mark.parametrize( ("data_type", "filename"), [ ("GSE130735", "GSE130735_subset.pkl"), ("GSE193140", "GSE193140.pkl"), ("GSE13...
bc3f32401fccd7fd9212f0dc2e5e18ca7fe0acdd6cf6ab9ec55506266726c475
Python
3,224
95
#!/usr/bin/env python # # Copy manually corrected labels (segmentations, vertebral labeling, etc.) from the preprocessed dataset to the # git-annex BIDS dataset's derivatives folder # # For full help, please run: python copy_files_to_derivatives.py -h # # Example: # python copy_files_to_derivatives.py # -pa...
473e921d31d368b59902c4554e1799fdd7454c06437e7432b004cc8c90fce438
Python
3,225
76
"""Spoiled gradient echo signal model.""" import torch from mrpro.operators.SignalModel import SignalModel from mrpro.utils.reshape import unsqueeze_right class SpoiledGRE(SignalModel[torch.Tensor, torch.Tensor, torch.Tensor]): """Spoiled gradient echo signal model.""" def __init__( self, flip_angl...
15219263dc38804147311fb3f69c5b74977459801a9ed72bce9782df0d204259
Python
3,227
94
from dateutil.tz import tzlocal import numpy as np import pytest from pandas.compat import WASM import pandas.util._test_decorators as td import pandas as pd import pandas._testing as tm class TestNormalize: def test_normalize(self): rng = pd.date_range("1/1/2000 9:30", periods=10, freq="D") re...
4c83a2da394b63dc9c293afd8ba65416b1956b8ed30b0d3ec9167fd39e30dc67
Python
3,227
97
try: if INIT: print("Initialized.") except: import matplotlib.pyplot as plt import numpy as np from scipy.signal import find_peaks import pandas as pd INIT=True def figGen(name="DATA.csv",i=0,T=False): df = pd.read_csv(name,header=0) stngExc = df['stngExc'].to_numpy() stngExcStd...
1d555e97a2f20e8d94d5c1473e8165a203ed8575fe449e1808ffe59d3458fcfd
Python
3,229
98
import sys import re import pdb import random DOCSTART = "0001:(U !ARTICLE)" LOGFILE = open("numberededitabletrees2conll.log","w+") class CorefTracker: def __init__(self): self.wordlist = [] #e.g., [('word1','0101'),('word2','0102'),...] self.chains = {} #e.g., {'0102':['0102','0112',...],...} ...
4f65243ae740935f227136a0d52f1fe0c3a220541f39bf01584876b97092d572
Python
3,229
92
import pytest import pandas._testing as tm class TestDataFrameTake: def test_take_slices_not_supported(self, float_frame): # GH#51539 df = float_frame slc = slice(0, 4, 1) with pytest.raises(TypeError, match="slice"): df.take(slc, axis=0) with pytest.raises(Ty...
f64aa4da92ea9356b1102b5aefc17f25f8bda1163fd6e70eb1057ceb1cf5e5c1
Python
3,229
89
import pandas as pd from matplotlib import pyplot as plt import os import numpy as np import scipy as sc import pylab as pl import seaborn as sns from matplotlib.lines import Line2D def plot_quartet_identical(data_file): data_frame = pd.read_table(data_file) fig = pl.figure(figsize=(5, 2)) ax = fig.add...
3b911781ceb5fcd68de11db308f2c5625aa028eb36c9d1b05df0541cc52648ac
Python
3,230
93
import os from typing import Optional, Union, cast import numpy as np import pandas as pd from ...util.config import Configurable from .rtlib import RetentionTimeLibraryBase COLUMN_RUN_NAME = "run_name" COLUMN_RT = "retention_time" COLUMN_SCORE = "score" class NonRedundantRetentionTimeConsensus(Configurable): ...
a8bbd7f8c37564fcc769798bb4cf2a3778026204930d833767a329f94aa5ce83
Python
3,231
87
import numpy as np import pytest import pandas as pd import pandas._testing as tm @pytest.mark.parametrize("func", ["ffill", "bfill"]) def test_groupby_column_index_name_lost_fill_funcs(func): # GH: 29764 groupby loses index sometimes df = pd.DataFrame( [[1, 1.0, -1.0], [1, np.nan, np.nan], [1, 2.0, ...
26cdb534ba1437e2c7ef228b7e4675ef03b7078b25f60fbfd1deccca405d5f08
Python
3,232
137
# JN 2015-01-13 # refactoring artifact calculation """ this module contains functions that identify artifact clusters based on the spike wave forms """ from __future__ import print_function, division, absolute_import import logging import numpy as np from .. import options, artifact_criteria logger = logging.getLogg...
3602d24402165b5d70cddd9b1b8e41ff3737c4f4cf54301b3a5996f569c0bb32
Python
3,232
68
import os import caffe import argparse import numpy as np import scipy.misc from PIL import Image from util import segrun, fast_hist, get_scores from cityscapes import cityscapes parser = argparse.ArgumentParser() parser.add_argument("--cityscapes_dir", type=str, required=True, help="Path to the original cityscapes da...
ca6a9660b49582265714c8853fcb55a7ed11f8fb82877188ac720dcaeaa43bf2
Python
3,232
87
import numpy as np import pytest import pandas as pd import pandas._testing as tm @pytest.mark.parametrize("func", ["ffill", "bfill"]) def test_groupby_column_index_name_lost_fill_funcs(func): # GH: 29764 groupby loses index sometimes df = pd.DataFrame( [[1, 1.0, -1.0], [1, np.nan, np.nan], [1, 2.0, ...
357784e70efb8ca5aec5f0baad8efb5eaf68cee7ef8713bdf8b62351683eac2c
Python
3,234
69
# Copyright 2019 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 # # http://w...
2ed9d96292a42d66d48ad6d73f1a8dd833a21cde037ae25cde9a9dcf340dcdc8
Python
3,237
170
# Copyright 2018-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 ...
30b07a66bc2d345d6df284cb858b730065411982140f7041cf5c66e493164b59
Python
3,237
112
import torch import torch.nn as nn from roost.cgcnn.model import DescriptorNetwork from roost.core import BaseModelClass from roost.segments import MeanPooling class CrystalGraphPreNet(BaseModelClass): """ Create a crystal graph convolutional neural network for predicting total material properties. ...
be7dd5606165d0518fe5b1222087489887e8a172542cec49a308118dc1862743
Python
3,237
114
from typing import Tuple, List, Dict import numpy as np from ...image import Stack from . import motion_estimation from . import iqa from ...utils import DeviceType def compute_metric( stacks: List[Stack], metric: str, batch_size: int, augmentation: bool, device: DeviceType, ) -> Tuple[List[float]...
bd7cc969cb5660dffdf1ecc83e6091ff5c5acba357fd0b7b340c7e46eded0e6c
Python
3,239
88
import sys import argparse import numpy as np import pandas as pd import configparser def compute_splitID(y, split_fields): """ Map tuples in columns designated by **split_fields** into integer ID to use for data partitioning. :param y: ``pandas`` ``DataFrame``; response data. :param split_fields: ``l...
a02dd553a34cdf7348cf531cc92803c084c816fa12c178efb75ad4ce04fb27a1
Python
3,240
108
"""CSV-upload datasource driver. Reads a CSV that the user uploaded via ``POST /data-sources``. The ``config`` carries the object-storage URI (``file://`` or ``s3://``); the driver pulls bytes through ``ObjectStore``. The ``secret_value`` arg is unused (CSV uploads have no credentials), kept in the signature for prot...
0dca7c11f070bc3ae826ce0dc5c2a518da9b9b5cd0638ae16160426b81e151b9
Python
3,241
77
# Copyright 2019 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 # # http://w...
960f1aa40712141184867ef7e0be6a69dcfc47bf4a5cc4572d4e07b5fb651fab
Python
3,241
83
import os, tempfile, shutil, pathlib from tqdm import tqdm from urllib.request import urlopen _DOWNLOADS_URL = 'https://www.kilosort.org/downloads' _DOWNLOADS_DIR_ENV = os.environ.get("KILOSORT_LOCAL_DOWNLOADS_PATH") _DOWNLOADS_DIR_DEFAULT = pathlib.Path.home().joinpath('.kilosort') DOWNLOADS_DIR = pathlib.Path(_DOWNL...
f9d6ff71b36f5876019739fece5705cea827f46e340908113bb962c8578db686
Python
3,241
85
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Mar 30 22:05:33 2022 @author: ecastrow """ import sqlalchemy as db import pandas as pd # Default setup to load a database engine = db.create_engine('sqlite:////data2/eduardo/code' '/xls_preprocessing/app/xls.db') connection...
0c2ea4365e32d0c19cd4bcb1139cb015a9c6f89ac6680abaa6809a584372939d
Python
3,242
117
import argparse import pandas as pd import matplotlib.pyplot as plt import numpy as np import scipy.stats as stats import scipy.signal as signal import sys script_path = sys.argv[0][:sys.argv[0].rfind('/')] sys.path.append(script_path+'/../..') import charact_utils as utils import plot_utils as pu def plot(time,data...
3c8cfe14fa5d2da91f008190c9b4539ae57d423dece16e3161ea8d7e26e5d484
Python
3,242
91
import numpy as np import torch.utils.data as tdata import torch import pandas as pd from sklearn.decomposition import NMF import warnings def warn(*args, **kwargs): pass warnings.warn = warn def randrows(A, size): return A[np.random.randint(A.shape[0], size=size), :] class RamanSpectraSeqDataset(tdata....
a0168100ec5989c1a7ab0c97722993ff4a0a266101c2fb16d095942ae1c21776
Python
3,242
97
import gymnasium import matplotlib.pyplot as plt import numpy as np import flappy_bird_gymnasium from flappy_bird_gymnasium.envs.utils import MODEL_PATH from flappy_bird_gymnasium.tests.dueling import DuelingDQN from flappy_bird_gymnasium.tests.dueling_v2 import DuelingDQN as DuelingDQN_v2 from flappy_bird_gymnasium.t...
daf74f9b5008543449ab0a41576248e30821ad042dd68231715964d7ff79d3a1
Python
3,242
105
"""Project CRUD (nested under a workspace).""" from __future__ import annotations from typing import Annotated from fastapi import APIRouter, Depends, HTTPException, status from sqlalchemy import select from sqlalchemy.orm import Session from pycaret_server.api.schemas import ProjectCreate, ProjectResponse from pyc...
26be883b75ef2fdd55c9052fa02aa4b0e1cdf24e2c50a32bc97370ccce4edebc
Python
3,243
103
# Copyright 2024 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...
d8d17a0ed09f078649ded87e9b647a8f2e06ec2fe354ecc9bffe73524ed49e15
Python
3,244
88
import esm from typing import Sequence, Tuple, List, Union import torch RawMSA = Sequence[Tuple[str, str]] def rawbatchlen(raw_batch: str): count = 0 counting = True for ch in raw_batch: if ch == "<": counting = False if ch == ">": counting = True ...
62e3e5725245307b37286ea4803b408e4a057cdc28ec242ab4cd99883c1b56bc
Python
3,245
105
""" This code incorporates modifications to software originally developed by the Turaga Lab, available at https://github.com/TuragaLab/DECODE. The original work is licensed under the GNU General Public License version 3.0 (GPL-3.0). We have adapted and extended this code under the same GPL-3.0 license. """ import t...
e659611f9de7dccb783716537c135f90b36855ecda416e0b449637e14d7153f7
Python
3,246
107
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jul 5 11:47:43 2023 @author: cbclab """ from numpy import genfromtxt import numpy as np import matplotlib.pyplot as plt import matplotlib.style as style import seaborn as sns from scipy import stats import pandas as pd from matplotlib.ticker import F...
c485918ad73e1ae5744a9a2b8c9a4bf4d92a45a7271d905654f2b057ad4e7234
Python
3,250
79
from wordfreq import tokenize, word_frequency import pytest def test_tokens(): # Let's test on some Chinese text that has unusual combinations of # syllables, because it is about an American vice-president. # # (He was the Chinese Wikipedia's featured article of the day when I # wrote this test.) ...
a2938be214748f2af59f09d81995e7839f05ab934534165f50f92504df8c1792
Python
3,251
105
import numpy as np import pygame from flappy_bird_gymnasium.envs.constants import ( BASE_HEIGHT, BASE_WIDTH, PIPE_HEIGHT, PIPE_WIDTH, PLAYER_HEIGHT, PLAYER_ROT_THR, PLAYER_WIDTH, ) class LIDAR: def __init__(self, max_distance): self._max_distance = max_distance self.co...
aea2ab81d244f6616d878792a99a3654473a65d57d54995aa9f08ad7e1833865
Python
3,252
85
""" @author: Hongao ZHU @description: extract the human response data from the .mat files and rearrange them in .csv format this program averages the voxel responses for the 12 rois relavant to language @example usage: cd ~/zhu.3986 python3 scripts/transform_mat.py -I /fs/project/schuler.77/corpora/or...
fcf842bb42804c659e5e00606a963b50d78fb8507658a08a66352811da237e1a
Python
3,252
135
"""Utility methods to print system info for debugging. adapted from :func:`sktime.show_versions` adapted from :func:`sklearn.show_versions` """ __author__ = ["Nikhil Gupta"] __all__ = ["show_versions"] import logging import platform import sys from typing import Optional from pycaret.utils._dependencies import get_m...
3454e1967763864897a44eedfd037159012e9c6eacba5fef4db26410a93fa488
Python
3,253
75
import psycopg2 import pdb from sqlalchemy import create_engine import sqlalchemy.orm as orm import os import sys import zipfile import pandas as pd import numpy as np from tqdm import tqdm import json from io import BytesIO sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.append(os...
91f0094ae5f319a16cc0954c0c158492950a9538530bbf689841629d692abbe9
Python
3,253
111
import os import csv import glob import random import pandas as pd def ID_shuffler(list1, list2): temp = list(zip(list1, list2)) random.shuffle(temp) res1, res2 = zip(*temp) # res1 and res2 come out as tuples, and so must be converted to lists. res1, res2 = list(res1), list(res...
ff0ec9fc7a70f82889703caea6912d93b1023e0675fceae6687849e93b6044f6
Python
3,254
96
import numpy as np import pytest import pandas.util._test_decorators as td import pandas as pd import pandas._testing as tm from pandas.core.internals.blocks import NumpyBlock class BaseCastingTests: """Casting to and from ExtensionDtypes""" def test_astype_object_series(self, all_data): ser = pd.S...
4d0fa3fae91d936ae661c8169faf02ffda875913d4e80ff12306df49793e09ab
Python
3,256
79
# Ported from the Isaac Lab rl_games integration (isaaclab_rl); original DexPBT # implementation from NVIDIA-Omniverse/IsaacGymEnvs (https://arxiv.org/abs/2305.12127). # Copyright (c) 2022-2026, The Isaac Lab Project Developers. # SPDX-License-Identifier: BSD-3-Clause from dataclasses import dataclass, field, fields ...
6712f19eda0889ec4b00aae445a5e671e9767a530504909dbcceef48084345af
Python
3,256
84
# 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...
8571cafe948f08dbfcd7e475733226c7cea662d49abde8e0ac6e0ebf5eece39c
Python
3,259
87
import numpy as np import matplotlib.pyplot as plt import sys import os from kcsd import sKCSD from kcsd import sKCSD_utils as utils import kcsd.validation.plotting_functions as pl import sKCSD_utils n_src = 512 lambd = 1 R = 8e-6/2**.5 if __name__ == '__main__': fname_base = "Figure_3" tstop = 75 scaling_f...
1f33c358e7cd8b019edee3905d17b028665fd555c27c4d142ee41ccb4c41d387
Python
3,260
75
"""Phase 1: jobs table — queueable unit-of-work for the worker pool. Revision ID: a1b2c3d4e5f7 Revises: f0a1b2c3d4e5 Create Date: 2026-05-13 09:00:00.000000+00:00 Adds the ``jobs`` table that backs the executor backend toggle (``RUNS_BACKEND=inprocess|redis``). With ``inprocess`` the in-process ``RunOrchestrator`` ke...
2451c3826210640a5e8ba50434da1841ea22283ca1f61f6761c1a011bc6f9305
Python
3,262
102
"""Test MDCNN dataset.""" import io import re import urllib.request import numpy as np import pytest import scipy.io import torch from mrpro.data import KData from mrpro.phantoms.mdcnn import MDCNNDataset, download_mdcnn from mrpro.utils import RandomGenerator N_PHASES = 2 N_COILS = 3 N_K1 = 208 N_K0 = 416 N_K0_PADD...
a057e93f33a258d27087ef2a0cc459334b36696b72a1e84dbc575d13e5eaa35f
Python
3,263
103
from skimage import filters, morphology as morpho, measure, util from matplotlib import pyplot #from sklearn.neighbors import LocalOutlierFactor from sklearn.ensemble import IsolationForest from cine import Cine import tube2 import align import numpy as np import glob import pathlib from multiprocessing import Process...
e26aa0acebf1799b22a11c2fbdeffab2c1cfccd1b226f9e562fe14c3d33619a0
Python
3,265
91
import numpy as np import pytest import pandas as pd import pandas._testing as tm class TestToNumpy: def test_to_numpy(self): df = pd.DataFrame({"A": [1, 2], "B": [3, 4.5]}) expected = np.array([[1, 3], [2, 4.5]]) result = df.to_numpy() tm.assert_numpy_array_equal(result, expected...
3add731d5663d0c782b56e34fad99730ee85c9efbfd1abc5d4c8e8d1bdc03925
Python
3,266
111
import os import csv import glob import random import pandas as pd def ID_shuffler(list1, list2): temp = list(zip(list1, list2)) random.shuffle(temp) res1, res2 = zip(*temp) # res1 and res2 come out as tuples, and so must be converted to lists. res1, res2 = list(res1), list(res...
517b788b954f2ca2d610bfb16b57784022ff55397479b5d6d580b336f5223fea
Python
3,266
111
import numpy as np import re import sys import random import cv2 def read_pfm(filename): file = open(filename, 'rb') color = None width = None height = None scale = None endian = None header = file.readline().decode('utf-8').rstrip() if header == 'PF': color = True elif he...
7e04de074cd6945fbeb0f2fafd00e11cdd999c6933de48192a22e64f3fefb110
Python
3,266
167
""" compat ====== Cross-compatible functions for different versions of Python. Other items: * platform checker """ from __future__ import annotations import platform import sys from typing import TYPE_CHECKING from pandas.compat._constants import ( CHAINED_WARNING_DISABLED, IS64, ISMUSL, PY312, ...
d78f2a7c2bb3e2350eefbb7b8b8797cd33c3bdc1858899bc33e94c643b7dca96
Python
3,267
86
#!/usr/bin/env python3 """ Description: Parallel experiment simulation using Python multiprocessing. Usage: ./simulate_exps_python.py -i <tx_counts> -m <tx2gene> -l <pheno> -n <num_experiments> Author: Beril Erdogdu Date: September 2025 """ import os import argparse from multiprocessing import Pool, c...
1124e0b9fe8ec3fc2a45063b03076b41a075d28dd790408a2f8cc62a4587fdcd
Python
3,271
73
# # Linearity class for use in holographic neural networks. # # Layer takes inputs f_{i-1} of shape l x c(l,i-1) x m(l) # and contracts it with weights W_{i} of shape c(l,i-1) x c(l,i). # It returns the contracted product as output. # # In einstein notation, the equation for this layer is # # g^i_{l,c(l,i),m(l)} =...
e612ea4e0643b2207dc7691b956c9cc7ba2497bb5f71cc8f922dd74568480ddc
Python
3,271
100
import pandas as pd import itertools from nltk.stem.isri import ISRIStemmer from nltk.corpus import stopwords from nltk.tokenize import word_tokenize from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix, roc_auc_...
c418c5d9a38dd1658b10927df4212d06b979fcf1c6d973f6c5289e65aba937fb
Python
3,273
102
from sklearn.model_selection import KFold, RepeatedStratifiedKFold, GridSearchCV class CVSpec(): """ A class that stores the specifications for the CV process. Attributes: ----------- n_splits : int, optional The number of folds to generate. Default is 5. n_repeats : int, optional ...
8daae99db219083485261f0df73ee1985008b56aa469cee295e17c7e4f095f8b
Python
3,275
107
from typing import Tuple import numpy as np import scipy.signal # type: ignore from caiman.source_extraction.cnmf import deconvolution # type: ignore def foopsi_all(intensities: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: """Uses FOOPSI algrorithm from CAIMAN package to decompose calcium signal and estimate...
d40b191115290b6d37ff61083f152bdcc465df500e5e349c7b18863bf352b734
Python
3,276
139
# MOFTransformer version 2.2.0 import torch.nn as nn from transformers.models.bert.modeling_bert import ( BertConfig, BertPredictionHeadTransform, ) class Pooler(nn.Module): def __init__(self, hidden_size, index=0): super().__init__() self.dense = nn.Linear(hidden_size, hidden...
3d2890194240469193ade3d9340b366fde451f630dbea757f86103727f9fa9e0
Python
3,277
109
# PrairieLink # Lloyd Russell 2017 import os import numpy as np import time try: # for Python2 import Tkinter as tk import tkFileDialog as filedialog except ImportError: # for Python3 import tkinter as tk from tkinter import filedialog def ReadRawFile(movie_path=None, start=1,...
3e62e0b4f600a8abc8e3ca75291eee6c6e750e75bac821ec58d7317ad098bb6c
Python
3,278
93
"""Tests for MOLLI signal model.""" from collections.abc import Sequence import pytest import torch from mrpro.operators.models import MOLLI from mrpro.utils import RandomGenerator from tests import autodiff_test from tests.operators.models.conftest import SHAPE_VARIATIONS_SIGNAL_MODELS @pytest.mark.parametrize( ...
e5b3ef67d09939d98239d1a772e714e27c203c64bd63db2ace8979d9de7501ba
Python
3,278
94
import numpy as np from collections import OrderedDict from batchgenerators.utilities.file_and_folder_operations import * from nnunet.paths import splitted_4d_output_dir import SimpleITK as sitk import shutil def copy_nifti_modify_labels(in_file, out_file): # use this for segmentation only!!! # nnUNet wants ...
5408a8c22c0efaeceb7c176fa9de32f26af446324fbdb6228781d6c8ecdcc7c9
Python
3,279
93
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon May 9 18:08:13 2022 @author: jinani """ # Import Required Libraries from tensorflow import keras from tensorflow.keras.layers import Conv2D, AveragePooling2D from SysIden_AvgMethod_SupportFiles.k_layers import gaussian2dMapLayer, PowerLowNonLinearity ...
ddb9dffbe26b69fe8ffeafc42d62e8e98e734e39b503b4044ab3c5ef24965f25
Python
3,279
86
import dgl import torch import torch.nn as nn import torch.nn.functional as F from dgllife.model.readout import WeightedSumAndMax class MultiHeadGATLayer(nn.Module): def __init__(self, in_dim, hidden_dim, num_heads): super(MultiHeadGATLayer, self).__init__() self.heads = nn.ModuleList() fo...
adba3ac0faabe52bdfb4541ca288d9b69db15ada7d6d77b7861c98e3d29155ad
Python
3,282
86
import numpy as np import pytest from pandas.errors import Pandas4Warning import pandas as pd import pandas._testing as tm class TestIndexConstructor: # Tests for the Index constructor, specifically for cases that do # not return a subclass @pytest.mark.parametrize("value", [1, np.int64(1)]) def t...
c0fe257ad695f03039273eab2cd413ad1ce97bace9128bc547a07ffb33b5051f
Python
3,283
86
from Environment import * from Registration.VISoR_Brain.visor_sample import VISoRSample VERSION = '0.9.6' class VISoRBrain: def __init__(self, path=None): self.slices = {} self._transforms = {} self.transform_source = {} self.atlas_transform = None self.slice_spheres = {} ...
456583d492861ed0ae1d168991a48e283edd260556f725b4147e384563617262
Python
3,286
103
from torch.nn.modules.loss import _Loss import torch.nn import torch.nn.functional as F from tnn.tensor_utils import modek_product class tLoss(_Loss): def __init__(self, size_average=None, reduce=None, reduction: str = 'mean') -> None: super(tLoss, self).__init__(size_average, reduce, reduction) class t...
dde398a12d98265a1d5ecf8db2f11259a63e0bbbeb3da924dae70e5681893c98
Python
3,286
103
r""" General math utils. """ __all__ = ['lerp', 'normalize_tensor', 'append_value', 'append_zero', 'append_one', 'vector_cross_matrix', 'vector_cross_matrix_np', 'block_diagonal_matrix_np'] import numpy as np import torch from functools import partial def lerp(a, b, t): r""" Linear interpol...
07e69ca1c102d30db40651b2ac2e5e5f04e13bb9bfd924042f7789f2f267c1d7
Python
3,287
82
# Copyright 2019 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 # # http://w...
7762070cea7d49a747d2063ed9d2f58e70b073083e67dd13f35792c73c42e136
Python
3,287
110
""" datetimelke_accumulations.py is for accumulations of datetimelike extension arrays """ from __future__ import annotations from typing import TYPE_CHECKING import numpy as np from pandas._libs import iNaT from pandas._libs.tslibs import OutOfBoundsTimedelta from pandas.core.dtypes.missing import isna if TYPE_C...
42a63d88e71cd3ead1755e5a17ece0bf863cdf732f42e191046c8ee1314a8540
Python
3,289
123
# -*- coding: utf-8 -*- # JN 2014-09-25 # create h5 file containing histogram of firing channels # in time bins # this is used to exclude bins with too many channels firing # as they are likely to be artifacts from __future__ import print_function, division import logging import os import numpy as np import tables imp...
89070d1ff91b3282ade831fcf073e3d02c0f42ae8d103399d31ec5f32a9a0b01
Python
3,289
86
import torch from torch import nn # Typing from torch import Tensor from typing import List, Optional, Tuple def bessel(x: Tensor, start: float = 0.0, end: float = 1.0, num_basis: int = 8, eps: float = 1e-5) -> Tensor: """Expand scalar features into (radial) Bessel basis function values. """ x = x[..., N...
aa0ea528b0ccaa910d6f89016725bf9931b97a76e24b94e2dccdfdd4673dfa41
Python
3,289
96
##################################################################################################################### # Date created : 10/21/2022 # Date modified: 10/21/2022 # Purpose : This program is to crate features from pdb, 25 features from dssp, 2 features from convex hull atoms volume and surface area, ...
34ed31ed305b2905752c2d1e6e06c002e43bfaa98c31814bbdd4556228165d51
Python
3,290
74
# 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...
9cc7de095cba862b7b76945a245ce6b2925cc6effc8da1d71c83c91a7eafade9
Python
3,291
85
import pandas as pd import numpy as np import altair as alt import scipy.stats as st datasets = ["glauc_sec", "age", "amd_rob", "amd_rob_age", "glauc_rob", "tenano"] bundles = ["UNC_L", "UNC_R", "CST_L", "CST_R", "L_OR", "R_OR"] #"fov_L", "fov_R", "mac_L", "mac_R", "periph_L", "periph_R"] formal_b_names = { "UNC...
732de35f55a4765941dc6b7efedac36ae19f501e5749869a3c9f22b2e8dcb11d
Python
3,292
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...
b7325bddbcd79697723c5da8110ec9d53ca8dfbe55e5f19fd58f4a71d407b98f
Python
3,292
105
#!/usr/bin/env python """ If given 1 input argument (FILEN), lists all the sub-BRIKs in that file. If given 2 input arguments (FILEN, SUBBRIKNAME), returns the zero-indexed BRIK number for that sub-brik. e.g. > greg% python /path/to/parse_3dinfo.py my_bucket+orig Full_Fstat cat2_conv_c1#0_Coef cat2_conv_c1#...
1c3039d38e2824fa46ec1f69cca350167275bd2bc5f6a176e4d9b707f3ee0511
Python
3,294
90
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.endGame: ...
fafaf024a89247846b1c700df80aab523775b3fdd87424adaf39595a42864f5b
Python
3,296
63
import pandas as pd import os import sys sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))) from app import create_app, db from app.models import Subject, SourceDataset, Visit from load_db.OASIS import get_oa...
18c05ed78c77fba5e72a41d7a8f033d288110f6a6728ffd6bf75f720db5b0ad3
Python
3,298
77
#%% Imports from pathlib import Path import os import argparse def get_subjects(data_dir: Path): subjects = [subject.name for subject in data_dir.iterdir() if subject.is_dir()] # remove fsaverage subjects = [subject for subject in subjects if subject != 'fsaverage'] return subjects def get_asegstats2t...
83e2ddd4cae409f95bf873b7b9121b05ae695a0d1969492637aa9937849f0294
Python
3,298
94
"""Zero Operator.""" import torch from mrpro.operators.LinearOperator import LinearOperator class ZeroOp(LinearOperator): """A constant zero operator. This operator always returns zero when applied to a tensor. It is the neutral element of the addition of operators. """ def __init__(self, keep...
92627927252964927a75e2acc759b643a027be99b72c43441a6e1c7900a49be3
Python
3,298
100
import pandas as pd import itertools from nltk.stem.isri import ISRIStemmer from nltk.corpus import stopwords from nltk.tokenize import word_tokenize from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix, roc_auc_...
f1249ba51e33acf8dac493027dc33a6c86d7e727400893b3f08d9abe470d3056
Python
3,300
102
# Created by G. Peter Lepage (Cornell University) in 12/2013. # Copyright (c) 2013-19 G. Peter Lepage. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # any...
06711858d7b1158165567ce9405e9ba193de79689284db28af21e6a1bd13bfac
Python
3,303
97
import argparse from datetime import datetime import numpy as np import os import windseer.utils as utils def make_openfoam_csv( cosmo_data_file, cosmo_terrain_file, geotiff_file, logfile, csv_file, resolution=64, plot_figs=False, rotate=None, s...
45bcc0ef81a071bc5bbbfc832d1c0848f7da235aa4b8cc5cf1a7fc4dc2bffccb
Python
3,303
79
"""Tests for CardiacFingerprinting signal model.""" from collections.abc import Sequence import pytest import torch from mrpro.operators.models.cMRF import CardiacFingerprinting from mrpro.utils import RandomGenerator from mrpro.utils.reshape import unsqueeze_right from tests import autodiff_test def test_cmrf_basi...
d8885b8d64e780c4b6c936f70b82f18ff90d9d14c508dbab85883d2cba590c63
Python
3,303
71
# -*- coding: utf-8 -*- import matplotlib.pyplot as plt import numpy as np import json import time import openmc from utils.mcsimulation_square import * from env_config import * #=========================set values below========================== num_sources = 1 # the number of radiation sources to place. a_num = 2 ...
3bb24796e6d93867bdeef1adbdbb8bf2ec60f96ced3fd029088f1d8f46771732
Python
3,304
104
""" Public API classes that store intermediate results useful for type-hinting. """ from typing import TYPE_CHECKING from pandas._libs import NaTType from pandas._libs.lib import NoDefault from pandas._libs.missing import NAType from pandas.core.col import Expression from pandas.core.groupby import ( DataFrameGr...
876cf418c53543bd7a7280e7d5879ad6f82dee07855b08ac6cb86fa4bd3d6801
Python
3,304
111
import os import csv import glob import random import pandas as pd def ID_shuffler(list1, list2): temp = list(zip(list1, list2)) random.shuffle(temp) res1, res2 = zip(*temp) # res1 and res2 come out as tuples, and so must be converted to lists. res1, res2 = list(res1), list(res...
d02b55565017c604f6164d9252177ec0a5dc88007b3300b21a5ce08ad22a07ab
Python
3,307
103
import pytest import pandas as pd import pandas._testing as tm from pandas.tseries.offsets import ( BaseOffset, Day, Hour, MonthEnd, ) class TestFreq: @pytest.mark.parametrize("values", [["0 days", "2 days", "4 days"], []]) @pytest.mark.parametrize("freq", ["2D", Day(2), "48h", Hour(48)]) ...