sha256 stringlengths 64 64 | language stringclasses 27
values | size int32 1 491k | lines int32 1 21.8k | content stringlengths 1 200k |
|---|---|---|---|---|
3f6e6df3d1f28c11a507ade5f9e05d20e581e80035a371f4f08e11d3ca7f52dd | Python | 3,096 | 52 | import numpy as np
import lpips
from data import data_loader as dl
import argparse
from IPython import embed
parser = argparse.ArgumentParser()
parser.add_argument('--dataset_mode', type=str, default='2afc', help='[2afc,jnd]')
parser.add_argument('--datasets', type=str, nargs='+', default=['val/traditional','val/cnn',... |
ead35618e19edddd73e615f0b37abf7acd59d42577f12bbd7d20dd78068fa926 | Python | 3,096 | 96 | import logging
from torch.utils.data import DataLoader
from chemprop.data.collate import (
collate_batch,
collate_cuik_batch,
collate_mol_atom_bond_batch,
collate_multicomponent,
)
from chemprop.data.datasets import (
CuikmolmakerDataset,
CuikmolmakerReactionDataset,
MolAtomBondDataset,
... |
f6e8ba49495f892c702c3616b2760c16821dca9288e094eedc1cc36da05ffc36 | Python | 3,098 | 74 | # Copyright (c) Facebook, Inc. and its affiliates.
from torch import nn
from torchvision.ops import roi_align
# NOTE: torchvision's RoIAlign has a different default aligned=False
class ROIAlign(nn.Module):
def __init__(self, output_size, spatial_scale, sampling_ratio, aligned=True):
"""
Args:
... |
c42a783464d34e63dfda64474a90056e361eeb0c0985df0d0e55ca40073e8504 | Python | 3,099 | 92 | #!/usr/bin/env python
#
# Copyright (c) 2018 10X Genomics, Inc. All rights reserved.
#
#
# Code related to the Python version of the SampleDef passed around inside the
# pipeline. Any code related to the argshim doesn't belong here.
from __future__ import annotations
from enum import Enum
# FastqMode enum from lib/... |
bfc2502308f730ec33f0d0cfa05e3dafe8384a37a552b4fbb027093b9eda4943 | Python | 3,101 | 140 | import math
import solara
from mesa.examples.basic.virus_on_network.model import (
State,
VirusOnNetwork,
number_infected,
)
from mesa.visualization import (
Slider,
SolaraViz,
SpaceRenderer,
make_plot_component,
)
from mesa.visualization.components import AgentPortrayalStyle
def agent_p... |
23367c0d61a2c9d66edd81b861d26c334911173d918160e3a8a28f5f5b16f1a8 | Python | 3,104 | 114 | import nibabel as nib
import numpy as np
import skfmm
from astropy.convolution import convolve as nan_convolve
logfile = open(snakemake.log[0], "w")
# this function solves the Laplace equation for Anterior-Posterior, Proximal-distal, and Inner-Outer axes of the hippocamps
convergence_threshold = snakemake.params.co... |
f19f18393849caf896b16edcfc7b044f7688222c78c71a99dd60d9a06a3512f5 | Python | 3,107 | 84 | """
Tutorial 1: Building your first gradient
=================================================
In this example, we will derive a gradient and do some basic inspections to
determine which gradients may be of interest and what the multidimensional
organization of the gradients looks like.
"""
##########################... |
9f85394765e29995a24003a0263017071b14adc202537941b1233203518ec4b2 | Python | 3,109 | 95 | import argparse
import pandas as pd
import os
import shutil
import sys
def filter_structure_files():
parser = argparse.ArgumentParser(
description="Filter PDB/PQR files based on a CSV of UniProt IDs.",
formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument(
... |
73ba6cd1b4adae6376538ca1ce6abb0e971f0d308623cf08c818f9c9d04987f7 | Python | 3,110 | 72 | #!/usr/bin/env python
# Copyright 2017-2018 Biomedical Imaging Group Rotterdam, Departments of
# Medical Informatics and Radiology, Erasmus MC, Rotterdam, The Netherlands
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obt... |
f78d59f1eda0de778f681c100604e6ff3800257169d58f759dc26bb5c5af63b9 | Python | 3,111 | 104 | """ Visualization of data """
__author__ = "Fabi Bongratz"
__email__ = "fabi.bongratz@gmail.com"
import os
from typing import Union
from collections.abc import Sequence
import numpy as np
# import open3d as o3d # Leads to double logging, uncomment if needed
import nibabel as nib
import matplotlib.pyplot as plt
impor... |
8fb6f8027bd4f4774f41f120a1d60d2324b74698f51d453d485e225c5021c434 | Python | 3,115 | 93 | from __future__ import annotations
import os
import pandas as pd
import scipy.io as sp_io
from six import ensure_binary, ensure_str
from cellranger.feature_ref import FeatureDef, FeatureReference
from cellranger.library_constants import GENE_EXPRESSION_LIBRARY_TYPE
from cellranger.matrix import FEATURES_TSV_GZ, Coun... |
0c109d464eedcacab1f9f34204ef9c7d36a20d5213c70a2d101fc826c2eb22e7 | Python | 3,116 | 105 |
# %% imports
# general imports
import mne
from functools import partial
# imports from our library
from micorr.estimators import mi_estimators, corr_est
from micorr.realdata import test_est, plotting
# %% Loading the mne sample data
sample_data_folder = mne.datasets.sample.data_path()
sample_data_raw_file = (sampl... |
32417c94618d237a640ce1f22848ed16a4471efbcc7db7db325d0af3878d2dc7 | Python | 3,121 | 74 | from copy import deepcopy
from typing import Iterable, Mapping, Optional, Sequence
import numpy as np
import numpy.typing as npt
import pandas as pd
import xarray as xr
from hsnn.core import SpikeRecord
from hsnn.core.types import SpikeTrains
from .conversion import spike_events_to_trains
from .filtering import selec... |
aa5efaa35b65e7061791bf6395c9a49cbdda0f2ae227950d03147c66de56b89f | Python | 3,123 | 84 | import re
from enum import Enum
from typing import Dict, Mapping, MutableSequence, Optional, Sequence
from ..definitions import NeuronClass, SynapseClass, Projection
NAMESPACE_TYPE_MAPPING = {
'neurons': NeuronClass,
'synapses': SynapseClass
}
def _split_symbol(symbol: str) -> tuple[str, Optional[int]]:
... |
e0964de4526fe43236df9e269308f86f0e8bd231b044f82dab5ec036798804ca | Python | 3,123 | 79 | import torch
import torch.nn as nn
import random
torch.manual_seed(123)
random.seed(123)
class Contrast(nn.Module):
def __init__(self, args):
super(Contrast, self).__init__()
self.hidden_dim = args.hgt_out_dim
self.proj_cross = nn.Sequential(
nn.Linear(self.hidden_dim, self.hi... |
fb74d179f76ae63a8499205897333a04ca310e3df27264904c5f8848f96003c5 | Python | 3,124 | 87 | import numpy as np
yeo7_colors = np.array([[0, 0, 0, 255],
[0, 118, 14, 255],
[230, 148, 34, 255],
[205, 62, 78, 255],
[120, 18, 134, 255],
[220, 248, 164, 255],
[70, 130, 180... |
978f51a5f0aa5d9d65f4a5739bebe695fc0a9d88480dd7d50dfa4f15313cbb9a | Python | 3,125 | 82 | # -*- coding: utf-8 -*-
# Copyright (c) Facebook, Inc. and its affiliates.
import numpy as np
import os
import xml.etree.ElementTree as ET
from typing import List, Tuple, Union
from detectron2.data import DatasetCatalog, MetadataCatalog
from detectron2.structures import BoxMode
from detectron2.utils.file_io import Pa... |
56fd457d25479c7ef275fd0812b87462effad19893b5fd72ddec056d5c3ddd5a | Python | 3,132 | 89 | from nilearn import surface, plotting
from nilearn.datasets import fetch_surf_fsaverage, fetch_atlas_surf_destrieux
from tristan_pipeline.io.params import *
from tristan_pipeline.utils.plotting_utils import *
FREESURFER_PATH =os.path.join(DATA_DIR, 'derivatives', 'freesurfer')
os.environ["SUBJECTS_DIR"] = FREESURFER_P... |
074716c06d8c19b941a048046e437d7f90d79503e658d7e7787085403f8871e3 | Python | 3,133 | 78 | from .base import BSVTKObjectWrapper
from .data_object import BSTable, BSPolyData, BSUnstructuredGrid
from .algorithm import (BSDataSetMapper, BSPolyDataMapper,
BSLabeledContourMapper, BSLabeledDataMapper,
BSLabelPlacementMapper, BSPolyDataMapper2D,
... |
90827131110b71e92bc4d384908a2eba932a475f57d0da15a69df09d3964da24 | Python | 3,137 | 98 | """compare timings across 2 benchmarks."""
import pickle
import numpy as np
import pandas as pd
filename1 = "timings_1"
filename2 = "timings_2"
with open(f"{filename1}.pickle", "rb") as handle:
timings_1 = pickle.load(handle) # noqa: S301
with open(f"{filename2}.pickle", "rb") as handle:
timings_2 = pickl... |
3aa0b022359a32a4b294f1a0f96318c5dcc2ad329db16cc25f1b6b359b053693 | Python | 3,138 | 89 | import warnings
from typing import Union
import torch
# Add ugly import guards to not break nnunet in case wrong dynamic-network-architectures version.
try:
from dynamic_network_architectures.architectures.primus import PrimusS, PrimusM, PrimusL, PrimusB
except ImportError:
warnings.warn(
"Unable to im... |
5ce9c4d9a4ac371b42bda8651725dd43e8567abaed2f859a5a2c2ab3cb406433 | Python | 3,140 | 89 |
#%% Imports
# Imports from our library
from micorr.simulation import simulations, testing, plotting
from micorr.estimators import mi_estimators, corr_est
# General imports
import numpy as np
from functools import partial
#%% Setting the initial parameters
# Dictionary with the estimators to be tested
est_list = {'... |
010585043db67aa1faf8428ef25ab5d968274ee15f5c7d5bd831b3bd43be879e | Python | 3,143 | 125 | import numpy as np
import pandas as pd
from sklearn.model_selection import StratifiedKFold, cross_val_score
from config import CV_SPLITS, SEED
from evaluation import metric_values, optimism_corrected_metrics, positive_scores
from models import build_pipeline, candidate_grid, fit_candidate
def cv_auprc(
x: pd.Dat... |
1648f9ef589fba4eabf0114c74be4303b1737ff1cff944674b2ce819a23e48a5 | Python | 3,144 | 93 | from mesa import Model
from mesa.datacollection import DataCollector
from mesa.discrete_space import OrthogonalMooreGrid
from mesa.examples.basic.schelling.agents import SchellingAgent
from mesa.experimental.scenarios import Scenario
class SchellingScenario(Scenario):
"""Scenario for the Schelling model.
Arg... |
2670b3c65eefcd70105e94f1c09b721f1679645f19ae736aa1aff41e472dfdc8 | Python | 3,148 | 83 | from __future__ import annotations
import os
import shutil
import tempfile
from contextlib import contextmanager
from pathlib import Path
import pytest
from src.utils import runtime
@contextmanager
def workspace_tmp_dir() -> Path:
root = Path(__file__).resolve().parent / ".tmp"
root.mkdir(parents=True, exi... |
98c8ca8a5808d170297739e2ac14a2428f73622ad07977b14c33da666fdb516d | Python | 3,148 | 95 | # This code is part of OpenFE and is licensed under the MIT license.
# For details, see https://github.com/OpenFreeEnergy/openfe
"""
Test the restraint settings.
"""
import pytest
from openff.units import unit
from openfe.protocols.restraint_utils.settings import (
BoreschRestraintSettings,
DistanceRestraintS... |
3d0a7fec674c0972e9d42c7ff385925565bcd205a9b66289523b1b900de5d280 | Python | 3,151 | 99 | import torch
import pickle
import numpy as np
from transformers import AutoTokenizer, EsmModel
print('start')
def read_data(file_path):
with open(file_path, 'r') as f:
lines = f.readlines()
sequences = [line.split()[1] for line in lines]
return sequences
def get_sequence_embeddings(sequences):... |
85549973dbb0afff3327871a4cff191283626dcdfb472df3cc7486334968c722 | Python | 3,154 | 73 | import SimpleITK as sitk
import shutil
import numpy as np
from batchgenerators.utilities.file_and_folder_operations import isdir, join, load_json, save_json, nifti_files
from nnunetv2.utilities.dataset_name_id_conversion import maybe_convert_to_dataset_name
from nnunetv2.paths import nnUNet_raw
from nnunetv2.utilitie... |
b486b7a2d12fe6dcf9d6ad9beb7f258d3b7f0abefae01b8ec9e67935d77ff84a | Python | 3,154 | 66 | import os
import glob
import argparse
def main(inputPath):
log_file_path = os.path.join(inputPath, "missing_files_log.txt")
SearchPath = os.path.join(inputPath, "**", "anat", "*Stroke_mask.nii.gz")
List_of_Stroke_rois = glob.glob(SearchPath, recursive=True)
print(List_of_Stroke_rois)
for ss in List... |
b5fc7f5c394b536e9b43f623eb01a10967cc53493ae024f42a889827dc7fa73e | Python | 3,156 | 92 | """
If you use this code, please cite one of the SynthSeg papers:
https://github.com/BBillot/SynthSeg/blob/master/bibtex.bib
Copyright 2020 Benjamin Billot
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 Lice... |
1060807e802f33195721de36bcb6814372a683b3650b39c8723113c61d258486 | Python | 3,159 | 71 | #!/usr/bin/env python
# Copyright 2016-2020 Biomedical Imaging Group Rotterdam, Departments of
# Medical Informatics and Radiology, Erasmus MC, Rotterdam, The Netherlands
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obt... |
0fe83684af4fb14ec4a78b1a0729cb0baab5f72087c60295d7895e15c4169b75 | Python | 3,160 | 102 |
#%%
# Imports from the library
from micorr.simulation import simulations, testing, plotting, transformations
from micorr.estimators import mi_estimators, corr_est
# More general imports
import numpy as np
from functools import partial
#%% Initial parameters
# Dictionary with the estimators to be tested
est_list = ... |
382211af0a1e95727b3ced854156129ef04ead09f6a2936e746eb735497e0445 | Python | 3,160 | 110 | import contextlib
import logging
import click.testing
import pytest
from openfecli.cli import OpenFECLI, main
from openfecli.plugins import OFECommandPlugin
@click.command("null-command", short_help="Do nothing (testing)")
def null_command():
logger = logging.getLogger("null_command_logger")
logger.info("Ru... |
43b5b122f818902a6e6e4d1dc99de12111ca9ac1cad7519a95df99dda51badbf | Python | 3,164 | 101 | #
# Copyright (c) 2020 10X Genomics, Inc. All rights reserved.
#
"""Utils for dealing with RTL multiplexing."""
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from cellranger.mro_types.structs import BarcodeReadComponent, WhitelistSpec
def _get_barcode_length(barcode_def: ... |
46c534e1eacbcd045eefe68adbca927cf525a90b1c80bf9e7ec523a43d8c3083 | Python | 3,164 | 95 | from functools import partial
import torch.nn as nn
from fvcore.common.param_scheduler import MultiStepParamScheduler
from detectron2 import model_zoo
from detectron2.config import LazyCall as L
from detectron2.solver import WarmupParamScheduler
from detectron2.modeling import MViT
from detectron2.layers import ShapeS... |
bbbcc49063eab0313cf855f93ebf121635625cffb6236c4fb403c29b722e3a85 | Python | 3,164 | 105 | """Variational Autoencoder for de novo molecular generation."""
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
class VAE(nn.Module):
"""Variational Autoencoder for molecular generation.
Operates on flattened tensor representations of molecules
(one-hot ato... |
4e456ad2e07c41092dcfc84584a86b2de0fe16cbd9cada2a2b6ca68e3bb0677e | Python | 3,166 | 68 | #!/usr/bin/env python
import argparse
import copy
from elastixparameterfile import ElastixParameterFile
def create_mean_transform_bin(input_transformations, output_transformation):
"""
This function reads a number of elastix transform files, creates the mean transformation and writes it back to the specified ... |
d224ed897621e0fa560013db2255913abb8bc67c23ceb06d7a98a992369752d5 | Python | 3,166 | 74 |
############################################################################
# Copyright (c) 2022-2026 University of Helsinki
# Copyright (c) 2019-2022 Saint Petersburg State University
# # All Rights Reserved
# See file LICENSE for details.
############################################################################
... |
adb24656233a4ac01c0a7398076c2c8df43082b69e1facb1c1cce923476affe5 | Python | 3,167 | 70 | from batchgenerators.utilities.file_and_folder_operations import *
import shutil
from nnunetv2.dataset_conversion.generate_dataset_json import generate_dataset_json
from nnunetv2.paths import nnUNet_raw, nnUNet_preprocessed
def convert_autopet(autopet_base_dir:str = '/media/isensee/My Book1/AutoPET/nifti/FDG-PET-CT-L... |
f4edb5a87350f8282dafba04565102069703e0280ba5483f5c756f5bd56291c3 | Python | 3,172 | 97 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu May 30 13:26:55 2024
@author: Ehsan.Sayyah
"""
import numpy as np
from rdkit import Chem
import os
import argparse
import glob
import shutil
import time
import subprocess
def read_sdf(file_path):
# Read SDF file and return a list of molecules
r... |
5df79b89329a63575e2bde43788b9f1d131e3ee537503975ee576a208092f263 | Python | 3,177 | 103 | #!/usr/bin/env python
#
# Copyright (c) 2015 10X Genomics, Inc. All rights reserved.
#
from __future__ import annotations
import collections
import os
import resource
from collections.abc import Callable
from typing import BinaryIO, Literal, TextIO, overload
class FileHandleCache[T_co: TextIO | BinaryIO]:
"""LR... |
339579ea7c335d79ddcd3b1fec2498cd0f981cdfcb45c9370d0bf6e619fee978 | Python | 3,179 | 118 | """This script splits the dataset such that
A selected set of class is separated as a test set while the remaining is the training and val set
"""
import argparse
import torch
import numpy as np
parser = argparse.ArgumentParser(description="Template")
parser.add_argument(
"-id",
"--input-dataset",
requir... |
498e4ce769576d8faa55928320e31890fe50b518da969e2dc33927cf7e9f579f | Python | 3,187 | 91 | #!/usr/bin/env python
# Copyright 2016-2020 Biomedical Imaging Group Rotterdam, Departments of
# Medical Informatics and Radiology, Erasmus MC, Rotterdam, The Netherlands
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obt... |
816fa1c5bbf00f8a35c48bde22f0bc484e0dc96326605bf485a5b73eb7d9fc95 | Python | 3,193 | 125 | """
Django settings for config project.
Generated by 'django-admin startproject' using Django 4.2.1.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.2/ref/settings/
"""
import os
fro... |
b2d8acea1a54af06e8ca7ff7486188d0524fb08fa04eb0786942fcfb7fbd3c3e | Python | 3,195 | 92 | # responses/session_responses_v2.py
from .unit_response_v2 import UnitResponse
from spikeinterface import full as si
from pathlib import Path
class SessionResponses:
def __init__(self, session_path, sorting_analyzer_path, trial_df, all_stim_timestamps, timing_params):
self._session_path = session_path
... |
fb9c93c108ecec6bdf04bb68b63c679e39335ebe707b0abadf2b093921ff4ab8 | Python | 3,196 | 74 | import cv2
import os
os.nice(20)
import subprocess
import numpy as np
import tifffile
from skimage import morphology
import platform
if platform.system() != 'Linux':
raise Exception # this script is designed to use Linux bash commands. Please use Linux
try:
subprocess.run(["ffmpeg"], stdout=subprocess.DEVNUL... |
52de7acea8689e1bc30537cfc74b5c31faca3ea9f599340da45dc3b9084250e8 | Python | 3,199 | 98 | from itertools import product
import torch
from tqdm import tqdm
import numpy as np
from . import config
from .utils.condition import AttackParamsLoader, Condition, TuneCondition
from .utils.model_utils import load_model
import torchvision.transforms as transforms
from .utils.activation_manager import ActivationManage... |
3d9d06bbb78c4ad6a17c1db3dd4d09ad1d67e6f1fbdf9b1d1eb94ceaa6d3b556 | Python | 3,203 | 149 | #!/usr/bin/env python
#
# Copyright (c) 2017 10X Genomics, Inc. All rights reserved.
#
from __future__ import annotations
import math
PIPELINE_AGGR = "aggr"
PIPELINE_COUNT = "count"
PIPELINE_REANALYZE = "reanalyze"
PIPELINE_VDJ = "vdj"
PIPELINE_META_COUNT = "meta-count"
CELLRANGER_COMMAND_NAME = "Cell Ranger"
# TOD... |
179ce1f7048ed291c2212c3f31fc6cb6252ab74c21d8ce9e3a3a0533bbc6e94c | Python | 3,204 | 106 | #
# Copyright (c) 2023 10X Genomics, Inc. All rights reserved.
#
"""File meant to provide some functions used by others, without a dependency on websummary."""
from __future__ import annotations
from six import ensure_str
import cellranger.websummary.numeric_converters
from cellranger.analysis import jibes_constants... |
81ea9939e2186eecb5c6521ebbf289250ec741f50c1ead5e1efc5f9405881a2b | Python | 3,207 | 115 | import sys
from pathlib import Path
import click
import click_log
from ..._cli.utils import OrderedClickGroup, catch_exception, logger
from ..._steinbock import SteinbockException
from ..._steinbock import logger as steinbock_logger
from .. import cellprofiler
@click.group(
name="cellprofiler",
cls=OrderedC... |
4aabfb177742ec58558ad5f4f0a31d401475a2737165e7210503b9170dbfb576 | Python | 3,208 | 94 | import json
import pathlib
from importlib import resources
import click
import pytest
from click.testing import CliRunner
from gufe.tokenization import JSON_HANDLER
from openfecli.commands.quickrun import quickrun
@pytest.fixture
def json_file():
with resources.as_file(resources.files("openfecli.tests.data")) a... |
7fe52042fbdce31194b14574809c69b79d5a5b67e78918f8b6a0c2c9eb809a42 | Python | 3,210 | 96 | """
If you use this code, please cite one of the SynthSeg papers:
https://github.com/BBillot/SynthSeg/blob/master/bibtex.bib
Copyright 2020 Benjamin Billot
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 Lice... |
92c022de5e2fea565bb886f03f31628be65c2eb48b5b050c49b901ebeda1c20d | Python | 3,216 | 113 | """This integration test is designed to ensure that the chemprop model can _overfit_ the training
data. A small enough dataset should be memorizable by even a moderately sized model, so this test
should generally pass."""
from lightning import pytorch as pl
import pytest
import torch
from torch.utils.data import DataL... |
1ee7ffbb12a430d791a8f836d0c432b364b512c80bf303f674e63d267bc633cb | Python | 3,220 | 90 | from detectron2.config import LazyCall as L
from detectron2.layers import ShapeSpec
from detectron2.modeling.meta_arch import GeneralizedRCNN
from detectron2.modeling.anchor_generator import DefaultAnchorGenerator
from detectron2.modeling.backbone import BasicStem, BottleneckBlock, ResNet
from detectron2.modeling.box_r... |
d60d83fe7e2946280d08d036fb71018dabb4297b9a3eb02995dc441d9aabbcd5 | Python | 3,222 | 106 | """NET probe diagram with unit templates colored by stim-evoked firing rate."""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
import json
from matplot... |
0bd33ded22e5456843b8c07f1c2059205a98aa7e463cfc808ebcdcf6a7bf9f76 | Python | 3,223 | 60 | from itertools import cycle
from typing import List, Tuple, Callable, Optional
from PIL import Image as pil_image, ImageDraw as pil_img_draw, ImageFont
from more_itertools.recipes import grouper
from taming.data.image_transforms import convert_pil_to_tensor
from torch import LongTensor, Tensor
from taming.data.helper... |
edaf10dea0c95e9b135f081668daf92a745c60b18ce3db9a28341a002c141ae3 | Python | 3,224 | 116 | import os
import logging
import psycopg2
from datetime import datetime
class PSQLCursorWrapper:
"""Wrapper class for the PSQL cursor"""
def __init__(self, cur):
self.cur = cur
def execute(self, query, vars=None, verbose=True):
if verbose:
logging.info('<< PSQL :: BEGIN >>\n{}... |
81d04fec4de61b8a036d22108f8f293fe58a5e606e1514e4d0619909b25b97ac | Python | 3,228 | 118 | import os
import logging
import psycopg2
from datetime import datetime
class PSQLCursorWrapper:
"""Wrapper class for the PSQL cursor"""
def __init__(self, cur):
self.cur = cur
def execute(self, query, vars=None, verbose=True):
if verbose:
logging.info('<< PSQL :: BEGIN >>\n{}... |
19f800c03fa86e3a0623b02064e76d836eaca52372ee5127af9febe4799fcf68 | Python | 3,233 | 80 | ############################################################################
# Copyright (c) 2022-2026 University of Helsinki
# # All Rights Reserved
# See file LICENSE for details.
############################################################################
"""Unit tests for intron-graph terminal-vertex refinement
(`... |
86e1653443f66a797cca19851d6628210f550ada30d422a83771378870114b5e | Python | 3,233 | 112 | import numpy as np
from stabl import data
from stabl.multi_omic_pipelines import multi_omic_stabl
from sklearn.model_selection import RepeatedStratifiedKFold, GroupShuffleSplit, GridSearchCV
from sklearn.linear_model import LogisticRegression
from stabl.stabl import Stabl
from sklearn.pipeline import Pipeline
from skle... |
72d631e39f21ec9acfb660b4d52fc3ab7174be27eec70fd962b2bd78619fc68a | Python | 3,235 | 72 | from typing import Dict, Tuple
from brian2 import NeuronGroup
from ._base import BaseLayer
from ..groups import GroupFactory
from ...definitions import NeuronClass, SynapseClass, Projection
__all__ = ["SpatialLayer"]
_PROJECTION_SYNCLS_MAP = {
Projection.FF: SynapseClass.PLASTIC,
Projection.E2I: SynapseCl... |
9c718a0652e870e1456aaf8764676ae66820f204be6238919a7fd4bd3ff86d8e | Python | 3,237 | 118 | import os
import logging
import psycopg2
from datetime import datetime
class PSQLCursorWrapper:
"""Wrapper class for the PSQL cursor"""
def __init__(self, cur):
self.cur = cur
def execute(self, query, vars=None, verbose=True):
if verbose:
logging.info('<< PSQL :: BEGIN >>\n{}... |
4ba1dd182658b3cb8a4bef3efa022052938fcb6a7723e441978f6dad4fc04a51 | Python | 3,238 | 69 | import numpy as np
import torch
import torch.multiprocessing
torch.multiprocessing.set_sharing_strategy('file_system')
from torchvision import transforms
from . import vision_transformer as vits
from . import vision_transformer4k as vits4k
def get_vit256(pretrained_weights=None, arch='vit_small', device=torch.device('... |
3af417afa7ffb4001542b24c1758f4596b73b5a9b1e4d296d3cca229a78587b0 | Python | 3,239 | 95 | import os
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import anndata as ad
import scanpy as sc
from scipy.io import mmwrite, mmread
import seaborn as sns
import scipy
np.random.seed(42)
# load anndata
dir_path = "/home/nomura/Proj/mmvelo/experiments/SHARE-seq_hf/2023-08-0... |
2eed1db418596d6d7dc0301f420c5466c443559ecda918c76165c260d95536ac | Python | 3,241 | 84 | from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Dict, List, Tuple, Type
import numpy as np
import numpy.typing as npt
from scipy.spatial import KDTree
from brian2 import NeuronGroup, Synapses
from ....logger import get_logger
__all__ = ["BaseConnector", "connector_registry"... |
0f934cf5654156045913fdd2ba6b02db002d55dc35b0d16495f776d7873c55c5 | Python | 3,249 | 97 | from pathlib import Path
import numpy as np
import pytest
from steinbock import io
from steinbock.preprocessing import imc
@pytest.mark.skipif(not imc.imc_available, reason="IMC is not available")
class TestIMCPreprocessing:
def test_list_mcd_files(self, imc_test_data_steinbock_path: Path):
imc.list_mcd... |
64c89b29ff1547c70c88f99d28d32d6a715c1b78a7c4bcc50770d1766936815a | Python | 3,251 | 97 | import pathlib
import click
from openfecli import OFECommandPlugin
from openfecli.parameters import MOL_DIR, NCORES, OUTPUT_FILE_AND_EXT, OVERWRITE, YAML_OPTIONS
YAML_HELP = """
Path to a YAML file specifying the method to use to charge the molecules
(any atom mapper or network generation options will be ignored).
... |
692a88d2278b45c9987b719bf1b2a162058f79183758b129413d8930179091b3 | Python | 3,252 | 90 | #
# Copyright (c) 2019 10X Genomics, Inc. All rights reserved.
#
"""Functions and classes for loading and manipulating images."""
from __future__ import annotations
import base64
import io
import os
import tempfile
from PIL import Image, ImageOps
def _base64_encode_image(filename, fmt="jpeg"):
"""Opens a file... |
834c1dfdfec07320579af3cbf758ba80a337ecadf298fe3ecf84382f0977e2b3 | Python | 3,252 | 79 | #!/usr/bin/env python3
#
############################################################################
# Copyright (c) 2022-2026 University of Helsinki
# Copyright (c) 2020-2022 Saint Petersburg State University
# # All Rights Reserved
# See file LICENSE for details.
#####################################################... |
9112bfc78612a9c410c77c1c5740976c6377541d18cac83fd89a9e77910e52fb | Python | 3,252 | 132 | # electrodes are in the same order they appear in the data
channels = [
"Fp1", # ,,0.5,µV
"Fp2", # ,,0.5,µV
"F7", # ,,0.5,µV
"F3", # ,,0.5,µV
"Fz", # ,,0.5,µV
"F4", # ,,0.5,µV
"F8", # ,,0.5,µV
"FC5", # ,,0.5,µV
"FC1", # ,,0.5,µV
"FC2", # ,,0.5,µV
"FC6", # ,,0.5,µV... |
31421cfcc6dc64102169636078a71a9460ade8bae86c6878901738c9710519b1 | Python | 3,253 | 109 | import ast
from lightning import pytorch as pl
import numpy as np
import pandas as pd
import pytest
from chemprop import data, models, nn
columns = ["smiles", "mol_y1", "mol_y2", "atom_y1", "atom_y2", "bond_y1", "bond_y2", "weight"]
@pytest.fixture
def mab_data_dir(data_dir):
return data_dir / "mol_atom_bond"
... |
5a4da1c707c4c7ab11d5e4ede8aeae7d1124df880cf8312ddadd612e5156aa17 | Python | 3,256 | 102 | import logging
from pathlib import Path
import pickle
from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple
import numpy as np
from brian2 import defaultclock, seed, start_scope, Network, Synapses
from brian2.units import msecond
from ..layer import BaseLayer
from ..._base import BaseNetwork
from ...... |
30dba428473fe3e76164df5a1d12b716041fd1a23db2d843452b5adb1f067256 | Python | 3,262 | 99 | import statistics
import numpy as np
from .utils import find_nearest
from scipy.spatial.distance import cdist
def prepare_data_with_dt(spike_time_lis, X, T,
dt, window_len=None):
"""
Create a set of S, X, T with a fixed time bin width, with a sliding window.
spike_time_lis : list... |
bd6849a3f5c602428c808a9d802ce14f3c43454ae613f409b43bb2050d13803f | Python | 3,262 | 99 |
############################################################################
# Copyright (c) 2022-2026 University of Helsinki
# All Rights Reserved
# See file LICENSE for details.
############################################################################
import json
import sys
import os
def simplify_and_sum_trans... |
c9a2e3412372d2e527fb04a7b05e72be4dc51799abd7003a39eae33bfb6b7b60 | Python | 3,262 | 100 | import torch
import torch.nn as nn
class ResidualBlock(nn.Module):
def __init__(self, in_channels, out_channels, stride=1, downsample=None):
super(ResidualBlock, self).__init__()
self.conv1 = nn.Sequential(
nn.Conv1d(
in_channels, out_channels, kernel_size=3, stride=stri... |
d31f93f82b889cb45ade32cc4541d40712381be92f6587d932bdb78d721ca6d9 | Python | 3,264 | 112 | """
EOD analysis
## Functions
- `eod_times()`: times of EOD zero crossings.
- `detect_eods()`: detect EOD times.
- `plot_eod_interval_hist()`: plot inter-EOD-interval histogram.
"""
import numpy as np
from scipy.signal import welch, butter, sosfiltfilt
from thunderlab.eventdetection import detect_peaks, std_thresh... |
d08f1638b96e39b4649f9bab6b5add6b6687dc5c8e99382705eddb1d19bbc16c | Python | 3,265 | 95 | #!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
import argparse
import json
import numpy as np
import os
from collections import defaultdict
import cv2
import tqdm
from detectron2.data import DatasetCatalog, MetadataCatalog
from detectron2.structures import Boxes, BoxMode, Instances
from dete... |
c48b27489bc8a3e46d07eb3b516e917f3af595e8b8bfddf20c5f6da8341c766a | Python | 3,271 | 69 | from batchgenerators.utilities.file_and_folder_operations import join, load_json, isfile
from nnunetv2.utilities.dataset_name_id_conversion import maybe_convert_to_dataset_name
from nnunetv2.paths import nnUNet_results
from nnunetv2.utilities.file_path_utilities import get_output_folder
if __name__ == '__main__':
... |
9ac6655dcc40ae739edb30d08e12fb3a7ecc6e507b50a08561c248469564b746 | Python | 3,272 | 85 | # This code is part of OpenFE and is licensed under the MIT license.
# For details, see https://github.com/OpenFreeEnergy/openfe
import MDAnalysis as mda
import pytest
from openfe.protocols.restraint_utils.geometry.harmonic import (
DistanceRestraintGeometry,
get_distance_restraint,
get_molecule_centers_r... |
bafa26af2935673e1742aa50acf8371fd9e08240fc7ff6b366fcb57f160e5e78 | Python | 3,273 | 58 | import shutil
from typing import Union, List, Tuple
from batchgenerators.utilities.file_and_folder_operations import load_json, join, isdir, maybe_mkdir_p, subfiles, isfile
from nnunetv2.configuration import default_num_processes
from nnunetv2.evaluation.evaluate_predictions import compute_metrics_on_folder
from nnun... |
e792072d98c2b97a0cf0f2099d22f4104afa32e34c731e7a9696bed086f78614 | Python | 3,273 | 71 | # Copyright (c) Facebook, Inc. and its affiliates.
import numpy as np
import unittest
from detectron2.data.transforms.transform import RotationTransform
class TestRotationTransform(unittest.TestCase):
def assertEqualsArrays(self, a1, a2):
self.assertTrue(np.allclose(a1, a2))
def randomData(self, h=5... |
654355d9c1d3a9420dd3b36f39a1ec4a1f0f61334109aa2162d9d8e8acd3d3b7 | Python | 3,274 | 92 | import os
import numpy as np
import PIL
from PIL import Image
from torch.utils.data import Dataset
from torchvision import transforms
class LSUNBase(Dataset):
def __init__(self,
txt_file,
data_root,
size=None,
interpolation="bicubic",
... |
98806bdefc9d1a19e9cd594fec18447f89967c51c8586095cb5e9814e048f135 | Python | 3,276 | 121 | ############################################################################
# Copyright (c) 2023-2026 University of Helsinki
# # All Rights Reserved
# See file LICENSE for details.
############################################################################
"""
Barcode calling for single-cell and spatial transcriptom... |
8cab974f2cf9dbd62ba724327248b8deebc11d86b0e14be20bc1e9dbcff1c49b | Python | 3,279 | 101 | # This code is part of OpenFE and is licensed under the MIT license.
# For details, see https://github.com/OpenFreeEnergy/openfe
"""
Restraint Geometry classes
TODO
----
* Add relevant duecredit entries.
"""
from typing import Optional
import MDAnalysis as mda
from rdkit import Chem
from .base import HostGuestRestr... |
ac887b6aa9fd77e99df84026e85d1488dfd2acff857bec07129c7a1a6e034a67 | Python | 3,280 | 105 | # This code is part of OpenFE and is licensed under the MIT license.
# For details, see https://github.com/OpenFreeEnergy/openfe
import click
from openfecli import OFECommandPlugin
from openfecli.parameters import MAPPER, MOL, OUTPUT_FILE_AND_EXT
def allow_two_molecules(ctx, param, value):
"""click callback to ... |
a7f6c8f32c9cfcbc7568b8a6364de537e80895aa347f1403d33424376ce64279 | Python | 3,281 | 116 | # This code is part of OpenFE and is licensed under the MIT license.
# For details, see https://github.com/OpenFreeEnergy/openfe
import json
import gufe
import pytest
from gufe.tests.test_tokenization import GufeTokenizableTestsMixin
import openfe
from openfe.protocols import openmm_afe
@pytest.fixture
def protocol... |
bf59c656be093c8bed7842489c1a69a7368a8548e09a45a07b486bd45b2be932 | Python | 3,283 | 115 | import numpy as np
import pytest
from rdkit import Chem
from chemprop.data.molgraph import MolGraph
from chemprop.featurizers.atom import MultiHotAtomFeaturizer
from chemprop.featurizers.molgraph import SimpleMoleculeMolGraphFeaturizer
@pytest.fixture(params=[0, 10, 100])
def extra(request):
return request.param... |
d22c4cd22a509c4e054da91b8e457a988d8f66382e16c2701d6b0420c79b4b3a | Python | 3,287 | 93 | """Tests for proxy lambda correspondence after Procrustes alignment (#94)."""
import numpy as np
from brainspace.gradient import GradientMaps
from brainspace.gradient.alignment import (
procrustes, procrustes_alignment, aligned_lambdas, ProcrustesAlignment,
)
def _psd(n, seed):
rs = np.random.RandomState(se... |
fdd1a4a86dc16a64df9ab5445f5a0d41914fe8e2ff6ee480380791b1e31de0ec | Python | 3,287 | 117 | # Generated by h2py from glu.h
from pymol.opengl.gl.glconst import *
# Included from GL/gl.h
GLU_VERSION_1_1 = 1
GLU_VERSION_1_2 = 1
GLU_INVALID_ENUM = 100900
GLU_INVALID_VALUE = 100901
GLU_OUT_OF_MEMORY = 100902
GLU_VERSION = 100800
GLU_EXTENSIONS = 100801
GLU_SMOOTH = 100000
GLU_FLAT = 100001
GLU_NONE =... |
e85428684e94512e52066d904d2aef00ce318521daf30b953c1a3dfa440bcabb | Python | 3,288 | 77 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import torch
from detectron2.layers import cat
def get_point_coords_from_point_annotation(instances):
"""
Load point coords and their corresponding labels from point annotation.
Args:
instances (list[Instances]): A list of N ... |
26a672d4db5bdab8c98e2622e3a859cb18462a81dba49c5bb5a0cb7aede81e40 | Python | 3,291 | 146 |
import pandas as pd
import numpy as np
import joblib
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split, RepeatedKFold, cross_val_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import MinMaxScaler
from sklearn.ensemble import RandomForest... |
59331826dbc4481897879b0166c0b39207536ddc0fabf21b5edb3d402ee2e7ab | Python | 3,295 | 112 | """runner for global performance benchmarks."""
import gc
import os
import pickle
import sys
import time
# making sure we use this version of mesa and not one
# also installed in site_packages or so.
sys.path.insert(0, os.path.abspath(".."))
from configurations import configurations
# Generic function to initializ... |
227e7bf93aeb3c48ec36b2aca3bd1d95a2e17e432ffd7e8795c6fc08d0aa52df | Python | 3,296 | 123 | # Script that makes use of more advanced feature selection techniques
# by Alberto Tonda, 2017
import numpy as np
import os
import sys
import pandas as pd
from classifiersMulti import *
from pandas import read_csv
directory="data"
numberOfFolds=10
def fakeBootStrapper():
# create folder
folderName ="./best/"
i... |
601f73a5bd7d10f56a395424abe9f702ad76661224567b6a88c5eaa429827ee5 | Python | 3,296 | 135 | # This script is part of navis (http://www.github.com/navis-org/navis).
# Copyright (C) 2018 Philipp Schlegel
#
# 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... |
20ed9202f4e61374aa994bd3ed0f076bebaff53f6392ede570a8531af294d3ec | Python | 3,300 | 110 | #!/usr/bin/env python
#
# Copyright (c) 2017 10X Genomics, Inc. All rights reserved.
#
from __future__ import annotations
import json
from typing import TYPE_CHECKING
import martian
import cellranger.webshim.common as cr_webshim
import cellranger.websummary.vdj as vdj_web
from cellranger.analysis.singlegenome impor... |
af0e072af92909d0e92c3c1d90ef4b510cbf589525071a6cb6aabd9876616e51 | Python | 3,300 | 79 | import os.path as op
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
import numpy as np
def plot_cmap(cm, norm, img_fn=None):
fig = plt.figure()
ax = fig.add_axes([0.05, 0.2, 0.9, 0.1])
cb = mpl.colorbar.ColorbarBase(ax, cmap=cm, norm=norm,
... |
ef8d083be7a56cb15b8aeb038323e458eb2613011c6facee0a056533dda78359 | Python | 3,300 | 108 |
#%% Imports
# Imports from the library
from micorr.simulation import simulations, testing, plotting, transformations
from micorr.estimators import mi_estimators, corr_est
# More general imports
import numpy as np
from functools import partial
#%% Initial parameters
# Dictionary with the estimators to be tested
est... |
78efa39e675f9ca7dd38b9ff1caf7f7d182b951f0a64d1c36afe0b94fc706395 | Python | 3,301 | 103 | #!/usr/bin/env python
#
# Copyright (c) 2020 10X Genomics, Inc. All rights reserved.
#
"""Constants used for the targeting pipeline."""
from __future__ import annotations
from typing import NamedTuple
# two types of targeted assays
TARGETING_METHOD_TL = "templated_ligation"
TARGETING_METHOD_TL_FILE_NAME = "probe se... |
af7640e240ba527c23592e62674c9bfa24cda447f7446b85161e6602af42d11d | Python | 3,301 | 78 | import sys
from pathlib import Path
if len(sys.argv)!=2: sys.exit("REQUIRED: pandas, pathlib; tested with Python 3.8.5\n","USAGE: python RawReadMZMS1.py <path to folder containing profile.intensity0.charge0.MS.txt file(s) like \"Z:/RawRead/\" >")
pathFiles = Path(sys.argv[1])
pathFiles = Path("L:/promec/Animesh/... |
aa1f830b5b23236613f269a779466d35f6d4632b44b605ef69f9409cabe539d6 | Python | 3,306 | 90 | """
Module: encoder.py
Description:
- Implements one-hot substitution encoding and placeholders for
DNA-BERT2 / RNA-FM encoding.
"""
import numpy as np
from config import FEATURE_DIM, ENCODING_DIMS
# Base mapping
BASE_VOCAB = ['A', 'T', 'G', 'C']
BASE_TO_IDX = {b: i for i, b in enumerate(BASE_VOCAB)}
def subst... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.