sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
83371dc201f4e652b8641a31386d5215ddf7026ae5b46418a9a10a2f1aa760ec | Python | 4,702 | 171 | # 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 agree... |
7fdee5816aa082d4b9eaca638415ede4fd8c4e8622327f3424b576d56ca49434 | Python | 4,705 | 143 | """Reconstruction module."""
from abc import ABC, abstractmethod
from collections.abc import Callable
from typing import Literal
import torch
from typing_extensions import Self
from mrpro.algorithms.prewhiten_kspace import prewhiten_kspace
from mrpro.data.CsmData import CsmData
from mrpro.data.DcfData import DcfData... |
c8a0066816da0e15f3add4d2b7a84826493c60e4792bcd89130b2e3435b00838 | Python | 4,705 | 229 | #!/usr/bin/env python
"""
This script is used to generate basis sources for the
kCSD method Jan et.al (2012) for 1D,2D and 3D cases.
Two 'types' are described here, gaussian and step source,
These can be easily extended.
"""
import numpy as np
def gauss(d, stdev, dim):
"""Gaussian function
Parameters
---... |
bd99f531cb16aceedd720ea1e4f8c10b32b9a0a20fd3b9efcdcabf8a58125f5c | Python | 4,706 | 143 | import torch.nn as nn
import torch.nn.functional as F
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None,
groups=1, base_width=64, dilation=1):
super(BasicBlock, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, k... |
d8a6c53525de1e6fe41806af4eafeb0ad28c2ca5c50f001ab0af127c4ee8a004 | Python | 4,708 | 150 | """Typed result objects returned from every Experiment operation.
Every PyCaret 4.0 verb (`compare_models`, `create_model`, `tune_model`, ...)
returns a frozen dataclass. This gives us three things simultaneously:
1. **Notebook compatibility** — the result's `.pipeline` (or `.models` /
`.best`) is still a sklearn ... |
57c942d003187692bd102b66176c80ff17c1045c29da39fc47adf55fd77e72cc | Python | 4,709 | 164 | import os
import argparse
from collections import Counter
import numpy as np
from pathlib import Path
import pandas as pd
import json
import copy
import pickle
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import r2_score, mean_absolute_error
from sklearn.preprocessing import StandardScaler
... |
cd79b0310773cf372a5741a87f4959baa8e4edcee2190b7abd03987179e1a13f | Python | 4,712 | 134 | from io import (
BytesIO,
StringIO,
)
import uuid
import pytest
import pandas as pd
import pandas._testing as tm
def test_compression_roundtrip(compression, temp_file):
df = pd.DataFrame(
[[0.123456, 0.234567, 0.567567], [12.32112, 123123.2, 321321.2]],
index=["A", "B"],
columns=... |
488cbf29a9c0cb8e218465e05b6dec6b620aa5d960bf853046c321c736a1b537 | Python | 4,713 | 98 | """End-to-end native parser/caller combinations beyond individual fix tests."""
import struct
import sys
import pytest
from MACS3.Utilities.Performance import DEFAULTS
from MACS3.Utilities.Execution import resolve_execution_policy
from test_native_streams import encoded
def bam_record(chrom, left):
# One mappe... |
cbc91845871252217cfbcb5bc8d172f5c67f90159e839f78a3b413b830951d90 | Python | 4,713 | 83 | import sys
import argparse, textwrap
from pgen.esm_sampler import ESM_sampler
from pgen import models
from pgen.utils import write_sequential_fasta, parse_fasta, unalign, add_gaps_back, RawAndDefaultsFormatter
from pathlib import Path
import random
from tqdm import trange
model_map = {"esm1b":models.ESM1b, "esm6":mode... |
374eb2d7381469ed710c5565ae3d35c65d75b2911c5798deb2d8179abb5695d9 | Python | 4,714 | 124 | """Experiment designer — takes a dataset + a user goal and returns a full
RunConfig-shaped proposal.
Input contract:
- CSV-upload DataSource (we read its column profile — same helper shape as
dataset_analysis so the prompt stays consistent across consultations).
- A free-text "goal" from the user ("predict chu... |
ab6ba10ccd45ac0ed49ba1afcced419924d4b71c47f0bd3dcb5d8961412584b9 | Python | 4,717 | 143 | import numpy as np
import pytest
import pandas as pd
import pandas._testing as tm
@pytest.fixture
def df():
# c1
# 2016-01-01 00:00:00 a 0
# b 1
# c 2
# 2016-01-01 12:00:00 a 3
# b 4
# ... |
e45342a125a3a894729ef459979fd519e5b402589c8c54776a595746c5420a72 | Python | 4,719 | 150 | """GPU device detection.
Single-source-of-truth for "does this worker have a GPU?". Used by:
- The worker entrypoint: refuses to claim ``queue=gpu`` Jobs unless
``detect_gpus().available`` is True, so a CPU worker started against
the GPU queue can't drain it into failures.
- The admin ``/system/info`` route: surf... |
3b5ab8bf07d4fd7552c95d9f34f4a66b6053eca807baedb3bb4469cbc7806adf | Python | 4,721 | 156 | import os
import numpy as np
import pandas as pd
from multiprocessing import Process, Queue
from evolutionary_experiment.config import config
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
class RibosomalAutoencoder(object):
def __init__(self, max_serann_tokens, use_cpu=True):
self._tokenizer = Tokenizer()
... |
8141a7d5201a2c28f14cf520a9a273d226aabd11b31dd39819b44cf08529ff96 | Python | 4,721 | 173 | import bionetwork
import numpy
import matplotlib.pyplot as plt
import torch
import activationFunctions
from scipy.optimize import minimize
plt.rcParams["figure.figsize"] = (4,4)
leak = 0.01
x = numpy.linspace(-5, 5, 2001)
delta = (max(x)-min(x))/len(x)
functionType = 'leakyRelu' #MML leakyRelu sigmoid
if functionT... |
9c976dfe56414f2bcea17dd3b9031e6c3d4d7e5d8ead32c9d450282f0fb777d9 | Python | 4,721 | 101 |
#pid,label,dir
import sys
# prepare your own data
import pandas as pd
import nibabel as nib
import numpy as np
import os
from sklearn.model_selection import train_test_split
print( "Reading in csv files ...")
max_age = 35.0*12
min_age = 3.0
centile = 75
print("dataset/csv_data/2D_Dataset_skull_stripped"+str(centile... |
ebb86e4b972660055dd108e595f699990e0b1d7ae44ffcce3cda22c32576f0b8 | Python | 4,721 | 123 | import torch
import numpy as np
from rdkit import Chem
from rdkit.Chem import AllChem
from sklearn.metrics import roc_auc_score
from torch.utils.data import Dataset, DataLoader
import torch.nn as nn
import torch.nn.functional as F
import copy
class AmesDataset(Dataset):
"""
dataset object
mols... |
1d16ccf59a72e5063d4f95fad6e7e7dcbb26d9f44deaea92123e0c06e01121c9 | Python | 4,723 | 105 | """WASABITI signal model for mapping of B0, B1 and T1."""
from collections.abc import Sequence
import torch
from torch import nn
from mrpro.operators.SignalModel import SignalModel
from mrpro.utils.reshape import unsqueeze_right
from mrpro.utils.unit_conversion import GYROMAGNETIC_RATIO_PROTON
class WASABITI(Signa... |
bf4399550a8a9122f9c28f2b6555318b0fc57811f714ffc75d14cebc8d360ad9 | Python | 4,724 | 92 | import pandas as pd
import numpy as np
import eLife_Grid_anchoring_2024.analysis_settings as Settings
from astropy.timeseries import LombScargle
from astropy.convolution import convolve, Gaussian1DKernel
import os
import traceback
import sys
def add_rolling_threshold(spike_data, shuffle_path):
gauss_kernel_std=Set... |
d909eac420c4e6ee85fd30f526c1113d25ee924cc525f9fb14f3148bf07e7e87 | Python | 4,724 | 168 | """Module to get datasets in pycaret"""
from typing import Optional
import requests
from pycaret.utils._dependencies import _check_soft_dependencies
def get_data(
dataset: str = "index",
folder: Optional[str] = None,
save_copy: bool = False,
profile: bool = False,
verbose: bool = True,
addr... |
69ff36c68beb25f04370598c878f03a1356f189b5270320d3be8ed27b25cf10f | Python | 4,725 | 177 | """Common utilities for Numba operations with groupby ops"""
from __future__ import annotations
import functools
import inspect
from typing import (
TYPE_CHECKING,
Any,
)
import numpy as np
from pandas.compat._optional import import_optional_dependency
from pandas.core.util.numba_ import (
NumbaUtilErr... |
2f97cb9d4202477fad807439e4c8ab3ae6737bad474b191e213e8775b02d16d3 | Python | 4,727 | 131 | # 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... |
a3b9f8160f444dd67e538050a2ec8d0e8c3de2db73a93e92a6ae3604d35468f3 | Python | 4,728 | 140 | """
Job tracking in databases or other types of stores
All trackers are returned based on conditional imports to avoid
creating dependencies on all types of trackers, which most users
of the pipeline won't ever use.
Authors:
Thomas A. Hopf
"""
from copy import deepcopy
from os import environ
from evcouplings.utils... |
bb8689b59f7659f331f562423f113e559970eaec2c7a0321c0a749ae96c87a47 | Python | 4,728 | 129 | """Parity tests for the tAge cohort transforms against the authors' R output.
Every expectation here is a fixture dumped from the reference R pipeline (see
``tests/data/tage/README.md``), so a passing test means agreement with the
authors' implementation rather than with another pyaging code path. The stage
chain is m... |
4a660c5403206ee190ac339321f533eb738263cec83e4c9113ef1652ebc17b12 | Python | 4,729 | 135 | import torch
import torch.nn as nn
import torch.nn.functional as F
class ContBatchNorm3d(nn.modules.batchnorm._BatchNorm):
def _check_input_dim(self, input):
if input.dim() != 5:
raise ValueError('expected 5D input (got {}D input)'.format(input.dim()))
#super(ContBatchNorm3d, self)._c... |
4113302077c620a49f877581d267a33b16f640b926765361e9ce753dfb7793a7 | Python | 4,731 | 141 | import numpy as np
import pytest
import pandas as pd
import pandas._testing as tm
@pytest.mark.parametrize(
"data, categories",
[
(list("abcbca"), list("cab")),
(pd.interval_range(0, 3).repeat(3), pd.interval_range(0, 3)),
],
ids=["string", "interval"],
)
def test_map_str(data, catego... |
2d023d1fecee8087139373f48cea6d49465ff6eaff878aac0abc1314c5eb54c8 | Python | 4,732 | 128 | import zoneinfo
import numpy as np
import pytest
import pandas as pd
import pandas._testing as tm
class TestTZConvert:
def test_tz_convert(self, frame_or_series):
rng = pd.date_range(
"1/1/2011", periods=200, freq="D", tz=zoneinfo.ZoneInfo("US/Eastern")
)
obj = pd.DataFrame(... |
35400ad506ec56922f3e09b7e8935ec23acbd82d7161319f513025211a7baeef | Python | 4,733 | 117 | import matplotlib.pyplot as plt
import os
import sys
from matplotlib.colors import ListedColormap
paths = [os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),'src')]
sys.path.extend(paths)
from src.draw import draw_angle_stimulus, dra... |
eeed863f7c98df141447f9d7f959afc6b8968641e51bdf4f2dfe7dd4d5929ad1 | Python | 4,733 | 146 | from viewContainer import viewContainer
from StimulationSystem.StimulationProcess.StimulateProcess import StimulateProcess
from StimulationSystem.StimulationProcess.FinishProcess import FinishProcess
from StimulationSystem.StimulationProcess.IdleProcess import IdleProcess
from psychopy import visual
from psychopy ... |
97fd455619b346de88c71bb5a8f4a73c081e34859c35f2a2c0552a91d6d145e3 | Python | 4,734 | 161 | # Copyright 2018-2020 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... |
d46674d838625a8dac4b0e94fa701870d1ee1e652d8e97753d5d05ae800c8eed | Python | 4,734 | 138 | from datetime import timedelta
import numpy as np
import pytest
from pandas.core.dtypes.dtypes import DatetimeTZDtype
import pandas as pd
import pandas._testing as tm
class TestDataFrameDataTypes:
def test_empty_frame_dtypes(self):
empty_df = pd.DataFrame()
tm.assert_series_equal(empty_df.dtype... |
d7ba20359bcf316b3248a60a49e3828871b40f5eaa1aa2ca03197f24177ff8dd | Python | 4,737 | 135 | # -*- coding: utf-8 -*-
"""
Created on Fri Oct 13 14:46:54 2023
@author: nrq2
"""
## ssh rachel@nostromo.ncl.ac.uk
## spyder-scenic-ad3
# cd /data/rachel/Linda_Lako/Retina/AD3/ATAC_analysis/SCENIC/
# conda activate scenicplus
# python -m spyder_kernels.console
# /home/rachel/.local/share/jupyter/runtime/kernel-2436... |
6d92db1ec4c20770fa6a6895d1625706a5aadb60f7cfe8d36448f0b6a538dd75 | Python | 4,738 | 179 | import numpy as np
import matplotlib.pyplot as plt
# increase the figure size
plt.rcParams["figure.figsize"] = [12, 10]
# remove the top and right spines from plot in the global plt setting
plt.rcParams["axes.spines.top"] = False
plt.rcParams["axes.spines.right"] = False
# change the linewidth of the axes and spines
... |
7a99f9ca93f2af7a41fa2592f263c5c10ab42c3e66732a895eb4f14abf471779 | Python | 4,738 | 118 | import torch
from torch import nn, optim
from torch.nn import functional as F
class ModelWithTemperature(nn.Module):
"""
A thin decorator, which wraps a model with temperature scaling
model (nn.Module):
A classification neural network
NB: Output of the neural network should be the classific... |
0170eca46ddc2d4467603cb9bfbf83a97aba31e6caf47f100e268497f89b24fa | Python | 4,741 | 120 | """
==============================================
Compute SESAME inverse solution on evoked data
==============================================
In this example we shall apply SESAME on an evoked dataset,
corresponding to the response to an auditory stimulus. Data are taken from the MNE-Python
`sample <https://mne.too... |
653257c76e030bcc62dcb42c2760e0ef8e973aa465ddc5b1ceb1c8e7a8a39a92 | Python | 4,743 | 115 | """Test ViT backbone utilities."""
from unittest.mock import MagicMock, patch
import safetensors.torch
import torch
from lightning_pose.models.backbones.vit import load_vit_backbone_checkpoint
class TestLoadVitBackboneCheckpoint:
"""Test the load_vit_backbone_checkpoint function."""
def _make_base(self, s... |
3b8befa9188248e65cfd59b5c78aea872a5d986a8a9ce8df8d9e4e4f66ef958a | Python | 4,746 | 167 | """
CNN NLP operations closely modeled after the original paper's vision task.
"""
import torch
import torch.nn as nn
from darts.api import Model
OPS = {
'none' : lambda c, stride, affine: Zero(stride),
'avg_pool_3' : lambda c, stride, affine: nn.AvgPool1d(3, stride=stride, padding=1, count_include_... |
573d2361469fc7949aa23c24aba67b5bef34d07376ee79b6c089c292d86ca58f | Python | 4,751 | 139 | # Copyright 2018-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 ... |
8c4e6c4a59230f3dd79eaa0ab7b316ac9cc1dc6d3a0ae5fc57e07168aef0363c | Python | 4,752 | 121 | import torch
from torch import nn
from torch_geometric.utils import scatter
import math
from ..mlp import MLP
from ..utils import graph_softmax
# Typing
from torch import Tensor
from typing import List, Optional, Tuple
class EquivariantAttention(nn.Module):
def __init__(self, dim: int, num_heads: int, edge_dim:... |
94e1433de01e321f37ac6c5c96f833eb534e6de8416bdd208e20fc7211c0b626 | Python | 4,752 | 132 | import numpy as np
import pytest
import pandas as pd
import pandas._testing as tm
class TestConcatSort:
def test_concat_sorts_columns(self, sort):
# GH-4588
df1 = pd.DataFrame({"a": [1, 2], "b": [1, 2]}, columns=["b", "a"])
df2 = pd.DataFrame({"a": [3, 4], "c": [5, 6]})
# for sor... |
e3548748ec1398c98d52b5732be63ba3d17862f63bf9ab6f3925a2821668b1ba | Python | 4,752 | 128 | """Dataset consultant — reads a CSV's profile and suggests a task + target +
preprocessing strategy + risk flags.
The prompt includes the column sample + row count; the LLM doesn't get the
raw file (too large, and it's not needed — column types + cardinality +
cardinality-of-target are what matters for task inference)... |
3e1e06968a844c32e4e475a0aa4438001f02f7ada27c5fdda0d240f64bed9413 | Python | 4,753 | 131 | import os
import argparse
import yaml
import numpy as np
import matplotlib.pyplot as plt
from trainer import evaluate
def read_yaml():
# read in yaml
parser = argparse.ArgumentParser()
parser.add_argument("--config", required=True, help="Path for the config file")
parser.add_argument("--exp_ids", ty... |
a5cf5c942987d1bd743f9a99fbdaf9ee244a11d235bf30f43c11c62e4180cd99 | Python | 4,757 | 114 | """
.. module:: gfx_mpr
:platform: Linux, Windows
:synopsis: Utils for multi-planar reformatting (MPR)
.. moduleauthor:: Fredrik Nysjo
"""
import gfx_utils
import numpy as np
import glm
MPR_PLANE_X = 0
MPR_PLANE_Y = 1
MPR_PLANE_Z = 2
MPR_PRESET_NAMES = ["Auto", "Custom", "Brain (CT)", "Head-neck (CT)", "Proba... |
def82c13ed93448c6aeadf2733cfa1de7df5634fce693909f96c2ccc71274fdf | Python | 4,757 | 166 | """
Index mapping for PDB structures
Authors:
Thomas A. Hopf
Charlotta P. Schärfe
"""
import numpy as np
import pandas as pd
from evcouplings.align.alignment import Alignment, parse_header
def map_indices(seq_i, start_i, end_i,
seq_j, start_j, end_j, gaps=("-", ".")):
"""
Compute index ... |
a4db58c7bbf3e50302cac1308446e07193cc83d02dd627e2fd426dc851de989a | Python | 4,761 | 155 | import json
import tarfile
from pathlib import Path
import pandas as pd
from nilearn.connectome import ConnectivityMeasure
from fmriprep_denoise.visualization import tables
MOTION_QC_FILE = "motion_qc.json"
project_root = Path(__file__).parents[2]
inputs = project_root / "data"
group_info_column = {"ds000228": "Chil... |
a84a1edcdc6f7334ce833efd1dbc4d0d754e74251eb6116448c3e4d6361ee43f | Python | 4,761 | 107 | # 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... |
dbb4c487f1f6af4a42d03463d8f804ae2c2eff42a1822c94d29ba10d7cd11e03 | Python | 4,761 | 127 | import ipywidgets as widgets
import config
def change_dim(value):
if dim_select.value == '1D':
config.dim, config.csd_profile, config.kCSD, config.visibility_map = \
config.initialize(dim_select.value)
elif dim_select.value == '2D':
config.dim, config.csd_profile, config.kCSD, conf... |
f76441d8fedb5100f8ddb9031ae7772609c6d12ed473a5325af8882b0f82e0a2 | Python | 4,762 | 108 | """Deterministic volume augmentation on raw, full-resolution volumes.
Ports `transform`/`rotate_img` from `Dataset_MRI.ipynb` / `Dataset_PET.ipynb`
(rotate / vertical-flip / horizontal-flip, chained 1-5 times, weighted
0.5/0.25/0.25): see `docs/legacy-notebooks-inventory.md`.
**Contract**: `augment_volume` operates o... |
4ae3970b2566c604c11ab936ed7d173a1ebda82aad37ed9c7348c9daed8f8df4 | Python | 4,764 | 132 | import math
from pathlib import Path
import pytest
import tbparse
from omegaconf import DictConfig, ListConfig, OmegaConf
from lightning_pose.train import train
pytestmark = pytest.mark.gpu
def _get_base_cfg(cfg):
# 2 steps per epoch to exercise difference between stepwise vs epochwise.
return OmegaConf.me... |
740419ef1c2248a18c6e9db1dc6b8ebab4d361fa7dc4909c237e0f82210eb3b9 | Python | 4,764 | 95 | import os
import sys
import re
import pandas as pd
import pdb
# import glob
# import argparse
# import subprocess
# import multiprocessing
def split_M_files(file_ldscore, chromosome, prefix_genomic_annot, list_annotations):
### Both file_M and file_M_5_50 contains a single line with the same number of fields as the ... |
178c9ba2ac9a9ade394596aeac874a53141139223fb9d3418abacd184dcedd2b | Python | 4,765 | 192 | from __future__ import annotations
from typing import (
TYPE_CHECKING,
Any,
ClassVar,
)
import numpy as np
from pandas.util._decorators import set_module
from pandas.core.dtypes.base import register_extension_dtype
from pandas.core.dtypes.common import is_float_dtype
from pandas.core.arrays.numeric imp... |
f45ae6e7b63e0f4bda096e09d72cfea7b1386bb6b66e1b87c97b77adb56dc7c6 | Python | 4,767 | 146 | """Phase 14: queue + worker admin routes.
Per-class queue depth + active worker visibility, so an admin page can
render "how many jobs waiting on the gpu queue / how many workers
listening".
Endpoints:
- ``GET /admin/queues`` queue depth + recent throughput
- ``GET /admin/workers`` active worker... |
257066141ba90cefc63ffca116b4ee2f3ce9bb26c757b17de1638af4ad0095ed | Python | 4,768 | 158 | # Copyright 2025 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... |
1eb7e3e75acee3a66ba0771e2e685de835178bea8a25281c7130ddeb755642cd | Python | 4,770 | 107 | # Guided Integrated Gradient
from .integrated_grads import compute_grads
from ..utils.process import get_last_layer
import numpy as np
import tensorflow as tf
import math
# A very small number for comparing floating point values.
EPSILON = 1e-9
def l1_distance(x1, x2):
"""Returns L1 distance between two points."... |
62d657ced137a542f1b43ff8d40277f671e04a10277541553f273cd1e8d68a8f | Python | 4,770 | 103 | # 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... |
3628ffae95edcb8baf5a6632f37879aa29bd8ddb3f2c44e0b61bdfd9d5afa036 | Python | 4,772 | 165 | import numpy as np
import pandas as pd
import pytest
"""
This file contains pytest fixtures for generating and using synthetic data in the PCNtoolkit.
The fixtures defined here include:
1. Number of training, testing, and transfer data points
2. Number of covariates and response variables
3. Functions to generate num... |
397c66d6f2c5acd456074072a6a03d822c5c8d383877e5295257a7ff2d75b970 | Python | 4,773 | 151 | import os
import pandas as pd
from deepglyco.chem.common.elements import ElementCollection
from deepglyco.chem.gpep.fragments import GlycanFragmentTypeCollection
from deepglyco.chem.gpep.glycans import MonosaccharideCollection
from deepglyco.chem.gpep.gpmass import GlycoPeptideMassCalculator
from deepglyco.chem.pep.am... |
2b5ee41f8eb1737208db4e4c3c152fa55e89b5473146c331689a9256774c6f8e | Python | 4,774 | 141 | import numpy as np
import pytest
from pandas.errors import Pandas4Warning
import pandas as pd
import pandas._testing as tm
class TestDropna:
@pytest.mark.filterwarnings("ignore:The inplace keyword in Series.dropna")
def test_dropna_empty(self):
ser = pd.Series([], dtype=object)
assert len(s... |
f8058f8aca9477914345fcc1fc58940a655a5fda4c1f4dd90ccaab80b215e990 | Python | 4,774 | 106 | # 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... |
a513ed7e20de7c83fad98ebe5941321890bb33b182a88bbe0b20b3d3f6bc2c62 | Python | 4,776 | 127 | """Tests for DcfData class."""
import pytest
import torch
from einops import repeat
from mrpro.data import DcfData, KTrajectory
from mrpro.utils import RandomGenerator
def example_traj_rpe(n_ka: int, n_kr: int, n_k0: int, broadcast: bool = True):
"""Create RPE trajectory with uniform angular gap."""
krad = r... |
9a9913a61599a75cc4e2db033d6fff015da9136bb3d48475988522154bdb6065 | Python | 4,778 | 190 | import os
import uuid
import pytest
import pandas.util._test_decorators as td
import pandas.io.common as icom
from pandas.io.parsers import read_csv
@pytest.fixture
def compression_to_extension():
return {value: key for key, value in icom.extension_to_compression.items()}
@pytest.fixture
def tips_file(datapa... |
ee486e1872e9f2376b3608c06af4c8b5d9ad2d2ff38cb9c5d3c7c03739e1d9ae | Python | 4,779 | 123 | # 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... |
c41d20a25a75083139e242b4bedc1ee0c03ffbb64aabca0538169ea8801822ff | Python | 4,782 | 112 | import sys
import collections
#import copy
class CueGraph(dict):
def add(self,src,lbl,dst):
self[src,lbl]=dst
def readline(self,s='',linenum=0):
## for each dep...
for dep in s.split():
## report ill-formed deps...
if ',' not in dep:
sys.stderr.write('WARNING: Improperly formed de... |
421db5b87f757fe83c18c30182847385ade61684648a97d0dbe559fedbb37832 | Python | 4,783 | 110 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 24 14:38:08 2019
@author: vman
"""
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import rc
rc('font',**{'family':'sans-serif','sans-serif':['Arial']}, size=14)
rc('text', usetex=False)
def plotModel():
# build model va... |
16059448fdeebf9a83731f9bf91c5cf6528979b0344792c83ee04cc6aee27742 | Python | 4,785 | 104 | #Functions for checking how well sequences match to hmm profiles.
#requires hmmer3 to be installed.
import uuid
from pathlib import Path
import subprocess
from collections import OrderedDict
from pgen import utils
def _open_if_is_name(filename_or_handle):
out = filename_or_handle
input_type = "handle... |
32c988f7a1ad1bfbd3b214dd2cd9be7ccbc82b647009f17dc003e3707ac011a5 | Python | 4,786 | 97 | import os
from PyQt5.QtWidgets import QWidget, QHBoxLayout, QLineEdit, QPushButton, QFileDialog, QMessageBox
from PyQt5.QtCore import pyqtSignal
from scanometrics.GUI import styles
from scanometrics.GUI.Icon import Icon
class PathSelector(QWidget):
"""
A custom widget for selecting a folder path with addition... |
165bddad0918976804c96c190ab0e3b6bfad5773172aaef4069b5327195c3fdb | Python | 4,787 | 122 | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules.activation import ReLU
from torch.nn.modules.batchnorm import BatchNorm3d
from torch.nn.modules.conv import Conv3d
class UNet3D(nn.Module):
def __init__(self, in_channel, n_classes, batchnorm_flag=True):
self.in_channe... |
75d3387c355a6ecc85ddb3d462872efeb5ad8bd2705dd3d31e65c5239d3a3212 | Python | 4,788 | 99 | from PIL import Image
from Environment import *
from Parameter import *
from Splice_post.utils import segmentation_quick_view
def concat(image_list, save_path, index):
start_x, start_y= 0, 0
restored_array = np.zeros((int(Preprocessing['z_num']), int(Preprocessing['patch_weight_num'])*int(Preprocessing['cut_si... |
c3b39714600b35df7c3eb5262636aff03a2befc2e390e0d3b95ad726e855a201 | Python | 4,788 | 190 | """Pydantic request/response models shared across routes."""
from __future__ import annotations
from datetime import datetime
from pydantic import BaseModel, EmailStr, Field
# ---------------------------------------------------------------- auth
class BootstrapRequest(BaseModel):
"""First-run admin + workspac... |
3e97b03034a9e49b91a1435ca9878a9fe811882fc2086f149f596738c84841c9 | Python | 4,792 | 146 | """
To acquire stacks of images with the fluo lamp on, for the fluorophore
classification project.
"""
import os
import time
import json
import cv2
import numpy as np
import matplotlib.pyplot as plt
#%% Load platform:
import pycromanager_tessie as pmt
# Start platform (without sync arduino):
platform = pmt.microscop... |
08ae2866e6f1084e2439a396b5a951b7f9ff82530557840db24355c10b3da22f | Python | 4,794 | 130 | import re
import numpy as np
import pytest
from pandas.core.dtypes import generic as gt
import pandas as pd
import pandas._testing as tm
class TestABCClasses:
tuples = [[1, 2, 2], ["red", "blue", "red"]]
multi_index = pd.MultiIndex.from_arrays(tuples, names=("number", "color"))
datetime_index = pd.to_d... |
e62f08b62146d512f1ed5bbf0f94573e78f57465578f9da56f27ae5b2986dd93 | Python | 4,794 | 109 | """Deterministic, generated BAM/FRAG benchmark inputs; no external downloads."""
import hashlib
import json
from pathlib import Path
import random
import struct
import zlib
def sha256(path):
digest = hashlib.sha256()
with Path(path).open('rb') as handle:
for block in iter(lambda: handle.read(1024 * 1... |
826a38d4a37d0a59d622289daaee6df7ccc5ad7e268d71038574fdd3c0db6995 | Python | 4,798 | 131 | # Time-stamp: <2024-10-02 16:53:35 Tao Liu>
"""Description: predict fragment size.
This code is free software; you can redistribute it and/or modify it
under the terms of the BSD License (see the file LICENSE included with
the distribution).
"""
# ------------------------------------
# python modules
# -------------... |
b1939cb0ed508e62c1d79cba1045f1fb151aa6064630ea1102b2386026603211 | Python | 4,798 | 150 | # SAPpy
from util.sarpy.SARpy import *
from util.sarpy.SARpytools import *
# rdkit
from rdkit import Chem
from rdkit.Chem import Recap
from rdkit.Chem import BRICS
# Functions
# def recap_frag_smiles_leaf(mols):
# all_leaves=set()
# for mol in mols:
# tree = Recap.RecapDecompose(mol)
# leaves =... |
51af6c7bf1da21ea01192e4ee9c74add9afaf5734365f9fc5301e4689fdedbcb | Python | 4,800 | 110 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 21 18:33:38 2019
@author: vman
"""
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
def computeRegressor(data):
# Parse the data frame
data.loc[data.resp_Guess == -1, 'resp_Guess'] = np.nan
d... |
587c62569260e411b3b14f002e97aedd4e392b57aac481445ee42297fced2998 | Python | 4,800 | 117 | import typer
import torch
import pkg_resources
from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())
from rdkit import Chem
from rdkit.Chem import rdChemReactions
import pandas as pd
from tqdm import tqdm
from typing import List
from rxn_yields.core import SmilesTokenizer, SmilesClassificationModel
i... |
0e16c93215eeacb39f225d90e4f725ed7fb93980834b5f9dbbce61e3f37101c4 | Python | 4,801 | 138 | import gymnasium as gym
import numpy as np
from smac.env import StarCraft2Env
from smac.env import MultiAgentEnv
class SMACEnv(gym.Env):
def __init__(self, name="3m", **kwargs):
gym.Env.__init__(self)
self._seed = kwargs.pop('seed', None)
self.reward_sparse = kwargs.get('reward_sparse', Fal... |
7ca58970f4576f0c0c3abbb5f51c3c8c41820525e66413ea49381e384033bbab | Python | 4,801 | 136 | import os
import glob
import cPickle
import copy
import argparse
import pandas as pd
from rdkit import DataStructs
from rdkit.Chem import AllChem
from rdkit import Chem
def calculate_drug_similarity(drug_dir, input_dir, output_file):
drugbank_drugs = glob.glob(drug_dir + '*')
input_drugs = glob.glob(input_d... |
eaafab878afb42d9068a7d164a3b12f1b84d194a03970c8da3672c0c51fc766f | Python | 4,803 | 172 | from __future__ import annotations
from datetime import (
date,
datetime,
time,
timedelta,
)
from decimal import Decimal
import pytest
from pandas.core.dtypes.dtypes import (
ArrowDtype,
)
import pandas as pd
import pandas._testing as tm
pa = pytest.importorskip("pyarrow")
@pytest.fixture(par... |
793e4a9fc77fc311c666735d8782b326256a9fa56645cc5e677eb87a320d4a0a | Python | 4,804 | 144 | from datetime import timedelta
import numpy as np
import pytest
from pandas._libs import lib
import pandas as pd
import pandas._testing as tm
class TestTimedeltaIndexInsert:
def test_insert(self):
idx = pd.TimedeltaIndex(["4day", "1day", "2day"], name="idx")
result = idx.insert(2, timedelta(da... |
b837238328be18a7d7da0c31717cf3e7ed72a466f4d48a1387d77659beef92c3 | Python | 4,804 | 108 | from pathlib import Path
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
from src import plotting
from src.analyzier import StatsAnalyzer
from src.experiment import ExperimentResults
class Plotter(StatsAnalyzer):
def __init__(self, results:ExperimentResults):
s... |
a718e41394420f94f784c33c327c2c403c38a4e99fa6fe4f9c7def62f06ec420 | Python | 4,805 | 176 | # -*- encoding: utf-8 -*-
# JN 2015-05-11
# what do I want in this script?
# * extraction thresholds in each region
# (and regression line, or other measure of variability)
# * rationale it's interesting to see whether highly variable channels are
# in one macro
# * firing rate stability for non-artifacts (correlated ... |
1d7e53dc7b3d2b5cd19e5902844b0ffd026ebb7d3473901d43784d9613d08289 | Python | 4,806 | 125 | import venn5
from matplotlib import pyplot as plt
import os.path
import pysam
from pybedtools import BedTool
def overlap_high_confident(input_path, sample, tool):
output_path = os.path.join(input_path, "{}_{}".format(sample, tool))
if not os.path.exists(output_path):
os.mkdir(output_path)
# # ... |
9fb8427d485a4682f9fa631dcce2ae15debf60da5edbb5f68dc92c0dc4f7bdca | Python | 4,809 | 186 | # Adopted and modified from https://pytorch-geometric.readthedocs.io/en/latest/_modules/torch_geometric/utils/smiles.html
import torch
from rdkit import Chem
x_map = {
'atomic_num':
list(range(0, 119)),
'chirality': [
'CHI_UNSPECIFIED',
'CHI_TETRAHEDRAL_CW',
'CHI_TETRAHEDRAL_CCW',... |
10dac74f594c8451364df8110e1d3e6106057c7cdae635b2aa89f6e36578d265 | Python | 4,810 | 72 | # The following implementation is based on the techniques described in:
# "Object Landmark Discovery Through Unsupervised Adaptation" by Enrique Sanchez and Georgios Tzimiropoulos
# You can find the article here: http://papers.nips.cc/paper/9505-object-landmark-discovery-through-unsupervised-adaptation.pdf
#
# For ... |
714e8b77e3e5da2659084ff1bf82ff6d4aa4d348ae8564f9b83bc793d49e4eb8 | Python | 4,813 | 148 | import numpy as np
import tensorflow as tf
from dm_control import viewer
import wandb
from rl_toolkit.networks.models import Actor
from ...core.process import Process
from ...core.wrappers import dmControlGymWrapper
class Tester(Process):
"""
Tester
=================
Attributes:
env_name (s... |
826b4db89171bd1912df2144146da870ee8ce46b4ee967591145e892fba35822 | Python | 4,816 | 133 | """
Based on:
https://github.com/KarenUllrich/binary-VAE
"""
import argparse
import json
import os
from shutil import rmtree
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import numpy as np
import pandas as pd
import tensorflow as tf
import tensorflow_probability as tfp
from ribosomal_autoencoder.model import ConcreteGA... |
1fd1c35df8fd6928b8ae39204e36a694f969c32ba036622b296cabc357c23eed | Python | 4,817 | 158 | """Slice Profiles."""
import abc
from collections.abc import Sequence
from math import log
import numpy as np
import torch
from mrpro.utils.TensorAttributeMixin import TensorAttributeMixin
__all__ = ['SliceGaussian', 'SliceInterpolate', 'SliceProfileBase', 'SliceSmoothedRectangular']
class SliceProfileBase(abc.AB... |
949f4ad050c70d14b5fb7f8a6ad30f4601bfaa4135a31bca954e92bb29b1f1bb | Python | 4,817 | 139 | import pandas as pd
from sktime.forecasting.base import BaseForecaster
from pycaret.utils.time_series import TSExogenousPresent
# from pycaret.time_series import TSForecastingExperiment
def _disable_pred_int_enforcement(forecaster, enforce_pi: bool) -> bool:
"""Checks to see if prediction interval should be enf... |
acbad4394bc42cf73ce32790c8d878b97d206e3f1aa010f173d2cd6c5b38976f | Python | 4,818 | 101 |
'''
This script takes a file with the columns [chrom, pos, ...] (but no headers) and adds the field `gene`.
'''
from ..utils import get_gene_tuples
from ..file_utils import VariantFileReader, VariantFileWriter, get_filepath
from .load_utils import mtime
from intervaltree import IntervalTree, Interval
import bisect
i... |
fb9ce9ae8f8f8f46b0bfa518e7f5ee11435d9ef007298d0139c9f94f4d4530a1 | Python | 4,818 | 141 | import numpy as np
import matplotlib.patches as patches
from UICreator.StimTargetRect import StimTargetRect
import matplotlib.pyplot as plt
import os
import matplotlib
from tqdm import tqdm
matplotlib.use('agg')
class frameLoader():
def __init__(self) -> None:
self.frameSet = None
... |
fdd9c3ae60771d9c51e93890b3d4d8611d4abff74466c40fabd9f99c8c5edba8 | Python | 4,819 | 114 | # -*- coding: utf-8 -*-
from keras.engine.topology import Layer
from keras import backend as K
# class AvgAggregator(Layer):
# def __init__(self, activation: str ='relu', initializer='glorot_normal', regularizer=None,
# **kwargs):
# super(AvgAggregator, self).__init__(**kwargs)
# ... |
3d70025954bdc283ff7aab8965a48b737e08fc91de9234ac38bf956c0670cf2b | Python | 4,820 | 113 | """Methods for encoding text into brain maps."""
import numpy as np
from nilearn.masking import unmask
from sklearn.feature_extraction.text import CountVectorizer
from .. import references
from ..due import due
from .utils import weight_priors
@due.dcite(references.GCLDA_DECODING, description="Citation for GCLDA enc... |
537d6465893c4b215bf55e38c9dba1d66759483394694c300da5870f21d85df3 | Python | 4,822 | 176 | """
Tests for the pandas custom headers in http(s) requests
"""
from functools import partial
import gzip
from io import BytesIO
import pytest
from pandas._config import using_string_dtype
import pandas.util._test_decorators as td
import pandas as pd
import pandas._testing as tm
pytestmark = [
pytest.mark.sin... |
0ee2dbd5b1f44bc1ca08f31984e8305389556e08c7a56d640243ad517bafe5c1 | Python | 4,824 | 135 | from pathlib import Path
import numpy as np
import pytest
import pandas as pd
import pandas._testing as tm
pyreadstat = pytest.importorskip("pyreadstat")
@pytest.mark.parametrize("path_klass", [lambda p: p, Path])
def test_spss_labelled_num(path_klass, datapath):
# test file from the Haven project (https://hav... |
934fab7877544fdbe5cfda5cf0ea8356eabba12934e93686da1b1867bb5758e2 | Python | 4,825 | 163 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# tractify documentation build configuration file, created by
# sphinx-quickstart on Fri Jun 9 13:47:02 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# au... |
de89491162e87579fba850820a68816280783b0958da751fda6d02b2f9325f8b | Python | 4,825 | 142 | import numpy as np
import pytest
import pandas as pd
import pandas._testing as tm
def test_agg_relabel():
# GH 26513
df = pd.DataFrame({"A": [1, 2, 1, 2], "B": [1, 2, 3, 4], "C": [3, 4, 5, 6]})
# simplest case with one column, one func
result = df.agg(foo=("B", "sum"))
expected = pd.DataFrame({"... |
318c1982400fc9e3959ee839ec86e44f727d191cf841e1e913914feb70aeb96f | Python | 4,827 | 154 | import torch, os, scipy
import numpy as np
from scipy.signal import butter, filtfilt
from scipy.interpolate import interp1d
from glob import glob
from torch.fft import fft, ifft, fftshift
def whitening_from_covariance(CC):
""" whitening matrix for a covariance matrix CC
this is the so-called ZCA whitening ... |
97eabb484ee2aff382b57071e5f18d8db89de9f13f5878ccf66bb059ba376eb4 | Python | 4,827 | 118 | import torch
import numpy as np
# Typing
from torch import Tensor
from typing import Tuple, List, Optional
####################### Base modules #######################
from torch import nn
from graphite.nn.basis import GaussianRandomFourierFeatures
from graphite.nn import MLP
class ScoreDynamicsModel(nn.Module):
... |
147c275f2044a6e29387f10d3f488aa7b6f947f93d0cb82594ea1977ab14e664 | Python | 4,828 | 168 | import codecs
import locale
import os
import platform
import pytest
from pandas._config.localization import (
can_set_locale,
get_locales,
set_locale,
)
from pandas.compat import (
ISMUSL,
WASM,
is_platform_windows,
)
import pandas as pd
_all_locales = get_locales()
_skip_if_only_one_local... |
4eb54ba5bb935d7e5bf320037565ea5a7afccd298fc7f8b738a33ea67f6fa4fd | Python | 4,829 | 149 | ''' This program will update janelia-neuronbridge-published-stacks
'''
import argparse
from copy import deepcopy
from operator import attrgetter
import sys
import boto3
from colorama import Fore, Style
import MySQLdb
from tqdm import tqdm
import jrc_common.jrc_common as JRC
# Configuration
TEMPLATE = "An exception o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.