sha256 stringlengths 64 64 | language stringclasses 27
values | size int32 1 491k | lines int32 1 21.8k | content stringlengths 1 200k |
|---|---|---|---|---|
63baccdbd9ec472e2236e5e3f12513053fdb6920a6412659b6bb28ae926733ed | Python | 515 | 16 | """Legacy (v2) response model.
Superseded by responses_v3 for the main feature table (raw_df). Retained because
pop_coupling and the per-unit QC figures in stage4_postprocess still build on it.
"""
from .session_responses_v2 import SessionResponses
from .unit_response_v2 import UnitResponse
from .stim_condition_respon... |
f52f3a01b6cf324dbb2d366f41a87e6b8239c53b64d9ca633ad38b06d1562039 | Python | 515 | 20 | #
# Copyright (c) 2024 10X Genomics, Inc. All rights reserved.
#
"""Demux cas track name."""
__MRO__ = """
stage DEMUX_CLOUPE_TRACK_NAME(
in string cas_track_name_from_user,
in string cas_track_name_from_ppln,
out string cas_track_name,
src py "stages/cas_cell_typing/demux_cloupe_track_name",
)
"... |
f5d11a38ff9724ef52c53b7507b815336159aa7899b99e364f531efbb774bc94 | Python | 515 | 30 | # type: ignore
__submodules__ = [
"bidsargs",
"cli_config",
"component_edit",
"pybidsdb",
"validator",
"snakemake",
"version",
]
# <AUTOGEN_INIT>
import lazy_loader
__getattr__, __dir__, __all__ = lazy_loader.attach_stub(__name__, __file__)
__all__ = [
"BidsArgs",
"BidsValidator",... |
290980ec3e057d5dc7556c39601482bc9d3fd55645219a0cc6b1fe32ed892121 | Python | 516 | 12 | import torch
from torch.optim.lr_scheduler import CosineAnnealingLR
from nnunetv2.training.nnUNetTrainer.nnUNetTrainer import nnUNetTrainer
class nnUNetTrainerCosAnneal(nnUNetTrainer):
def configure_optimizers(self):
optimizer = torch.optim.SGD(self.network.parameters(), self.initial_lr, weight_decay=sel... |
ad87f9a62e7dd9446d000e60bae60788c103ec523d45d00cefb2d637b7479c9b | Python | 519 | 13 | # @BAR bar
# @float a
# @float b
# This script distributed through the BAR update site[1] exemplifies how Ops[1]
# can be added outside the core imagej-ops project. In this case, it exemplifies
# how an existing function provided by a BAR lib[2] can be converted to an Op.
# The full tutorial by Mark Hiner is available... |
36ea1e306002ee737a34e533d26922ded78284829510068283d24307165aee26 | Python | 523 | 17 | import re
from typing import Iterable
def _get_uid(names: Iterable[str], startswith: str) -> str:
def _extract_number(s):
match = re.search(r'\d+', s)
if match:
return int(match.group())
else:
return 0
pattern = re.compile(rf"^{startswith}(_\d+)?$")
matches ... |
d937d5f32355fe6664afc046a760a2bff4d94de1a718b4c29bcc0d35e6d005f6 | Python | 523 | 9 | # Copyright (c) Facebook, Inc. and its affiliates.
from .coco import load_coco_json, load_sem_seg, register_coco_instances, convert_to_coco_json
from .coco_panoptic import register_coco_panoptic, register_coco_panoptic_separated
from .lvis import load_lvis_json, register_lvis_instances, get_lvis_instances_meta
from .pa... |
c62f2854479a77aede53d65d55acdec2348f8e392bd136d4606c708bb86314a7 | Python | 526 | 27 | """Utility functions for I/O and model management."""
from nfml.utils.io import (
create_writer,
filter_by_smarts,
load_model_bundle,
load_params,
load_pickle,
remove_dummy_atoms,
resolve_model_class,
save_model,
save_model_bundle,
save_pickle,
)
__all__ = [
"create_writer"... |
50c338b512a11aae7d0d3330f106904ee6df4a7d3376c356a6195bf35454e7a6 | Python | 528 | 22 | import warnings
import os
import torch
from lightning.pytorch.cli import LightningCLI
from loguru import logger
warnings.filterwarnings("ignore")
def main():
"""
Run with: python -m stoic_train.train fit --config configs/config_sap.yaml
Or in sbatch: srun python -m stoic_train.train fit --config configs... |
ffebe5e3648b1fd53dae42d2bde3aec5143e97dbad410c8cddcc501614e8c476 | Python | 529 | 17 | # Copyright (c) Facebook, Inc. and its affiliates.
# pyre-unsafe
from detectron2.data import MetadataCatalog
from detectron2.utils.file_io import PathManager
from densepose import DensePoseTransformData
def load_for_dataset(dataset_name):
path = MetadataCatalog.get(dataset_name).densepose_transform_src
dens... |
5d87cd728661d8192b8f753855842dba7228d2bd7b37f73e250f3ffbb82a545c | Python | 531 | 14 | # Copyright (c) 2019 10x Genomics, Inc. All rights reserved.
"""Prevent pandas frm using eval when subsetting data frames.
We ran into a problem with a bug in glibc and haswell processors that causes
a lock in some situations. We first found it in bwa and fixed it by linking to
jmalloc. But now it is turning up in pan... |
f90319b9a4c5f655dc2419afbec25e501d5568bdc652f05f20193cb848e5c1b4 | Python | 531 | 12 | #https://medium.com/coding-nexus/why-i-stopped-using-pandas-describe-method-two-libraries-that-do-it-better-e2890c2c24d1
from skimpy import skim
import polars as pl
import polars.selectors as cs
import sys
fileName=sys.argv[1]
with open(fileName, 'r') as file: row_count = sum(1 for line in file)
print(f"Number of rows:... |
95a38c4b3744de2117aa1c7fadba4186c8f1f3f5d798d006bb4e91cc3515f8b5 | Python | 532 | 17 | import nibabel as nib
import numpy as np
warp2d = nib.load(snakemake.input.warp2d)
unfold_phys_coords_nib = nib.load(snakemake.input.unfold_phys_coords_nii)
IOdim = unfold_phys_coords_nib.get_fdata().shape[2]
field = warp2d.get_fdata()
shp = np.array(field.shape)
field_z = np.concatenate((field, np.zeros((np.append(... |
5c87061247eefcd691058e2c58f7617ad50018caae4b3e1fbc4242957507ac97 | Python | 537 | 18 | # -*- coding: utf-8 -*-
# Copyright (c) Facebook, Inc. and its affiliates.
from dataclasses import dataclass
from typing import Optional
@dataclass
class ShapeSpec:
"""
A simple structure that contains basic shape specification about a tensor.
It is often used as the auxiliary inputs/outputs of models,
... |
01cb1f2e8061a863939584d91488eb0d9997ba93ef9eb2eff7eced89dfa57864 | Python | 540 | 23 | import numpy as np
from scipy.stats import pearsonr
def abs_correlation(signal1, signal2):
'''
Calculating absolute value of Pearson correlation between two signals.
Parameters
----------
signal1: np.ndarray
The first signal to compare.
signal2: np.ndarray
The secon... |
84b3832ef8f33bda6a54f06908d62dc353c10d972155b10ec9db09e61eb71e11 | Python | 542 | 19 | try:
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtWidgets import QMainWindow
except ImportError:
MainWindow = None
else:
class MainWindow(QMainWindow):
"""Subclass of QMainWindow to capture closing event."""
signal_close = pyqtSignal()
def __init__(self, parent=None):
... |
b59a9b71a328b9ab09fcfd2db4903b6145130be6d2d8ded5cefa3c2fbc05e83b | Python | 543 | 27 | import torch
def softmax_helper_dim0(x: torch.Tensor) -> torch.Tensor:
return torch.softmax(x, 0)
def softmax_helper_dim1(x: torch.Tensor) -> torch.Tensor:
return torch.softmax(x, 1)
def empty_cache(device: torch.device):
if device.type == 'cuda':
torch.cuda.empty_cache()
elif device.type ... |
fab37ec9a665d4679d53c60415e514dc819c72ed96db2b17247b7af1cde6dad3 | Python | 543 | 16 | # Copyright (c) 2019 10X Genomics, Inc. All rights reserved.
ESSENTIAL_CRISPR_FILES = [
"cells_per_protospacer.json",
"protospacer_calls_summary.csv",
"protospacer_umi_thresholds.json",
]
CRISPR_ANALYSIS_FILE_NAMES = [
"feature_reference.csv",
"protospacer_calls_summary.csv",
"protospacer_calls_... |
c1ec160d901b9870bf1bcf9547bcc60a85ecb18f20ff998cbe1adc2c2f8e57e6 | Python | 544 | 20 | # This code is part of OpenFE and is licensed under the MIT license.
# For details, see https://github.com/OpenFreeEnergy/openfe
from .atom_mapping import (
KartografAtomMapper,
LigandAtomMapper,
LigandAtomMapping,
LomapAtomMapper,
PersesAtomMapper,
lomap_scorers,
perses_scorers,
)
# TODO... |
422c1036f961f5997886865769620fad987cef3bd85b51afb9e2beb97d965330 | Python | 548 | 23 | """
Module: data_class.py
Description:
- Defines a PyTorch Dataset for mismatch-based substrate data.
"""
import torch
from torch.utils.data import Dataset
class RandomMismatchDataset(Dataset):
"""
Dataset wrapping pairs of encoded sequences and continuous labels.
"""
def __init__(self, X, y):
... |
4c38bd93d55a8774127d8e961f3410e1e183ed9debeba297e80613a7cfca384e | Python | 548 | 14 | from rCPGswCPG.protocols.protocols import *
def construct_protocol(model, name, params):
if name == "Protocol_noSI":
protocol = Protocol_noSI(model, **params)
elif name == "Protocol_longSI":
protocol = Protocol_longSI(model, **params)
elif name == "Protocol_shortSI":
protocol = Prot... |
c1707ca5818268774c502fcd5cf69c636161a462da74a98412fd00782ea64abe | Python | 548 | 24 | """
This file defines the macros for the mkdocs site.
"""
import navis
# Some variables
# Depth from the
DEPTH = None
def define_env(env):
@env.macro
def autosummary(func):
"""Return first line of dosctring"""
try:
f = navis
for name in func.split('.'):
... |
adee2f5c829b1cadefac807ac1ceb243cb19649a2ce23ab301d0ad27e0731697 | Python | 551 | 16 | #!mamba create -n pycaret -c rapidsai-nightly -c nvidia -c conda-forge cuml=22.08 python=3.8 cudatoolkit=11.5
#!mamba activate pycaret
#!pip install --pre pycaret
#!mamba activate pycaret
from pycaret.datasets import get_data
data = get_data('juice')
from pycaret.classification import *
s = setup(data, target = 'Purcha... |
3e33723fe60d7921687c590c88e42e4bf3eb3630b1eda7e1c06bcbe27986fb2e | Python | 552 | 25 | import pandas as pd
## Load data
expr = pd.read_csv("ExprData_filtered_ordered.csv")
## Your gene list
genes = [
"ENSG00000104695",
"ENSG00000118520",
"ENSG00000127884",
"ENSG00000160712",
"ENSG00000180340",
"ENSG00000184557",
"ENSG00000211697",
"ENSG00000211699"
]
## Filter rows
filt... |
af78127c741477423ba2fa376230bd3d5f77c2d0d9f191266be6c4a6cf93c168 | Python | 559 | 15 | from .base import (load_conte69, load_mask, load_group_fc, load_group_mpc,
load_parcellation, load_gradient, load_marker, load_fsa5,
load_confounds_preprocessing,
fetch_timeseries_preprocessing)
__all__ = ['load_conte69',
'load_fsa5',
'load... |
6fbed470cb3a9010c1ea81aa01ed0332b2f26fe887fc9a2155e074b99c0e3057 | Python | 561 | 20 | # -*- coding: utf-8 -*-
"""Fixtures for all abagen tests."""
import shutil
import pytest
def pytest_configure(config):
"""Add markers for tests."""
config.addinivalue_line(
"markers", "workbench: mark test to run with Connectome Workbench"
)
def pytest_runtest_setup(item):
"""Skip tests th... |
22e346acddd1318a2e17ab40200be395d2781ce097616cd576cbec383ed97b4f | Python | 564 | 26 | import numpy as np
from torch.utils import data
def InfiniteSampler(n):
# i = 0
i = n - 1
order = np.random.permutation(n)
while True:
yield order[i]
i += 1
if i >= n:
np.random.seed()
order = np.random.permutation(n)
i = 0
class InfiniteSa... |
9d06fddcef7f9d5b69f059e88c0f7e0030d08a9d507069545ce1052ec69728b6 | Python | 564 | 25 | import pandas as pd
## Load data
expr = pd.read_csv("GSE226260_AdditionalSamples.rawCounts.csv")
## Your gene list
genes = [
"ENSG00000104695",
"ENSG00000118520",
"ENSG00000127884",
"ENSG00000160712",
"ENSG00000180340",
"ENSG00000184557",
"ENSG00000211697",
"ENSG00000211699"
]
## Filt... |
51e9e58b7871abe5058e0df85d32c04a461663500f1b6f5c27b42a88db9f33ab | Python | 566 | 24 | #!/usr/bin/env python3
import os
from snakebids.app import SnakeBidsApp
from snakebids.cli import add_dynamic_args
def get_parser():
"""Exposes parser for sphinx doc generation, cwd is the docs dir"""
app = SnakeBidsApp("../hippunfold")
add_dynamic_args(app.parser, app.config["parse_args"], app.config["p... |
b3b7e13fdab87f2228ef4faf1f414557de52080f947480d7823e3a000fa64ad7 | Python | 568 | 15 | from tristan_pipeline.io.params import *
from tristan_pipeline.utils.loading_utils import *
from tristan_pipeline.utils.preproc_utils import *
from nilearn.image import load_img, index_img
import nibabel as nib
import json
for subj in subjects:
for ses in sessions:
RFUNC_PATH, RFMAP_PATH = load_rawdata(RA... |
fceb6fec5428372c3d9f95175ab06acb8ccf676983340820171a8fb2ebc8fc39 | Python | 570 | 14 | """Shared substrate for the low-, high-, and binding-neuron reuse analyses.
Builds and persists the canonical HFB annotation tables (:mod:`.api`), exposes the
shared constants (:mod:`.constants`), and provides the role co-membership /
role-switching matrix (:mod:`.comembership`), the binding-neuron ambiguity /
resolut... |
7c70c5e3ae361fd19ee44f9d59e4ac7f445c9d8d9769f7258e3d98bc8927b28e | Python | 572 | 18 | import torch.nn as nn
class DropoutPredictor(nn.Module):
def __init__(self,
latent_dim: int,
hidden_dim: int = 128,
dropout: float = 0.2,
**kwargs):
super(DropoutPredictor, self).__init__()
self.input_layer = nn.Linear(latent_dim,... |
b73d4087593fb4314feb35ffd9486730f9ed02b3ef32acf723879fea2e20121e | Python | 574 | 22 | import click
from ..._cli.utils import OrderedClickGroup
from .cellprofiler import cellprofiler_cmd_group
from .intensities import intensities_cmd
from .neighbors import neighbors_cmd
from .regionprops import regionprops_cmd
@click.group(
name="measure",
cls=OrderedClickGroup,
help="Extract object data f... |
04386fc9d638e97d66f21d015e184c996ae65725c327d05191b291c77b3e4dc3 | Python | 577 | 20 | from setuptools import setup
setup(name='ldsc',
version='1.0',
description='LD Score Regression (LDSC)',
url='http://github.com/bulik/ldsc',
author='Brendan Bulik-Sullivan and Hilary Finucane',
author_email='',
license='GPLv3',
packages=['ldscore'],
scripts=['ldsc.py', '... |
05aba6054471e2832d36df5a39c8b990a5eeae6ec630eb8e757e15603d223670 | Python | 580 | 15 | # Copyright (c) Facebook, Inc. and its affiliates.
from .base_tracker import ( # noqa
BaseTracker,
build_tracker_head,
TRACKER_HEADS_REGISTRY,
)
from .bbox_iou_tracker import BBoxIOUTracker # noqa
from .hungarian_tracker import BaseHungarianTracker # noqa
from .iou_weighted_hungarian_bbox_iou_tracker imp... |
b7c72d09c8e649e893c86c212b4ef870025a452ca19bd2a8bb537580920f62b4 | Python | 581 | 28 | #@ImageJ ij
#@UIService ui
#@LogService log
#@ScriptService script
#@DisplayService display
#header
import bar
import sys
def main():
# Load template BAR lib (BARlib.py) (see 'BAR> Utilities>
# Install Multi-language libs...'). Exit if file is not
# available
sys.path.append(bar.Utils.getLibDir())
... |
f1b1487d2b3c4a1304d86660ffa6750d54eb42a5605fd373dbce7dbdea8c8d3c | Python | 584 | 23 | # Generated by Django 4.2 on 2024-12-25 16:30
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('abx_app', '0015_rename_current_dim_user_count_cond_and_more'),
]
operations = [
migrations.RenameField(
model_name='user',
... |
baca6daf9e12d0f05a1784ae1a24c15a06ba496a5b269711c02d69425494b71e | Python | 587 | 17 | import mne
import numpy as np
def project_wave(entry, stc_gen, verbose=False):
measured = entry.measured
forward = entry.forward_model
info = mne.io.read_info(measured, verbose=verbose)
fwd = mne.read_forward_solution(forward, verbose=verbose)
# Project into sensor space
nave = n... |
c1b3f050034f3bf3e8e56aad1d29c6c96c414231bca86972f03e0150113e10c4 | Python | 587 | 20 | # This code is part of OpenFE and is licensed under the MIT license.
# For details, see https://github.com/OpenFreeEnergy/openfe
from typing import TypeVar
import matplotlib.axes
import matplotlib.backend_bases
from rdkit import Chem
try:
from typing import TypeAlias
except ImportError:
from typing_extension... |
fa3df4f5e9779ee82c8e48bdc739698c6fd76fca47db519ae409baa7721ea097 | Python | 588 | 21 | import os
import numpy as np
import matplotlib
def configure_runtime(
cuda_visible_devices : str | None = None,
headless : bool | None = None,
numpy_precision : int = 6,
numpy_suppress : bool = True,
) -> None:
if cuda_visible_devices is not None:
os.... |
506448d89a02368163b0c618351d3a3f786ad2bfbd9bac3109e5d60f019185b9 | Python | 589 | 22 | from __future__ import annotations
from pathlib import Path
from typing import TYPE_CHECKING, TypeAlias, TypedDict
if TYPE_CHECKING:
from argparse import _ArgumentGroup
__all__ = ["ArgumentGroups", "SnakebidsConfig"]
ArgumentGroups: TypeAlias = "dict[str, _ArgumentGroup]"
class SnakebidsConfig(TypedDict):
... |
87e0037987bfa8d43743ff9ff69108b832e31d11dc1c327621616479a83fe9f9 | Python | 589 | 21 |
""" Convenient dataset splitting. """
__author__ = "Fabi Bongratz"
__email__ = "fabi.bongratz@gmail.com"
from data.cortex import CortexDataset
from data.abdomen import AbdomenCTDataset, AbdomenMRIDataset
from data.supported_datasets import (
CortexDatasets,
AbdomenCTDatasets,
AbdomenMRIDatasets,
)
# Map... |
537ec5fb37d42c440e35ac1635bb07328cc4bd6556489089ca15d3551b5aa7a7 | Python | 590 | 23 | """Visualization backends for Mesa space rendering.
This module provides different backend implementations for visualizing
Mesa agent-based model spaces and components.
Note:
These backends are used internally by the space renderer and are not intended for
direct use by end users. See `SpaceRenderer` for actu... |
b62df77b30c92e05b29e039a71043f49754d8bc60347e9e76f26bf70a5f75314 | Python | 590 | 17 | #install: pip install skimpy summarytools numpy pandas
#usage: python dataSum.py proteinGroups.txt "Intensity "
#blog: https://medium.com/coding-nexus/why-i-stopped-using-pandas-describe-method-two-libraries-that-do-it-better-e2890c2c24d1
from skimpy import skim
from summarytools import dfSummary
import numpy as np
imp... |
4cee2fedddeb50e4710d994007760e62749c3bc624f0ac9717fa4cc095370a98 | Python | 592 | 22 | import click
from ..._cli.utils import OrderedClickGroup
from .cellpose import cellpose_cli_available, cellpose_cmd
from .cellprofiler import cellprofiler_cmd_group
from .deepcell import deepcell_cli_available, deepcell_cmd
@click.group(
name="segment",
cls=OrderedClickGroup,
help="Perform image segmenta... |
ac28b640ba2136f0a11eb51f1ac15547df086fe6a1ba9c9797bfb747c0d5178f | Python | 596 | 26 | # -*- coding: utf-8 -*-
"""For testing neuromaps.utils functionality."""
import os
import pytest
from neuromaps import utils
def test_tmpname(tmp_path):
"""Test generating temporary filenames."""
out = utils.tmpname('.nii.gz', prefix='test', directory=tmp_path)
assert (isinstance(out, os.PathLike) and o... |
bb5f75b6ebebd4138f6ec7efc1f00f2700abe80ed00e055171f6ba03f886bb48 | Python | 597 | 16 | from typing import Any, Dict
import numpy as np
__all__ = ["assert_netstate_equal"]
def assert_netstate_equal(state1: Dict[str, Dict[str, Any]], state2: Dict[str, Dict[str, Any]]):
state_keys = state1.keys()
assert state2.keys() == state_keys, "state keys differ at network level"
for state_key in state_... |
fb4c0155cea4709fe74e80130cb8d8a8f48c5de05bc0228e03c3b28827fd9c08 | Python | 598 | 20 | # Copyright (c) Facebook, Inc. and its affiliates.
from .build import build_backbone, BACKBONE_REGISTRY # noqa F401 isort:skip
from .backbone import Backbone
from .fpn import FPN
from .regnet import RegNet
from .resnet import (
BasicStem,
ResNet,
ResNetBlockBase,
build_resnet_backbone,
make_stage,... |
4448babfba2044cad5388981fa513664be317514800155d43407034c5f6c335f | Python | 599 | 24 | # Copyright (c) Facebook, Inc. and its affiliates.
from .compat import downgrade_config, upgrade_config
from .config import CfgNode, get_cfg, global_cfg, set_global_cfg, configurable
from .instantiate import instantiate
from .lazy import LazyCall, LazyConfig
__all__ = [
"CfgNode",
"get_cfg",
"global_cfg",
... |
5747f4a5385b37786f5d7dcc703e21686ca7875f6fa2cedf989f3a53edd31450 | Python | 602 | 24 | import contextlib
import logging
@contextlib.contextmanager
def silence_root_logging():
"""Context manager to silence logging from root logging handlers.
a.k.a, "Why are you using basicConfig during import -- or in library
code at all?"
"""
root = logging.getLogger()
old_handlers = list(root.... |
aabb1f101e7151b613c41f90c1da071f4af987c6f66080009722197970e5518a | Python | 604 | 26 | from __future__ import annotations
import sys
from pathlib import Path
PROJECT_ROOT = Path(__file__).resolve().parents[1]
if str(PROJECT_ROOT) not in sys.path:
sys.path.insert(0, str(PROJECT_ROOT))
# Import torch before RDKit/Qt to keep the Windows DLL load order deterministic.
import src.utils.torch_preimport ... |
c556d52f5ed09340bc7a4c11a390067847f2ab7f733feb98721d58809c9fb376 | Python | 604 | 20 | from detectron2.config import LazyCall as L
from detectron2.layers import ShapeSpec
from detectron2.modeling import PanopticFPN
from detectron2.modeling.meta_arch.semantic_seg import SemSegFPNHead
from .mask_rcnn_fpn import model
model._target_ = PanopticFPN
model.sem_seg_head = L(SemSegFPNHead)(
input_shape={
... |
cd676cc10a3a755932798964f2174a53592336a8a0abbe00e465f202b6dc74e4 | Python | 604 | 27 | #!/usr/bin/env python3
#
# Copyright (c) 2017 10x Genomics, Inc. All rights reserved.
"""Parse RunInfo.xml to get flowcell."""
from __future__ import annotations
import sys
import xml.etree.ElementTree
def main(loc):
tree = xml.etree.ElementTree.parse(loc)
maxilen = 0
reads = tree.getroot().findall(".... |
d67973857de32cf35a8e4f4116b61f3abf34ab00099fc1963827e5479751c559 | Python | 604 | 21 | #
# Copyright (c) 2025 10X Genomics, Inc. All rights reserved.
#
"""Demultiplexing cell typing methods."""
from cellranger.cell_typing.common_cell_typing import AZIMUTH_MODELS, BROAD_TENX_MODELS
__MRO__ = """
stage CELL_TYPING_DEMULTIPLEXER(
in string model_family,
out bool disable_cloud_cell_types,
o... |
8504ee3ff4e685b42a74f52b83fce3cacd7c9f011738f303e8c6d9bf7d849b5f | Python | 605 | 24 | from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Dict, Type
import numpy as np
import numpy.typing as npt
from ..interfaces import IEncoder
__all__ = ["BaseEncoder", "encoder_registry"]
encoder_registry: Dict[str, Type[BaseEncoder]] = {}
class BaseEncoder(ABC, IEncoder):
... |
40f3e4c3adc12a2cce9f86b8ef8fde791b4e85c0d518768bcd5abda46aa895a3 | Python | 606 | 23 | from detectron2.modeling.meta_arch.fcos import FCOS, FCOSHead
from .retinanet import model
model._target_ = FCOS
del model.anchor_generator
del model.box2box_transform
del model.anchor_matcher
del model.input_format
# Use P5 instead of C5 to compute P6/P7
# (Sec 2.2 of https://arxiv.org/abs/2006.09214)
model.backbo... |
1d827ae411d807038a5416ea715d49cefcd7767a449b0e8ef86641040ffc34c9 | Python | 607 | 14 | from .AttnSleep import Model as AttnSleep
from .EEGNET import Model as EEGNET
from .SleepingPower import Model as SleepingPower
from .visualModels import ViT, SimpleEEGCNN, ResizeTo64, ResNet18Wrapper
from .BrainDecoder import Model as BrainDecoder
from .NeuroStream import Model as NeuroStream
from .SleepingPower impor... |
be2cc33c473e4911d2c7ee05e0282920137c227a713df6dd48721783ec46bb1f | Python | 609 | 23 | from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Dict, Type
import numpy as np
__all__ = ["BaseTransform", "transform_registry"]
transform_registry: Dict[str, Type[BaseTransform]] = {}
class BaseTransform(ABC):
def __init_subclass__(cls, **kwargs):
super().__in... |
40f8546d0ea19ae9b4061d8a3ea41aadf5827347c38d22b4ecd301f0756e2e26 | Python | 610 | 19 | # Copyright (c) Facebook, Inc. and its affiliates.
import unittest
import torch
from detectron2.structures.keypoints import Keypoints
class TestKeypoints(unittest.TestCase):
def test_cat_keypoints(self):
keypoints1 = Keypoints(torch.rand(2, 21, 3))
keypoints2 = Keypoints(torch.rand(4, 21, 3))
... |
797afe2e4fc5fb61194e344780c642c79e509123eca2d60caea0f6a558d3d674 | Python | 610 | 24 | from .cache import MolGraphCache, MolGraphCacheFacade, MolGraphCacheOnTheFly
from .molecule import (
BatchCuikMolGraph,
CuikmolmakerMolGraphFeaturizer,
SimpleMoleculeMolGraphFeaturizer,
)
from .reaction import (
CGRFeaturizer,
CondensedGraphOfReactionFeaturizer,
CuikmolmakerCGRFeaturizer,
Rx... |
a6094a6be171e2fb0f5dbad68b92736c14193a5c4823b140a29a49ac072cc514 | Python | 610 | 17 | try:
import torch
except ImportError:
raise ImportError('Torch is not installed. Please install through https://pytorch.org/get-started/locally/')
# check if torch version >= 1.9.0
from packaging import version
if not version.parse(torch.__version__) >= version.parse('1.9.0'):
raise ImportError(
f... |
2e3e05ac0792a2b5e53bd57dd4700380d83aa3144cecab41ce4ab27190a9190b | Python | 612 | 23 | from dataclasses import dataclass, field
from pathlib import Path
__all__ = ['CheckpointView']
@dataclass
class CheckpointView:
path: Path = field(repr=False)
name: str = field(init=False)
def __post_init__(self):
self.path = self.path.resolve()
if not self.path.exists():
rai... |
7c4e2730607d5f931f612285244ae9355a2a448a2b7f947e06b68f335b5c6fb7 | Python | 614 | 19 | import torch
from torch import Tensor
class KLDivergence():
def __init__(self, reduction: str = "mean", **kwargs):
super().__init__(**kwargs)
assert reduction in ["sum", "mean", "none"]
self.reduction = reduction
def __call__(self, means: Tensor, logvars: Tensor) -> Tensor:
kl... |
97550c5aa1b4e32a250390649102f9404dd38eed793665f6f0668ab8ebe1b90a | Python | 614 | 24 | # Copyright (c) Facebook, Inc. and its affiliates.
import unittest
from detectron2.utils.collect_env import collect_env_info
class TestProjects(unittest.TestCase):
def test_import(self):
from detectron2.projects import point_rend
_ = point_rend.add_pointrend_config
import detectron2.pro... |
773c58a340f61a24a64e3bf0ede6ee39e860cd65c31ac686c265409216191e13 | Python | 616 | 34 | # -*- coding: utf-8 -*-
"""For testing neuromaps.caret functionality."""
import pytest
@pytest.mark.xfail
def test_read_surface_shape():
"""Test reading surface shape."""
assert False
@pytest.mark.xfail
def test_read_coords():
"""Test reading surface coordinates."""
assert False
@pytest.mark.xfai... |
841a3e9c8b2ed6d59a4f16cedf28a5cfad007662aca04aed3250ec4a3fded746 | Python | 618 | 17 | import click
import pytest
from openfecli.clicktypes.hyphenchoice import HyphenAwareChoice
class TestHyphenAwareChoice:
@pytest.mark.parametrize("value", ["foo_bar_baz", "foo_bar-baz", "foo-bar_baz", "foo-bar-baz"])
def test_init(self, value):
ch = HyphenAwareChoice([value])
assert ch.choices... |
2fcd9e124407c9782d155fe7254fa2c1eaadf6204db92d3461ed193f0def5728 | Python | 619 | 16 | from typing import List
import numpy as np
from sklearn.model_selection import KFold
def generate_crossval_split(train_identifiers: List[str], seed=12345, n_splits=5) -> List[dict[str, List[str]]]:
splits = []
kfold = KFold(n_splits=n_splits, shuffle=True, random_state=seed)
for i, (train_idx, test_idx) ... |
2af158cb427779a6e302f97582261c8b07f1075a5e5fd6ac0009d89239a58e6e | Python | 620 | 32 | """New style data collection."""
from .basedatarecorder import BaseDataRecorder, DatasetConfig
from .datarecorders import (
DataRecorder,
JSONDataRecorder,
ParquetDataRecorder,
SQLDataRecorder,
)
from .dataset import (
AgentDataSet,
DataRegistry,
DataSet,
ModelDataSet,
NumpyAgentDat... |
fb54cc6720d1d7c7e5e71fd14fce2537282ccd3be06714a89f284a116f3cf984 | Python | 621 | 18 | from .gradient import GradientMaps
from .embedding import (DiffusionMaps, LaplacianEigenmaps, diffusion_mapping,
laplacian_eigenmaps)
from .alignment import ProcrustesAlignment, procrustes_alignment
from .kernels import compute_affinity
from .utils import is_symmetric, make_symmetric
__all__ =... |
d0b921cba2bdf767bba53290e189f56c14a403ad39c0008a05668564857330da | Python | 622 | 27 | import pytest
from pathlib import Path
from omegaconf import DictConfig, OmegaConf
from hsnn.core.config import paramset, ModelParams
SAMPLES_DIR = Path(__file__).parents[1] / 'samples'
@pytest.fixture(scope='module')
def config_path() -> str:
return str((SAMPLES_DIR / 'config.yaml').resolve())
@pytest.fixt... |
5e5c7701e60313d39c266160fa1245e72ef7644f12f6b6c8175632f01de7b051 | Python | 627 | 19 | import detectron2.data.transforms as T
from detectron2 import model_zoo
from detectron2.config import LazyCall as L
from .coco_loader import dataloader
# Data using LSJ
image_size = 1024
dataloader.train.mapper.augmentations = [
L(T.RandomFlip)(horizontal=True), # flip first
L(T.ResizeScale)(
min_sca... |
ac6dd75c317aed3ae3f967719375caad6ab5cb523e61e296fcfbe7ae4e27a754 | Python | 630 | 29 | from setuptools import setup, find_packages
setup(
name="vascumap",
version="0.1.0",
packages=find_packages(),
install_requires=[
"numpy",
"torch",
"tifffile",
"albumentations",
"segmentation-models-pytorch",
"catalyst",
"scikit-image",
"t... |
b575d2f5cf99f1e3bf3f930e512d6721765b2e39a081b683ee69b9df09bf81d5 | Python | 632 | 17 | """Functions for fetching datasets."""
from .atlases import (fetch_all_atlases, fetch_atlas, fetch_civet,
fetch_fsaverage, fetch_fslr, fetch_mni152,
fetch_regfusion, get_atlas_dir, DENSITIES, ALIAS)
from .annotations import (
available_annotations, available_tags, fetch... |
5f353eef2e95bb1de88929ae29acebfdba71b5ec54a66b49edb04fb2bf0cfa6c | Python | 633 | 24 | from abc import ABC, abstractmethod
from argparse import ArgumentParser, Namespace, _SubParsersAction
class Subcommand(ABC):
COMMAND: str
HELP: str | None = None
@classmethod
def add(cls, subparsers: _SubParsersAction, parents) -> ArgumentParser:
parser = subparsers.add_parser(cls.COMMAND, he... |
20c3c3107442d9665c17b0e5c906284992b92af5cc3555799d44d608f73a7a23 | Python | 635 | 17 | # Copyright (c) Facebook, Inc. and its affiliates.
# pyre-unsafe
from .hflip import HFlipConverter
from .to_mask import ToMaskConverter
from .to_chart_result import ToChartResultConverter, ToChartResultConverterWithConfidences
from .segm_to_mask import (
predictor_output_with_fine_and_coarse_segm_to_mask,
pre... |
88c453be623d5eac110a9a72be31e9c1da896890296d1195eaa6e05a130b4fc9 | Python | 635 | 18 | # Common training-related configs that are designed for "tools/lazyconfig_train_net.py"
# You can use your own instead, together with your own train_net.py
train = dict(
output_dir="./output",
init_checkpoint="",
max_iter=90000,
amp=dict(enabled=False), # options for Automatic Mixed Precision
ddp=d... |
1ac192fa0dac1ae7c3fdffac9d2f1cac2cf9ecc67a55cee15ff07128820a9f68 | Python | 637 | 16 | # Copyright (c) Facebook, Inc. and its affiliates.
import unittest
import torch
from densepose.data.transform import ImageResizeTransform
class TestImageResizeTransform(unittest.TestCase):
def test_image_resize_1(self):
images_batch = torch.ones((3, 3, 100, 100), dtype=torch.uint8) * 100
transfo... |
c7e46187d0663cb327a483dc906515abd1692cf8d1671aa6906826318711021d | Python | 638 | 13 | #pip install git+https://github.com/cox-labs/perseuspy.git
from perseuspy import pd#, nx, write_network
import sys
#_, n, m, outfolder = sys.argv
#G = nx.random_graphs.barabasi_albert_graph(int(n), int(m))
#networks_table, networks = nx.to_perseus([G])
#write_networks(outfolder, networks_table, networks)
from perseuspy... |
428bfb4c1ab804fd8643f580025144d3da5b0c3d68509b7e32178ac629c8a942 | Python | 644 | 19 | # Copyright (c) Facebook, Inc. and its affiliates.
from . import transforms # isort:skip
from .build import (
build_batch_data_loader,
build_detection_test_loader,
build_detection_train_loader,
get_detection_dataset_dicts,
load_proposals_into_dataset,
print_instances_class_histogram,
)
from .c... |
cb3558c62fc3636038eba9082d26ae616c23305a4f30caceb362c0b84955b580 | Python | 644 | 30 | from abc import abstractmethod
from collections.abc import Sized
from typing import Generic, TypeVar
import numpy as np
from chemprop.data.molgraph import MolGraph
S = TypeVar("S")
T = TypeVar("T")
class Featurizer(Generic[S, T]):
"""An :class:`Featurizer` featurizes inputs type ``S`` into outputs of
type ... |
367a3f79828c1796554b9c4a6f061d121dcf26ec78f4a730026179cee650e2fd | Python | 645 | 17 | # Copyright (c) Facebook, Inc. and its affiliates.
from .boxes import Boxes, BoxMode, pairwise_iou, pairwise_ioa, pairwise_point_box_distance
from .image_list import ImageList
from .instances import Instances
from .keypoints import Keypoints, heatmaps_to_keypoints
from .masks import BitMasks, PolygonMasks, polygons_to... |
997e789c333cdc1dc3ba0d965b19b3d4251f46703bf345953a46b1d15ca1a446 | Python | 649 | 19 | import pyriemann
def run_potato(epochs, potato_threshold=2):
'''
This function takes an mne.epochs object and identifies outlying ("bad") segments using some riemann magic
'''
# estimate the covariance matrices from our epochs
covs = pyriemann.estimation.Covariances(estimator="lwf")
cov_mats... |
ecb5f9f130b91e97dd015f0a48438bf439b11d48802b9cc1192c6c15b46e193b | Python | 651 | 23 | import warnings
from gufe import LigandAtomMapping
def get_alchemical_charge_difference(mapping: LigandAtomMapping) -> int:
"""
Return the difference in formal charge between stateA and stateB defined as (formal charge A - formal charge B)
Parameters
----------
mapping: LigandAtomMapping
... |
fb2df2674c19b0f0a649035ba98087fc30123970987740e21319f3ffdb709574 | Python | 652 | 21 | # Copyright (c) Facebook, Inc. and its affiliates.
from __future__ import absolute_import, division, print_function, unicode_literals
import torch
def pairwise_iou_rotated(boxes1, boxes2):
"""
Return intersection-over-union (Jaccard index) of boxes.
Both sets of boxes are expected to be in
(x_center,... |
d0ce10b07e1cdce9c1ebc047050ff79b968e35a4dccfb71088133769d7aa9028 | Python | 653 | 16 | from typing import NamedTuple
import numpy as np
class MolGraph(NamedTuple):
"""A :class:`MolGraph` represents the graph featurization of a molecule."""
V: np.ndarray
"""an array of shape ``V x d_v`` containing the atom features of the molecule"""
E: np.ndarray
"""an array of shape ``E x d_e`` c... |
8babfaff0134188769290d7a976b678a81d4af06c4108e01bf640dbab27a8b54 | Python | 654 | 20 | #
# Copyright (c) 2021 10X Genomics, Inc. All rights reserved.
#
"""Constant values used by compute code and websummary code, put here to allow their use without lots of other.
imports
"""
MT_THROUGHPUT = "MT"
HT_THROUGHPUT = "HT"
GEMX_THROUGHPUT = "GEMX"
THROUGHPUT_INFERRED_METRIC = "throughput_inferred"
INCONSISTEN... |
c42c269b72a6944dce4266680be39b89fa5ba4bf974da36c7cd838b55e434b8b | Python | 656 | 27 | """Scenarios module."""
from .exceptions import (
ModelInstantiationException,
ScenarioAbortedException,
ScenarioFailedException,
ScenarioNotFoundException,
ScenarioNotReadyException,
)
from .runner import RunConfiguration, run_scenarios
from .scenario import Scenario, rescale_samples
from .store i... |
e2c4db7d666e8ab64e0446dc3bd17c2aa3524736b6c2fd2fba9ca5271d30035c | Python | 656 | 24 | import os
import subprocess
try:
subprocess.call(["md5sum", "--help"], stdout=subprocess.DEVNULL)
except FileNotFoundError:
raise Exception # md5sum not found. Are you using Linux?
def md5sum(filename):
"""
returns the md5sum of a file, along with its filename, e.g.:
0df61fe4ddf4455ba4d4e3c15abfabe2 predic... |
05294b36b4c9524209b1f8583db909fbe1bcd547bcd0419bb7d90f36d034b6e9 | Python | 658 | 18 | import shutil
from batchgenerators.utilities.file_and_folder_operations import isdir, join
from nnunetv2.paths import nnUNet_raw, nnUNet_results, nnUNet_preprocessed
if __name__ == '__main__':
# deletes everything!
dataset_names = [
'Dataset996_IntegrationTest_Hippocampus_regions_ignore',
'Da... |
a0aba64383ceee56462481c957066f1220cd9c58f554626e362907b5398ebb7a | Python | 658 | 28 | # This code is part of OpenFE and is licensed under the MIT license.
# For details, see https://github.com/OpenFreeEnergy/openfe
"""
Run SepTop free energy calculations using OpenMM and OpenMMTools.
"""
from .equil_septop_method import (
SepTopComplexRunUnit,
SepTopComplexSetupUnit,
SepTopProtocol,
Se... |
6373079c7e5a0691db4c2d390dd831c4dbaec14930a4a2844dda2be3724ab279 | Python | 659 | 22 | from .cascade_mask_rcnn_mvitv2_b_in21k_100ep import (
dataloader,
lr_multiplier,
model,
train,
optimizer,
)
model.backbone.bottom_up.embed_dim = 144
model.backbone.bottom_up.depth = 48
model.backbone.bottom_up.num_heads = 2
model.backbone.bottom_up.last_block_indexes = (1, 7, 43, 47)
model.backbone... |
90e096e9bc2818aebda269e7314747511e566438a767587673a187d5522e6964 | Python | 659 | 26 | from detectron2.config import LazyCall as L
from detectron2.evaluation import (
COCOEvaluator,
COCOPanopticEvaluator,
DatasetEvaluators,
SemSegEvaluator,
)
from .coco import dataloader
dataloader.train.dataset.names = "coco_2017_train_panoptic_separated"
dataloader.train.dataset.filter_empty = False
d... |
b828c5d0f3086ae38d0432ec8b8a492b50dd011c11c7fdf32cd7182a5f5c2288 | Python | 662 | 22 | #!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")
try:
from django.core.management import execute_from_command_line
except Impor... |
2c4a29b952a5070b341256a864ba34076398112c2accb526710030d7e10c2654 | Python | 665 | 14 | # 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... |
d14589eece616e41e23b686187f79be24cb5a13f6aff20a650f4154f19b4c145 | Python | 665 | 19 | from __future__ import annotations
import json
from dataclasses import asdict
from datetime import datetime, timezone
from pathlib import Path
from src.utils.models import RunReport
def write_report(report: RunReport, report_dir: str) -> Path:
target_dir = Path(report_dir)
target_dir.mkdir(parents=True, exi... |
76afc1e7d4638f490cbf98386059057d12d549b73350d88682dbb0441d3b378c | Python | 671 | 30 | """Mesa Agent-Based Modeling Framework.
Core Objects: Model, and Agent.
"""
import datetime
import mesa.discrete_space as discrete_space
import mesa.experimental as experimental
import mesa.meta_agents as meta_agents
import mesa.time as time
from mesa.agent import Agent
from mesa.datacollection import DataCollector
... |
7e916fa03704066c2ea478e2f2e32d508ec04ef8e98023d07e5d61abe5accb00 | Python | 671 | 12 | # Copyright (c) Facebook, Inc. and its affiliates.
from .cityscapes_evaluation import CityscapesInstanceEvaluator, CityscapesSemSegEvaluator
from .coco_evaluation import COCOEvaluator
from .rotated_coco_evaluation import RotatedCOCOEvaluator
from .evaluator import DatasetEvaluator, DatasetEvaluators, inference_context,... |
9f163ece58d8051e656b8a5f3c06e2ce29de6392f0fe99473b392b7b9aefb6e8 | Python | 671 | 28 | import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name='Stabl',
version='1.0.0',
author='Grégoire Bellan',
author_email='gbellan@surge.care',
description='Stabl light weight',
packages=['stabl'],
install_requires=[
... |
40bd6d2b9093cd01c462f475df8b4338194b139058836e616858bbca0563e4b8 | Python | 673 | 30 | # -*- coding: utf-8 -*-
import warnings
from .flatten import TracingAdapter
from .torchscript import dump_torchscript_IR, scripting_with_instances
try:
from caffe2.proto import caffe2_pb2 as _tmp
from caffe2.python import core
# caffe2 is optional
except ImportError:
pass
else:
from .api import ... |
2ce7bf97795be2c56f8f8120d0d5f409069791bc0aec4abd4761bead4899292a | Python | 678 | 24 | from typing import TypeAlias
import numpy as np
import numpy.typing as npt
import xarray as xr
__all__ = [
"RatesArray",
"CountsArray",
"OccurrencesArray",
"RatesDatabase",
"DeltaTuple"
]
RatesArray: TypeAlias = xr.DataArray
"Rates array, with dims (`rep`, `img`, `pk`)."
CountsArray: TypeAlias =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.