sha256 stringlengths 64 64 | language stringclasses 27
values | size int32 1 491k | lines int32 1 21.8k | content stringlengths 1 200k |
|---|---|---|---|---|
25a49c4e5bced37c789976e603eef5fdb234686a8d0cdb2867bdb7c170735734 | Python | 3,912 | 117 | #!/usr/bin/env python3
"""
Create stereo-seq barcode subsets and corresponding filtered read files.
From the full 10M stereo barcode whitelist:
1. Randomly select 1M barcodes -> stereo.1M.tsv
2. Randomly select 80K barcodes (subset of the 1M) -> stereo.80K.tsv
3. Filter reads to keep only those matching each subset
R... |
48860a74f330971fef42decef3496a2acf73b1a94e75aea5071edaa78da1cea6 | Python | 3,914 | 104 | from .cuda_test import get_gpu_name # type: ignore
from .__cpu_count__ import get_cpu_count
from .__md5sum__ import md5sum
import os
import time
import platform
import subprocess
if platform.system() != 'Linux':
raise Exception # this script is designed to use Linux bash commands. Please use Linux
def get_hostnam... |
15d514a4a0b0fad0e0a25b5666676c14cb745c48b1e8285256dbe6f600c04236 | Python | 3,921 | 99 | import torch
from torch import nn
import torch.nn.functional as F
class UNet3D(nn.Module):
"""
Neural network for time-consistent segmentation or volume segmentation,
adapted from Li, X. et al. Real-time denoising enables high-sensitivity fluorescence time-lapse imaging
beyond the shot-noise limit. Na... |
3c7401211d252b1e1cd0aaad4ec7627e867a609c2917eccd041f22930c1eb4f0 | Python | 3,921 | 112 | import pickle
import numpy as np
import sympy
from matplotlib import pyplot as plt
from rCPGswCPG.utils.gen_utils import get_project_root
from rCPGswCPG.prc_extraction.prc_extraction_subroutines.filtering_utils import *
from scipy.optimize import minimize
'''
given the time series, extract the phase of oscillations
'''... |
99ef05a0cb6d79927999faaab0a0de1f8f5d73c1f4c996d15de141ddf7a149b4 | Python | 3,923 | 129 | """Utilities for computing PNG counts from detection databases.
This module provides shared functionality for counting PNGs across trials,
used by both standard experiment analysis and hyperparameter sweep scripts.
"""
from concurrent.futures import ThreadPoolExecutor
from functools import partial
from typing import ... |
8e3d12bd5ac7da5d8b18d90e53c9026e483bcd573761dad47c5da7e4fcc31ada | Python | 3,926 | 123 | # Copyright (c) Facebook, Inc. and its affiliates.
import logging
from datetime import timedelta
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
from detectron2.utils import comm
__all__ = ["DEFAULT_TIMEOUT", "launch"]
DEFAULT_TIMEOUT = timedelta(minutes=30)
def _find_free_port():
... |
2140c9c6b20273bbf3052a72459954543d93790cc5269e0d8fbaddcfbd30aa8f | Python | 3,928 | 108 | from copy import deepcopy
import numpy as np
def get_shape_must_be_divisible_by(net_numpool_per_axis):
return 2 ** np.array(net_numpool_per_axis)
def pad_shape(shape, must_be_divisible_by):
"""
pads shape so that it is divisible by must_be_divisible_by
:param shape:
:param must_be_divisible_by:
... |
bd8fee9f9a329028185aa375beb71356f63061334dfeae63660eda5fcc59fc72 | Python | 3,928 | 117 | """Utility for splitting large files into chunks and reassembling them."""
import os
import shutil
def split_file(input_path, chunk_size_mb=95, output_dir=None):
"""Split a large file into chunks under the specified size.
Args:
input_path: Path to the file to split
chunk_size_mb: Maximum siz... |
6176f3b272f445ad923d9fe4875a3e142279ff479b8c3958dc661d1c2e061c24 | Python | 3,933 | 120 | """
Boids Flocking Model
===================
A Mesa implementation of Craig Reynolds's Boids flocker model.
Uses numpy arrays to represent vectors.
"""
import os
import sys
sys.path.insert(0, os.path.abspath("../../../.."))
import numpy as np
from mesa import Model
from mesa.examples.basic.boid_flockers.agents imp... |
3d85306730b758b06c9b0a16f4c0b6a6a3153cca7eb0025427b716e11a952ee0 | Python | 3,935 | 116 | # 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... |
331d8087c3ec615e17367b72bfc0ebdfe0a118acde2f57243086f187a24a2973 | Python | 3,937 | 125 | #!/usr/bin/env python
#
# Copyright (c) 2022 10X Genomics, Inc. All rights reserved.
#
import numpy as np
import cellranger.analysis.clustering as cr_clustering
import cellranger.analysis.constants as analysis_constants
import cellranger.analysis.io as analysis_io
import cellranger.analysis.kmeans as cr_kmeans
import... |
6ecbd53ef6a8d43bdb4ea31e3582e6e14208e03a2ec70e0b1ddca73d0ab6a3b5 | Python | 3,940 | 104 | from itertools import product
from typing import Sequence
import numpy as np
import numpy.typing as npt
import pandas as pd
import xarray as xr
from scipy.spatial import KDTree
from hsnn.ops import conversion
from hsnn.core import SpikeRecord
from hsnn.core.logger import get_logger
from hsnn.core.types import Recordi... |
52b87b819cf6b65944b6873e97fc7b67537e802a7e6fbe32e38b047c36eb4552 | Python | 3,949 | 129 | """Support functions for rebuilding the TB Portal FLQ-resistance analysis dataset."""
from pathlib import Path
from typing import Iterable
import numpy as np
import pandas as pd
RIF_COLUMNS = [
"genexpert_rifampicin",
"truenat_rifampicin",
"lpaother_rifampicin",
"hain_rifampicin",
"le_rifampicin"... |
640c381093196ad61fc600eaa83a5f01c520584cdce0d886eb967dd7b60b1b30 | Python | 3,949 | 137 | import csv
import glob
import os
from functools import partial
from multiprocessing import Pool
import numpy as np
import pandas as pd
from tfsenc_config import parse_arguments, setup_environ, write_config
from tfsenc_encoding import build_Y
from tfsenc_load_signal import load_electrode_data
from tfsenc_main import pr... |
da5dfaa5b2392e51698ff197254cf2486ee1773b0c5600b4b64a042f2e4c7d98 | Python | 3,950 | 92 | ############################################################################
# Copyright (c) 2025-2026 University of Helsinki
# All Rights Reserved
# See file LICENSE for details.
############################################################################
"""Tests for AssignmentData header-based column detection in
m... |
a6389cfc749780dabf4dbdb503641ba4bc3a6d1314217b240478e02f1fbc9799 | Python | 3,951 | 105 |
""" Utility functions for cortical thickness analysis. """
__author__ = "Fabi Bongratz"
__email__ = "fabi.bongratz@gmail.com"
import numpy as np
import torch
from pytorch3d.structures import Meshes, Pointclouds
from pytorch3d.loss.point_mesh_distance import _PointFaceDistance
from utils.mesh import Mesh
point_face... |
8cf463feee5c271a4b0d8cbcf291b53b02206a2e6b333f486d35f39994328631 | Python | 3,952 | 125 | # -*- coding: utf-8 -*-
"""
Created on Fri Nov 26 11:20:48 2021
@author: Joseph Vermeil
MainDepthoMaker_##.py - Script to use the Deptho-making functions in the BeadTracker program.
Please replace the "_NewUser" in the name of the file by "_##",
a suffix corresponding to the user's name (ex: JV for Joseph Vermeil)
J... |
63edaf108c4229e4924af882b2704e91bc697643a60889d99228f5d9ce1cc327 | Python | 3,955 | 102 | # Copyright (c) Facebook, Inc. and its affiliates.
import numpy as np
import unittest
from typing import Dict
import torch
from detectron2.config import instantiate
from detectron2.structures import Boxes, Instances
class TestBaseHungarianTracker(unittest.TestCase):
def setUp(self):
self._img_size = np.a... |
bf26185c147961eeca20f03f7c4a358cf5eb44b678c19bb8bf7cc17164b08085 | Python | 3,961 | 97 | import multiprocessing
import shutil
import SimpleITK as sitk
import numpy as np
from batchgenerators.utilities.file_and_folder_operations import *
from nnunetv2.dataset_conversion.generate_dataset_json import generate_dataset_json
from nnunetv2.paths import nnUNet_raw
def copy_BraTS_segmentation_and_convert_labels_... |
18b0b10ee9e3bf12ffec8c41f0b1fb3948acb095a84aff4b187683bbd6797a0d | Python | 3,963 | 105 | import importlib
from typing import List, Any, Tuple, Optional
from taming.data.helper_types import BoundingBox, Annotation
# source: seaborn, color palette tab10
COLOR_PALETTE = [(30, 118, 179), (255, 126, 13), (43, 159, 43), (213, 38, 39), (147, 102, 188),
(139, 85, 74), (226, 118, 193), (126, 126,... |
02b07aea0a2047efe2b73ae740ac5915e38c6fc48848b8769eda164f45e32c10 | Python | 3,965 | 67 | #C:\\Users\\animeshs\\AppData\\Local\\Programs\\Spyder\\Python\\python.exe f:\GD\OneDrive\Dokumenter\GitHub\scripts\evidenceIntensityPepMap.py z:\SIGRID\combined\txt\evidence.txt
import sys
from pathlib import Path
pathFiles = Path(sys.argv[1])
#pathFiles = Path("L:\\promec\\USERS\\Alessandro\\230119_66samples-redo\\co... |
dabcc19d8f30794a1570e7a27451bc358a6efc8cd34ef1b288c4e2d5348b859d | Python | 3,965 | 103 | # Copyright (c) Facebook, Inc. and its affiliates.
# pyre-unsafe
import numpy as np
from typing import Optional, Tuple
import cv2
from densepose.structures import DensePoseDataRelative
from ..structures import DensePoseChartPredictorOutput
from .base import Boxes, Image, MatrixVisualizer
class DensePoseOutputsVisu... |
bee67a3b0d42f07a26bac5155d8709195d82727a231a83baa629873c46ab2003 | Python | 3,969 | 91 | import os
import glob
import numpy as np
import pandas as pd
# from util.test_impedance_analyzer import TestImpedanceAnalyzer
class ImpedanceAnalyzer:
def __init__(self):
pass
@staticmethod
def intan_to_ripple(intan_channels):
intan_to_ripple_map = np.array([31, 29, 27, 25, 2... |
490fd9eaf102ec0d2a6a45d163b6d26439baa312f97551855a023542a4b57371 | Python | 3,971 | 113 | """
Code to execute code tutorial notebooks in /docs/examples/.
This will not be run through pytest but is executed in a separate CI job.
A couple notes:
- the tutorials require a number of extra dependencies and data files to be present
check out the test-tutorials.yml workflow to see how this is set up.
- the ... |
4f2b75a176102b83c5724b075bf5c70ef1af5a91dc67647c001d0ba4e26c1006 | Python | 3,973 | 113 |
############################################################################
# Copyright (c) 2022-2026 University of Helsinki
# All Rights Reserved
# See file LICENSE for details.
############################################################################
#!/usr/bin/env python3
import argparse
import csv
def load_... |
a7a62fab8cb7c6d44fef3aa6c101b6a411a9113ee6e8be74566ba562b2b36516 | Python | 3,973 | 127 | # 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
import numpy as np
from gufe.settings.typing import Nano... |
5141356a858b54a64b0f05d53978f4d52b924012e6c0778910194de2efa603e4 | Python | 3,976 | 123 | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from support.config import (
ALGORITHMS,
ALGORITHM_LABELS,
COLORS,
COUNTRIES,
METRICS,
SETTINGS,
SETTING_LABELS,
)
from support.plot_helpers import metric_ci, metric_value, tables
OFFSETS = {
"within_country": 0.18... |
f6eb47759a3c755607c5bf6bfec625d30cb19d73634527d25f567dbdfc8459dd | Python | 3,977 | 108 |
############################################################################
# Copyright (c) 2022-2026 University of Helsinki
# All Rights Reserved
# See file LICENSE for details.
############################################################################
#!/usr/bin/env python3
import argparse
import csv
import os
... |
3d588d791a001c02618715e24eb8400599799795ae8c604e02a629c25c83ed61 | Python | 3,979 | 108 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import copy
import json
import numpy as np
import os
import sys
import pycocotools.mask as mask_utils
from detectron2.utils.env import seed_all_rng
from detectron2.utils.file_io import PathManager
d... |
fd5e25c7d73c289f543196425c2a0ccc66d4a635867c0e072b0c28283e0585f7 | Python | 3,979 | 111 | from itertools import product
import torch
import torchvision.transforms as transforms
from tqdm import tqdm
import numpy as np
from scipy.stats import spearmanr
import matplotlib.pyplot as plt
from . import config
from .utils.condition import AttackParamsLoader
from .utils.model_utils import load_model
from .utils.a... |
c8e8fa59363fba4333fe34ff588e4e5a33dca1bf5befd18ab23aaad7d216aa76 | Python | 3,983 | 117 | # This code is part of OpenFE and is licensed under the MIT license.
# For details, see https://github.com/OpenFreeEnergy/openfe
import numpy as np
import openmm
import pytest
from openfe.protocols.restraint_utils.openmm.omm_forces import (
add_force_in_separate_group,
get_boresch_energy_function,
get_cus... |
df0a776f81904b8b87d7635a1082d71bdeac2619c2a4cd2c7b6251aed886f539 | Python | 3,987 | 120 | import os
import pandas as pd
import numpy as np
import scanpy as sc
import scib
from scib.metrics import kBET
result_dir = "PATH_TO_RESULT_DIR/"
os.makedirs(result_dir, exist_ok=True)
unintegrated_path = "PATH_TO_UNINTEGRATED_COMBINED_ADATA_H5AD"
METHODS = [
{"name": "scvi", "h5ad": "PATH_TO_INTEGRATED_SCVI_RES... |
72b24d7d9d3fba4401fc2a1c94bba2d42902edab59249ef3756963ba02293585 | Python | 3,988 | 113 | verbose = False # verbosity of ratinabox, recommend False unless debugging
_save_plot_warnings_on = True # whether to warn that autosave is turned off
_stylize_plot_warnings_on = (
True # whether to warn that rcParams haven't been set to make plots look good
)
_stylized_plots = False # whether rcParams have be... |
6bf0a547818395184760f9fa285a710e72659f483ef4a11d23c9161e43263d52 | Python | 3,990 | 133 | from __future__ import annotations
import itertools as it
import json
import operator as op
import textwrap
from collections.abc import Sequence
from math import ceil, floor, inf
import more_itertools as itx
from snakebids.types import ZipList
def quote_wrap(val: str) -> str:
"""Wrap string in quotes, with add... |
86c2c72bde612f5d1fa6e035968c7d3e276d5b0facef89cc00ba3d6ce80a639c | Python | 3,992 | 110 | from os.path import join as join
import urllib.request
import numpy as np
import torch
import logging, os, urllib
from qm9.data.prepare.utils import download_data, is_int, cleanup_file
md17_base_url = 'http://quantum-machine.org/gdml/data/npz/'
md17_subsets = {'benzene': 'benzene_old_dft',
'uracil':... |
ff1f8feda9a12aae95348ca50d395fab197a8ff21cbcb01a8d7138d5ba61409e | Python | 3,993 | 103 | #
# Copyright (c) 2019 10X Genomics, Inc. All rights reserved.
#
"""Functions to compute various statistical operations on sparse matrices."""
from __future__ import annotations
from typing import TYPE_CHECKING
import numpy as np
import scipy.stats
import sklearn.utils.sparsefuncs as sparsefuncs
if TYPE_CHECKING:
... |
9be05214019b6d51ec5fb7119f5a910b97f70aa88e3fc2e6619e177bae45ade6 | Python | 3,998 | 123 | import argparse
import torch
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def main(output_dataset_path, out_csv_path=None, make_plot=False, plot_path=None):
# Load the output dataset
ds = torch.load(output_dataset_path)
# Expect keys: "labels", "semantics", "dataset"
labels ... |
e89daed8a548b704575c11f298cafab34f74e8edde1b448223d2dcb5662476da | Python | 3,998 | 75 | # Copyright 2020 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... |
264d3c442ba12313a9d9f02e64eecc5f6fea54f62664a5b752c3ebcae6184b17 | Python | 4,005 | 120 | """Graph-convolution layer for MolGpKa.
Vendored from MolGpKa (https://github.com/Xundrug/MolGpKa), MIT License.
Patched for SMILES2Docking:
* Removed the ``torch_scatter`` dependency (its single ``scatter_add`` use in
degree normalisation is replaced with a native ``index_add_``), so the
frozen cross-platfo... |
767c2066b4eb4d22ddb983b0c53992af98c2841da8ad7e8b78e21eb344af5e4c | Python | 4,008 | 134 | """Tools to manage generation and interconversion of bidsapps and snakemake outputs."""
from __future__ import annotations
import json
from pathlib import Path
from typing import Literal
import more_itertools as itx
from snakebids.exceptions import RunError
Mode = Literal["workflow", "bidsapp"]
def prepare_bidsa... |
95e93b7072eb1388d2d34e497f7853e773089886528ad8752b5eba4319b727d2 | Python | 4,011 | 78 | """Command-line interface for the TAPA pipeline."""
import argparse
import sys
from .config import TAPAConfig
from .pipeline import TAPAPipeline
def main():
parser = argparse.ArgumentParser(
prog="tapa",
description="TAPA: Speaker diarization + phonetic analysis pipeline",
)
parser.add_a... |
6abe74c9bbe62cd777e86fdbe40d03211e0db68cdc50b022eb103d6c5967ce07 | Python | 4,015 | 109 | """Tests for `node_label_sorting`.
The sort used to be driven by a directed breaks-by-breaks geodesic matrix (4.5GB on a
71k node skeleton). It now uses two O(N) quantities instead - the subtree height and a
difference of root distances - which are mathematically the same thing. The reference
implementation below is t... |
4741e2b1a6bd4e671ee2ac66d100561234c7f1899109cc1df4ce7a53cd4c9046 | Python | 4,017 | 133 | """Tests for path-like and vectorized inputs in GradientMaps.fit (issue #140)."""
from pathlib import Path
import numpy as np
import pytest
from brainspace.gradient import GradientMaps
from brainspace.gradient.gradient import _devectorize, _load_matrix
def _make_psd_matrix(n, seed):
rs = np.random.RandomState(... |
ae494d49d8a77c1ab30f5f760b1ae9cdcfd16adca1f8eeb01f568a3727c65f9f | Python | 4,017 | 109 |
from tqdm import tqdm
import numpy as np
import mne
from micorr.snr import snr_func
# Testing given estimators by comparing single channels response with all other channels
def cal_rel_values(est_list, sig_comp, data, snr=30):
results = {est: [] for est in est_list}
n_total = data.shape[0] * len(est_l... |
e3668f55b83c9f12777683cdcb30a28adc2f1469681aeb8c8808d8c3fc1c1de4 | Python | 4,017 | 106 | import torch
from torch import nn
class Unet_v0(nn.Module):
"""
Neural network for semantic image segmentation U-Net (PyTorch),
Reference: Falk, T. et al. U-Net: deep learning for cell counting, detection, and morphometry. Nat Methods 16,
67–70 (2019).
Parameters
----------
n_filter : in... |
266aadaafe0b7b323af4a3679fdee07a4d11814e288e5dbf7776d8b465bdae47 | Python | 4,023 | 90 | from typing import Any, Dict, Optional, Sequence
import numpy as np
from .base import BaseTrainable, set_nested
from .scalars import scalar_registry, BaseScalar, StateMixin
from .criterion import criterion_registry, BaseCriterion
from ._utils import parse_scale_factor
__all__ = ["TrainSNN"]
class TrainSNN(BaseTrai... |
808453cd524bd252995a17e729351f3fb217dec99ed330d4490b54e2ce409875 | Python | 4,023 | 106 | #!/usr/bin/env python3
############################################################################
# Copyright (c) 2022-2026 University of Helsinki
# All Rights Reserved
# See file LICENSE for details.
############################################################################
"""Convert exon splice-site counts fro... |
f216f800bc6f7aa073cd5e3234cd7322580d197fd9067fca3456e57d01976d5e | Python | 4,026 | 121 | """Tests for `navis.config.quiet_logger` and the sites that use it.
There is only one navis logger, so a function that silences it and then fails
takes the whole library's output down with it - for the rest of the session,
and with nothing to tell the user why. These check that no such function can.
"""
import loggin... |
bd4e9e58c84af5bb86889899574492253597174fea879add5afc7c8ffdcc3213 | Python | 4,027 | 112 | """Helpers for building the canonical HFB annotation table."""
from __future__ import annotations
import numpy as np
import pandas as pd
from hsnn.analysis.png import PNG
_ROLE_COLUMNS = {
"l": ("l_layer", "l_id"),
"h": ("h_layer", "h_id"),
"b": ("b_layer", "b_id"),
}
def png_record(
png: PNG, exp... |
2e2fcf2c38cce81d24af78fb0542ca2b9a2b9ca953ae2bff36eeb161236656ab | Python | 4,032 | 103 | # Copyright (c) 2020 10x Genomics, Inc. All rights reserved.
"""Code to provide preflights for AGGR and munging of data.
From multiple versions in the preflight.
"""
from __future__ import annotations
import os
import martian
import cellranger.constants as cr_constants
import cellranger.hdf5 as cr_h5
import cellran... |
710e33b4702d45df67a8cdf5f87198a1ed032c8748a7c95aee3084292fe81d5e | Python | 4,034 | 93 | #!/usr/bin/env python
# Copyright 2017 - 2022 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 o... |
71b7abea21183f9e5dd130b883912d6b5ccfdc4a1dd06d941c1ce97f1068b6db | Python | 4,041 | 139 | """
The Basics
==========
<!-- difficulty: beginner -->
Get a feel for NAVis: load a neuron, inspect it and run basic operations.
This is not supposed to be comprehensive but rather to give you a flavor of how things work. For inspiration,
explore the [example gallery](../index) and for detailed explanations have a l... |
43d677ddde9fbb2b22ac944459f4d74711645e7d6c825f4f73df812e0cfadeff | Python | 4,044 | 119 | #!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
"""
Point supervision Training Script.
This script is a simplified version of the training script in detectron2/tools.
"""
import os
import detectron2.utils.comm as comm
from detectron2.checkpoint import DetectionCheckpointer
from detectron2.co... |
364549a6a53c84366f9047a0e1b8dc77758d04cf543806264b0231c8813ce09a | Python | 4,045 | 100 | # Copyright (c) Facebook, Inc. and its affiliates.
import torch
from torch.nn import functional as F
from detectron2.structures import Instances, ROIMasks
# perhaps should rename to "resize_instance"
def detector_postprocess(
results: Instances, output_height: int, output_width: int, mask_threshold: float = 0.5
... |
fb7a0b963167b8c9baa0f0d489957b236cca62578c5c9cbe063d43755d99d5e0 | Python | 4,051 | 88 | import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from scipy.stats import pearsonr, spearmanr
# 1. Load Data
df_iq = pd.read_csv('peptides.txtiQ_log2_LFQ.csv').rename(columns={'Leading razor protein': 'Protein'})
df_mq = pd.read_csv('proteinGroups.txt', sep='\t', low_memory=F... |
0190dbc7303a12d7c1afa5ba633d72bcaedabb4086fedacefffbe72b85b7e363 | Python | 4,053 | 88 | import traceback
from typing import Type
from batchgenerators.utilities.file_and_folder_operations import join
import nnunetv2
from nnunetv2.imageio.natural_image_reader_writer import NaturalImage2DIO
from nnunetv2.imageio.nibabel_reader_writer import NibabelIO, NibabelIOWithReorient
from nnunetv2.imageio.simpleitk_r... |
10c32b7bdcc1e9db33fb8a00a1515b8fbba1012686a075cc24b5eb804e8b170c | Python | 4,053 | 98 | # This code is part of OpenFE and is licensed under the MIT license.
# For details, see https://github.com/OpenFreeEnergy/openfe
import pathlib
import pytest
from gufe.protocols import execute_DAG
from openff.units import unit
import openfe
from openfe.protocols import openmm_afe
@pytest.mark.integration # takes ... |
bd2d3d712c496bd3e5f4fff2ab889c28fd798aeef826af60b8dab18f91c71136 | Python | 4,055 | 88 | """The generated config must not depend on where the user typed the command.
Workflow jobs run with --directory set to the output directory, so every path the config hands
to Snakemake has to be absolute regardless of whether -o was relative.
"""
import argparse
import os
import sys
import tempfile
import unittest
fro... |
eccfb23848beefe67bed3d0698e40c7e2f4ed43f7e92320e411681523a7a1776 | Python | 4,065 | 126 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import torch
# from torch.autograd import Variable
from lpips.trainer import *
from lpips.lpips import *
def normalize_tensor(in_feat,eps=1e-10):
norm_factor = torch.sqrt(torch.sum(in_... |
f04b1801fc8e079868d28f8f7730bbbfdc8757adb69b720e1f6069efa1a765f9 | Python | 4,071 | 154 | """ Experiment-specific parameters. """
__author__ = "Fabi Bongratz"
__email__ = "fabi.bongratz@gmail.com"
from params.default import hyper_ps_default
from utils.utils import update_dict
from utils.losses import *
from utils.graph_conv import (
GraphConvNorm,
LinearLayer,
)
from utils.eval_metrics import *
#... |
8c5afff8e86690685a5108e7a04af15d391e106abd05152b2d96b91d90be8c3c | Python | 4,075 | 96 | #!/usr/bin/python2
""" Align words in textgrid files with token codes from words.tsv """
from __future__ import print_function
import sys
import itertools
from collections import namedtuple
import textgrid
Code = namedtuple("Code", "story token".split())
Word = namedtuple("Word", "code parts".split())
WORDS_FILENAME ... |
596c9fea9b83a09b4029c858577bfb891ca40b4ce20818f7ef036b6f717ccc0b | Python | 4,077 | 118 | # Copyright (c) Facebook, Inc. and its affiliates.
import numpy as np
from typing import List
import fvcore.nn.weight_init as weight_init
import torch
from torch import nn
from detectron2.config import configurable
from detectron2.layers import Conv2d, ShapeSpec, get_norm
from detectron2.utils.registry import Registry... |
80fd41d10105b91334290c5b5c3b7c6cf2e5f853e481d5fb85c873bc307d5a86 | Python | 4,092 | 128 | from __future__ import annotations
import argparse
import importlib
import re
from pathlib import Path
from typing import Any, cast
import attrs
from snakebids import bidsapp
from snakebids.exceptions import ConfigError
from snakebids.io.yaml import get_yaml_io
def _make_underscore_dash_aliases(name: str) -> set[s... |
50b12a183faf5cdec4323180ce0bc6fb4b4ea24c0e093e32fe4865c38428f994 | Python | 4,094 | 138 | """ Created on Wed Jun 25 13:49:08 2025
@author: dcupolillo """
import spyne
from pathlib import Path
from PyQt5.QtWidgets import (
QMainWindow, QFrame, QLabel, QGridLayout,
QPushButton, QFileDialog, QMessageBox)
from PyQt5.QtCore import Qt, pyqtSignal
import ROIpy as rp
class LoadFiles(QFrame):
dat... |
098e11a5327c79325771eb241d3c08c6adaf278f938eba02a7279012cd298932 | Python | 4,096 | 161 | # -*- coding: utf-8 -*-
"""For testing neuromaps.images functionality."""
import nibabel as nib
import numpy as np
import pytest
from neuromaps import images
def test_construct_surf_gii():
"""Test constructing a surface GIFTI image."""
vertices = np.array([[0, 0, 0], [0, 0, 1], [0, 1, 1]])
tris = np.arr... |
7ca0c559a3702d86da035a6e33a4ffca5998f2cc989bf8cc5509c60dc5e10d6b | Python | 4,096 | 158 | # Copyright (c) Facebook, Inc. and its affiliates.
"""
An awesome colormap for really neat visualizations.
Copied from Detectron, and removed gray colors.
"""
import numpy as np
import random
__all__ = ["colormap", "random_color", "random_colors"]
# fmt: off
# RGB:
_COLORS = np.array(
[
0.000, 0.447, 0.... |
db9161e5b39ce809b358254efac5af6ec51f563e69f0d53f1ce28f9d50192c97 | Python | 4,097 | 91 | import os
import numpy as np
import cv2
import albumentations
from PIL import Image
from torch.utils.data import Dataset
class SegmentationBase(Dataset):
def __init__(self,
data_csv, data_root, segmentation_root,
size=None, random_crop=False, interpolation="bicubic",
... |
a1727bccfa860fb27088785009d836e756c81d7be196674c8df5c12bdbc9632f | Python | 4,101 | 104 | #!/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... |
1b475599246af53e44ef139d0c7d4d025ad28e249e6ce9e70fa955f13fb43224 | Python | 4,105 | 172 | """This tests the CLI functionality of training and predicting a regression model on a multi-molecule.
"""
import pytest
from chemprop.cli.main import main
pytestmark = pytest.mark.CLI
@pytest.fixture
def data_path(data_dir):
return (
str(data_dir / "regression" / "rxn+mol" / "rxn+mol.csv"),
st... |
0cd9ac46147a0383a121b5d21f12d081a78bc20ae1938a66ca04cbfdcd78a969 | Python | 4,106 | 122 | #!/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.
#####################################################... |
1801564019900a607484fde384641ee43d6363928afcfb43e7a096e6379b1f5b | Python | 4,111 | 156 | import numpy as np
import pytest
from sklearn.preprocessing import StandardScaler
import torch
from chemprop.nn.transforms import GraphTransform, ScaleTransform, UnscaleTransform
class MockBatchMolGraph:
def __init__(self, V, E):
self.V = V
self.E = E
@pytest.fixture
def mean():
return np.a... |
f7edbad2fc3e1e9577c95e3bf9551e622cb3618e42e4ecb7629296d258be1d5b | Python | 4,111 | 121 | # %% 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
es... |
ca683c9a779ab9e669b1b2ed1f411291948cdc82848b8986204c7233f2d1342c | Python | 4,112 | 122 | #!/usr/bin/env python3
#
############################################################################
# Copyright (c) 2023-2026 University of Helsinki
# # All Rights Reserved
# See file LICENSE for details.
############################################################################
"""
Standalone barcode detection to... |
868ead80d7bb872800bfcb2e94e4ab42774d717088c0de6d125b7ecdd83da7a9 | Python | 4,113 | 125 | from typing import Literal
import mesa
from mesa.discrete_space import OrthogonalMooreGrid, OrthogonalVonNeumannGrid
from mesa.examples.advanced.epstein_civil_violence.agents import (
Citizen,
CitizenState,
Cop,
)
from mesa.experimental.scenarios import Scenario
# Define a typed scenario subclass with de... |
7a6d480192c65ad45f9c121a6ff344fd76e0a3389467b93a1f72f72b53f80d2e | Python | 4,114 | 128 | import time
import numpy as np
import torch
from thop import profile
import eeg_visual_classification.models as models
def evaluate_model(model, input_size=(1, 128, 440), device="cpu", runs=10):
"""
Measure evaluation metrics for a given model.
Returns:
metrics_dict: Dictionary containing params... |
e8ba825420b990263dfceaac4aa83926f0bd5c9a7fb255522ad140b0a1a464f1 | Python | 4,115 | 152 | # -*- coding: utf-8 -*-
"""Utility functions."""
import os
import numpy as np
from pathlib import Path
import tempfile
import subprocess
def tmpname(suffix, prefix=None, directory=None):
"""
Little helper function because :man_shrugging:.
Parameters
----------
suffix : str
Suffix of crea... |
176581f4b17eb5db2a536eca7420763cda4a2778c7162cd1c8c0129c7c48b919 | Python | 4,116 | 93 | import os
import pandas as pd
import numpy as np
from scipy.stats import ttest_1samp
from loguru import logger
logger.info('Import OK')
input_path = 'results/preprocessed/normalised_summary.csv'
output_folder = 'results/preprocessed/'
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# Read in ... |
69068d632d4385d15e7d66180e9ada9b5ed828efe9e7aca7a6e53caa12abce70 | Python | 4,119 | 114 | #!/usr/bin/env python3
############################################################################
# Copyright (c) 2022-2026 University of Helsinki
# # All Rights Reserved
# See file LICENSE for details.
############################################################################
"""Split a simulation GTF into the re... |
47a64248474b736926f23afe413d0eff8f84797c7a7d9073cca8662c2807c0b0 | Python | 4,122 | 145 | import torch
import torch.nn as nn
import math
class ConvLayer2D(nn.Sequential):
def __init__(self, in_channels, out_channels, kernel, stride, padding, dilation):
super().__init__()
self.add_module("norm", nn.BatchNorm2d(in_channels))
self.add_module("relu", nn.ReLU(True))
self.add... |
fa48840211d09ae4737d71e20dde8fb98a13517121f368a226df1233b96c297c | Python | 4,124 | 128 | from __future__ import annotations
import argparse
from pathlib import Path
from typing import Literal
import more_itertools as itx
import pytest
from hypothesis import given
from hypothesis import strategies as st
from snakebids.exceptions import ConfigError
from snakebids.plugins.cli_config import CliConfig
clas... |
05ba17ad690cac1e16b1be76ce0505b5f73ab083cd5421fe1868485599e34be8 | Python | 4,125 | 125 | import yaml
import subprocess
from pathlib import Path
from datetime import datetime
def get_timestamp():
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
CONFIG_PATH = Path("config_attackcnn.yaml")
with CONFIG_PATH.open("r") as config_file:
config = yaml.safe_load(config_file)
LAYERS = config["layers"]... |
a667fcd60fa4e46c15892f6691d03d2604ca623202961f323ce8cab857a21fe5 | Python | 4,126 | 103 | # -*- coding: utf-8 -*-
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import numpy as np
import torch
# fmt: off
from detectron2.data.detection_utils import \
annotations_to_instances as base_annotations_to_instances
from detectron2.data.detection_utils import \
transform_instance_ann... |
aec5d80bc27869713462cecef6724d7d484c3ea1d42b437be1d945f9ff657273 | Python | 4,127 | 121 | # This code is part of OpenFE and is licensed under the MIT license.
# For details, see https://github.com/OpenFreeEnergy/openfe
from typing import Callable
from openfe.utils import requires_package
from ...utils.silence_root_logging import silence_root_logging
try:
with silence_root_logging():
from per... |
30f60396252015b89697786d4baa9535fab30f4ad6337f8e21720fc524081cba | Python | 4,131 | 123 | """Internal module for console introspection.
Module modified from [pandas](https://github.com/pandas-dev/pandas)
`pandas.io.formats.console` under BSD 3-Clause License
LICENSE
=======
BSD 3-Clause License
Copyright (c) 2008-2011, AQR Capital Management, LLC, Lambda Foundry, Inc. and PyData \
Development Team
All r... |
d63ea4a4b4867dbf526bc88ed07ec1bc2032b68fbf690d4c670444cda12eb7a4 | Python | 4,131 | 113 | #!/usr/bin/env python
# Copyright 2016-2019 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... |
305e054ed48729c309f6cbda50d55ddfde5e16721ab63c5520d06b79fa448eb6 | Python | 4,133 | 106 | #
# Copyright (c) 2020 10X Genomics, Inc. All rights reserved.
#
"""Extension methods for the molecule counter."""
from __future__ import annotations
import numpy as np
from cellranger import molecule_counter as cr_mc
def get_indices_for_values(
mc: cr_mc.MoleculeCounter, col_names, values, chunk_size: int = (... |
b08803f78714b3370aedc48600ae4e4c71c2abb5c9e450dc23428eaa5479cb5f | Python | 4,136 | 104 | """
utils/common.py
---------------
Shared data structures, logging helpers, and figure saving.
All other modules import from here.
"""
import sys
import time
import dataclasses
from typing import Dict, List
import numpy as np
import matplotlib.pyplot as plt
# ── Colour codes for terminal output ─────────────────────... |
e7cfb0ebb36c752b279f00ba0a36158dccb88dc24a826f7a3a604a145ec57b2f | Python | 4,137 | 97 | #!/usr/bin/python3
'''
BSD 3-Clause License
Copyright (c) 2023, F. Teufel and M. H. Gíslason
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
... |
1e41b2e7c42e2808bbf6785c7272ceadc5cc53ad98fad6b0737e451525ea48ce | Python | 4,138 | 114 | """Tests for the flow metrics on *fragmented* neurons.
These metrics work out how many synapses/leafs are proximal to a node as
`total - distal`. That identity only holds on a single-rooted tree; on a forest, nodes
in another fragment are neither distal nor proximal, and counting them as proximal used
to inflate the f... |
4a6bd9e71ca81ddd1161afe0c40a64e24711f3720851c2888c9141594eda5b11 | Python | 4,139 | 145 | import torch
import torch.nn as nn
class ResidualBlock(nn.Module):
def __init__(
self,
in_channels: int,
out_channels: int,
kernel_size: int,
leaky_relu_negative_slope: float,
) -> None:
super().__init__()
# Main convolutional laye... |
0251ef9edc829ae5bbc6f4327696a8c6e11fde3e918d35ca6cb685be54d1c3c7 | Python | 4,140 | 96 | import os
import numpy as np
import pandas as pd
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)
# peak-gene linkage matrix
#dir_path = "/home/nomura/Proj/mmvelo/data/10x_multiome_brain_repre_wo_IN/anal... |
e72dfc40590b59ca2748d589922ce08f4d52dba12e7009bdfc3484dc31685b43 | Python | 4,140 | 115 | import math
import torch
from pyro.distributions.zero_inflated import ZeroInflatedNegativeBinomial
import numpy as np
from torch.distributions import Distribution
from scipy.special import iv
def kl_divergence(d1, d2, K=100):
"""Computes closed-form KL if available, else computes a MC estimate."""
if (type(d1)... |
774e96c97f030e9b8c9d7d760e615e70c783781fcaafff2ed7bf61a8e6c72757 | Python | 4,142 | 102 | #!/usr/bin/env python3
# Copyright 2004-present Facebook. All Rights Reserved.
import numpy as np
from typing import List
from detectron2.config import CfgNode as CfgNode_
from detectron2.config import configurable
from .base_tracker import TRACKER_HEADS_REGISTRY
from .vanilla_hungarian_bbox_iou_tracker import Vanil... |
ff615ff7b67226d925875985493b9eaba20939bd9651544bd508d62d37c5264b | Python | 4,142 | 84 | from nnunetv2.dataset_conversion.generate_dataset_json import generate_dataset_json
from nnunetv2.paths import nnUNet_raw, nnUNet_preprocessed
from batchgenerators.utilities.file_and_folder_operations import *
import shutil
if __name__ == '__main__':
"""
This is going to be my test dataset for working with ti... |
11bf9c643954ce8f650329cd325df52069e2c0e8783988deab38858a86fdcf67 | Python | 4,143 | 138 | import pandas as pd
from sklearn.base import clone
from sklearn.compose import ColumnTransformer
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import ParameterGrid
from sklearn.neural... |
f2e6b41c333311fff689783de7dcac03f071522abd902b0857676a52af080013 | Python | 4,149 | 123 | #!/usr/bin/env python
#
# Copyright (c) 2015 10X Genomics, Inc. All rights reserved.
#
"""Assorted grab-bag of miscellaneous helper methods.
Do not add to this module. Instead, find or create a module with a name
that indicates to a potential user what sorts of methods they might find
in that module.
"""
from __fut... |
c74ad4264338e0574ee3fa96b75a9f08105a28c771f26ce425d95a7d06500527 | Python | 4,153 | 119 | # 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... |
58e6fa43d6ce4c20afab539aed165ef6b5d2c0fad12ada6f48f39cf4409261fa | Python | 4,163 | 102 | from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any
from rdkit import Chem
from src.utils.models import MolecularRecord
class InvalidSmilesError(Exception):
"""Raised when a SMILES string cannot be parsed."""
class AmbiguousFragmentError(Exception):
"""Raise... |
6ebe5357561ce70f839be68972bbbbe84b70511f642e9cc8bc6a7e7a024fae20 | Python | 4,165 | 144 | import argparse
import pandas as pd
import logging
from create_pairs_from_alignments import create_genus_df
from filter_comparisons import filter_comparisons
from assign_splits import assign_splits
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"--data-dir",
"-d",
... |
6b531c77a1b3b1e86c9c2a3c9c633121aa8c76b1039a0081a6a88cc9c16095e1 | Python | 4,171 | 118 | """Categorical and feature-cleaning helpers for descriptive analyses.
Please do not perform modeling-time imputation here. For predictive models,
imputation should be inside sklearn pipelines.
"""
import pandas as pd
def replace_missing_categorical(df: pd.DataFrame, columns: list[str]) -> pd.DataFrame:
out = df.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.