sha256
stringlengths
64
64
language
stringclasses
27 values
size
int32
1
491k
lines
int32
1
21.8k
content
stringlengths
1
200k
63a7a8e848ccd981b9e713bff1ecbd686fb269cdc17f7e4c6c1f3afe9322267b
Python
3,308
123
"""Conversion functions between RGB and other color systems. This modules provides two functions for each color system ABC: rgb_to_abc(r, g, b) --> a, b, c abc_to_rgb(a, b, c) --> r, g, b All inputs and outputs are triples of floats in the range [0.0...1.0]. Inputs outside this range may cause exceptions...
f5bf44cc24796fedbe35a1fc1d13287f62868f4e80a02927328626e8887d87fd
Python
3,308
101
""" neuPrint ======== <!-- difficulty: intermediate --> Query and fetch neurons and connectivity from a neuPrint server. [NeuPrint](https://www.biorxiv.org/content/10.1101/2020.01.16.909465v1) is a service for presenting and analyzing connectomics data. It is used to host, for example, the Janelia EM reconstructions ...
a00d00d0d8a54c78b45d8a2e61a35c3129a928374d60fc1f4bde8536a46e4d42
Python
3,309
92
"""A Boid (bird-oid) agent for implementing Craig Reynolds's Boids flocking model. This implementation uses numpy arrays to represent vectors for efficient computation of flocking behavior. """ import numpy as np from mesa.experimental.continuous_space import ContinuousSpaceAgent class Boid(ContinuousSpaceAgent): ...
2ea620765e982cffe87b46ab2054e729540b7166dd00646d1d96624bfa1fc03d
Python
3,322
106
import logging from descriptastorus.descriptors import rdDescriptors, rdNormalizedDescriptors import multiprocess import numpy as np from rdkit import Chem from rdkit.Chem import Descriptors, Mol from rdkit.Chem.rdFingerprintGenerator import GetMorganGenerator from chemprop.featurizers.base import VectorFeaturizer fr...
4e06397f1f90cf35bdef04e6c647db81989bf02450333fff3ca0dcc7ffc28051
Python
3,324
57
import numpy as np import torch from nnunetv2.training.nnUNetTrainer.nnUNetTrainer import nnUNetTrainer class nnUNetTrainer_probabilisticOversampling(nnUNetTrainer): """ sampling of foreground happens randomly and not for the last 33% of samples in a batch since most trainings happen with batch size 2 an...
e0afc9d50037967a01af1990cc7fdc2c595d6064cff25f462ed3400f0cb350d4
Python
3,325
103
import time from pathlib import Path import torch import torch.nn as nn import torchvision.transforms as transforms from tqdm import tqdm from .utils.activation_manager import ActivationManager from .utils.pgd_attack import PGDAttack, AttackParams from .utils.attack_result import AttackResult from .utils.data_utils i...
2d675f7c8c11a425cd2f1d1a34b08f4a3d24b79f422a59c8cb2b04fd86d194b2
Python
3,332
122
# This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe import gzip import pytest from gufe.tests.test_tokenization import GufeTokenizableTestsMixin import openfe from openfe.protocols.openmm_afe import ( AbsoluteBindingComplexUnit, Abso...
8d8c610c4e7b548c49a723a5d35e64914cd2094cd8dcc199b0c87ccb1fdca5f2
Python
3,335
97
#!/usr/bin/env python # # Copyright (c) 2021 10X Genomics, Inc. All rights reserved. # """A helper stage to determine method used for multiplexed data.""" from __future__ import annotations from typing import TYPE_CHECKING import martian import cellranger.rna.library as rna_library from cellranger.fast_utils import...
9127e7c7aa473328ba15862b6dbf4d5f0e1aa2a9bad63b3517636a4bc6615ddc
Python
3,338
69
from matplotlib import pyplot as plt import numpy as np import os import pickle def get_index(T, dt): return int(T*1000 / dt) def plot_VNA_responses(VNA, long_stim_start_ind, long_stim_stop_ind, short_stim_start_ind, short_stim_stop_ind): fig, ax = plt.subplots(1, 1, figsize = (8, 3)) ax.plot(VNA, color='...
e80f661414b5949d275f04cf616ee8e437f3533883914bff98e0dd2dc0c6dabc
Python
3,341
79
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 diffExprNetwork.py <path to folder containing Formaldehyde_XL_Analyzer outouts like \"F:\20210118_8samples\QE\" >") pathFiles = Path(sys.argv[1]) pathFiles = Path("F:\\20210118_8sa...
622c0a3cd04ffa64fc4f8cf85d0e3e89f19ba39b60d0796f864ec4d042dd5d34
Python
3,345
86
from copy import deepcopy from matplotlib import pyplot as plt import numpy as np def replace_name(name): if name == 'Sensory_relay': return "SR" elif name == 'KF_gate': return 'KFg' elif name == 'KF_phasic': return 'KFp' else: return name def get_short_name(param_to_v...
bc59bbb687f29ee89b8f1878604827ce85f0f734279ee000b75f0dd8c9eae5fc
Python
3,347
83
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # pyre-unsafe import torch from torch.nn import functional as F def squared_euclidean_distance_matrix(pts1: torch.Tensor, pts2: torch.Tensor) -> torch.Tensor: """ Get squared Euclidean Distance Matrix Computes pairwise squared Euclid...
6e47e3895776b4d51d4a55d20e5fcb7974b64b084c4b9e2291f305ea9aa1635f
Python
3,348
116
import argparse import pandas as pd from pathlib import Path import logging import os from create_pairs_from_alignments import create_genus_df from filter_comparisons import filter_comparisons def get_args(): parser = argparse.ArgumentParser() parser.add_argument( "--data-dir", "-d", ...
7ddc71b346ed9f17ba029e5ccc01194c903213a8e53dd5c1088f7af1079bf69e
Python
3,360
95
#%% import pandas as pd import bambi as bmb import pymc as pm import joblib from scipy.stats import zscore from os.path import join import arviz as az from plus_slurm import Job import sys sys.path.append('/mnt/obob/staff/fschmidt/cardiac_1_f') from utils.pymc_utils import coefficients2pcorrs #%% #a seed for repr...
e21e000ea0d80c2854533f4b3123099e8d1a28f171c19be153b0482983ad764b
Python
3,362
101
"""MolGpKa protonation backend tests. Locks in the reviewer's litmus case: piperazine at pH 7.4 must return the mono-cation (+1), which requires the iterative titration protocol (naive per-site Henderson-Hasselbalch would return +2). """ from __future__ import annotations import pytest torch = pytest.importorskip("...
6313f7ef0e26c78625029496a688217edb7ef073f08d2766804762f54e490c3a
Python
3,363
119
""" author:CBJ """ import sys from pathlib import Path import logging import pandas as pd import numpy as np PROJECT_ROOT = Path(__file__).parent.parent sys.path.insert(0, str(PROJECT_ROOT)) from src.utils import get_fwi_grade logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s...
66a16ae5a872e9d00c93c166aa148cbd66bcbcca3f685e386c1726fb0b059adf
Python
3,365
93
import DeepLINK as dl import numpy as np import keras from keras.layers import Dense from keras.models import Sequential from pairwise_connected_layer import PairwiseConnected import pandas as pd from keras.callbacks import EarlyStopping from sklearn.linear_model import LogisticRegressionCV dataset = ['Zeller_CRC'] d...
54c8e6a7d148d31940ff081e5ee04aee2ea3cc4002477db13d49aa216dfdd5fc
Python
3,366
123
# This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe import functools import importlib import logging from datetime import datetime from typing import Callable, Optional import click def import_thing(import_string: str): """Obtain an ob...
64f1f188d26edc5ef03431ea86b1b7235e9a9d1bafa6ced2f89671c45d5c1be6
Python
3,366
109
#!/usr/bin/env python3 # # Copyright (c) 2019 10X Genomics, Inc. All rights reserved. # """Tool for converting feature-barcode matrices from sparse format to dense. CSV format, for use by external programs. The commands below should be preceded by '{cmd}': Usage: mat2csv <input_path> <output_csv> [--genome=GENO...
8161419878bfcbecf969bf1b32dfd85ec813993d2d4b1318069bc4d7afa6f199
Python
3,369
94
import pandas as pd import os from WORC.addexceptions import WORCKeyError # All standard texture features accepted texture_features = ['GLCM', 'GLDZM', 'GLRLM', 'GLSZM', 'NGLDM', 'NGTDM'] def convert_radiomix_features(input_file, output_folder): ''' Convert .xlsx from RadiomiX to WORC compatible .hdf5 format...
c3d08ce95a9a035fa3cd66c9c8dc55487dd70f29675117e444d2c2fd958e2d0b
Python
3,369
114
import numpy as np from stabl import data from stabl.multi_omic_pipelines import multi_omic_stabl_cv from sklearn.model_selection import RepeatedStratifiedKFold, GroupShuffleSplit, GridSearchCV from sklearn.linear_model import LogisticRegression from stabl.stabl import Stabl from stabl.adaptive import ALogitLasso from ...
e18ecf522d58e9b24eeaec5b19f60923a10c79e899eb5c8303e045a3b9c5dfea
Python
3,370
85
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # pyre-unsafe from typing import Any, List import torch from torch.nn import functional as F from detectron2.config import CfgNode from detectron2.structures import Instances from .utils import resample_data class SegmentationLoss: """ ...
6d400f633d5b2033597eb36434cd8f7397145b468500b6c88b0f38d09b372a95
Python
3,373
103
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # pyre-unsafe from .catalog import MeshInfo, register_meshes DENSEPOSE_MESHES_DIR = "https://dl.fbaipublicfiles.com/densepose/meshes/" MESHES = [ MeshInfo( name="smpl_27554", data="smpl_27554.pkl", geodists="geodists/...
7519a549450309bdc26803a3fb0dbcab125ec95bd5322684478d0cad75d08d11
Python
3,375
92
#!/bin/python """ Script for registering and processing microglia ASAP snRNA-seq samples for Amygdala (AMY). Workflow steps: 1. Load the region-specific sample sheet and post-QC samples. 2. Filter samples to exclude non-microglia samples (e.g., "AA_ASAP111"). 3. Register samples with the trusTEr `Experiment` object. 4...
badd1a4ffb5d0a1f3695c0586631e3c2c581090dab6c20d6a17bdaf1afbbff87
Python
3,376
77
# 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 openff.units import unit from openfe.protocols.restraint_utils.geometry.flatbottom import ( FlatBottomDistanceGeometry, get_flatbottom_di...
1e72849487866ad9f65f3dd496f812b5d08114d75326f96c88e6707fb767995e
Python
3,378
107
#%% 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...
6a8c1bcef9fb5d56cd68343a65c6bca734d27cf2305c5137dea69ff198941f7a
Python
3,378
94
# 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 pytest from numpy.testing import assert_, assert_allclose from openff.utilities import skip_if_missing from openfe.setup import perses_scorers from ....utils.sile...
307517d88f70e96571ecca0ee304eae01159831c30f9dadf8727086bd672c1ed
Python
3,383
96
""" Boltzmann Wealth Model ===================== A simple model of wealth distribution based on the Boltzmann-Gibbs distribution. Agents move randomly on a grid, giving one unit of wealth to a random neighbor when they occupy the same cell. """ from mesa import Model from mesa.datacollection import DataCollector from...
fb1975ce17a6e1de9de94a7a0d545f5c280b4c3d5fb95715b2481422e2fd7045
Python
3,384
100
# Copyright (c) Facebook, Inc. and its affiliates. # pyre-unsafe from dataclasses import dataclass from typing import Any, Callable, Dict, List, Optional from detectron2.structures import Instances ModelOutput = Dict[str, Any] SampledData = Dict[str, Any] @dataclass class _Sampler: """ Sampler registry en...
fd29e62a1b0bff11407fcae846fbbcc309f8afa48efb42a5be4297dbb624739a
Python
3,385
75
# python proteinGroupsCombine.py D:\TMPDIR\mqpar.xml_20250403_135936 4 12 # D:\TMPDIR\mqpar.xml_20250403_135936 is output of mqrun.bat # %%setup #python -m pip install pandas seaborn pathlib supervenn import sys from pathlib import Path # %% read if len(sys.argv) != 4: sys.exit("\n\nREQUIRED: pandas, seaborn, supervenn...
7dde1849c7fed559dea05cc56acdd8a17d347a2a02b8ee0f782eb0b0c67c902f
Python
3,392
87
import numpy as np import torch import pandas as pd from torch.utils.data import Dataset class LFPDataset(Dataset): def __init__(self, cfg, aligned_data, step_onset_texture, step_onset_LD, val_idx, validation=False): """ Args: cfg: config file aligned_data: aligned lfp data ...
f700e4c1d36b80203a7f11162bb6fce3ebbfc49037559521fd26dcda59f8294f
Python
3,394
106
#!/usr/bin/env python # # Copyright (c) 2017 10X Genomics, Inc. All rights reserved. # import json import os import h5py as h5 import cellranger.cr_io as cr_io import cellranger.hdf5 as cr_h5 __MRO__ = """ stage SUMMARIZE_ANALYSIS( in h5 matrix_h5, in h5 pca_h5, in h5 clustering_h5, in ...
4551cbaa5af87580238c7b28f3ddaa551043d782bcca350041a10dad7dd8b713
Python
3,397
86
import multiprocessing import shutil 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 from skimage import io from acvl_utils.morphology.morphology_helper import generic_filter_co...
9bc94838d4316e638f2a4c22fbf06b8ea67fa1aae18bab75280d756f7ef7e639
Python
3,401
122
import tensorflow as tf print(tf.__version__) #https://stackoverflow.com/a/40219528/1137129 tf.random.set_seed(42) #vecs=tf.random.uniform(shape=[n],minval=0,maxval=n,dtype=tf.dtypes.int64) #https://laurentlessard.com/bookproofs/mismatched-socks/ n=1000 j=0 k=[] while j < n: vecs=tf.range(0,j, delta=1, dtype=tf.dty...
52db1d61478fbfcebeb51a57b5897b979218519e0703790cf05f0168dacf0952
Python
3,404
74
from abc import abstractmethod from torch import Tensor, nn from chemprop.data import BatchMolGraph from chemprop.nn.hparams import HasHParams class MessagePassing(nn.Module, HasHParams): """A :class:`MessagePassing` module encodes a batch of molecular graphs using message passing to learn vertex-level hidd...
d4a46bc4320abbac66750b66aacd5e64fd8cd4555b45848ee9f72654f37b257d
Python
3,406
118
import warnings import torch import numpy as np import pandas as pd from torch import nn from torch.utils.data import DataLoader from torch.utils.data import Dataset from torch.autograd import Variable import numpy as np import pandas as pd from sklearn.metrics import mean_absolute_error,mean_squared_error,r2_score imp...
bbecd534f24d3c15ab004b325248605897ea1aa37bd8f873140fc11e3be1fbd3
Python
3,410
98
#!/usr/bin/python3 ################################################################################## # # MIT License # # Copyright (c) 2025 Kevin Rockenbach, Agnieszka Golicz # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "So...
0f606e0248f37757fa96196a5fe4cb72e9b6492791c665ba554739a2800b7cbb
Python
3,411
103
from pathlib import Path import pytest from unittest.mock import MagicMock import tempfile from WORC.validators.preflightcheck import InvalidLabelsValidator import WORC.addexceptions as ae """ Test to see what happens if a valid configuration is given to the InvalidLabelsValidator. Under normal circumstances this sh...
67ffae59a16a9205592e47f55eb4fd8b80fa56c6dde1c6aeda854c931afe4126
Python
3,411
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...
9c71cc2ad9f130e466a93a1f9e7849cee6a58c50f5ff1d7fa657766ab15a2497
Python
3,412
68
#!pip3 install pandas --user #!pip3 install pathlib --user import sys from pathlib import Path if len(sys.argv)!=2: sys.exit("REQUIRED: pandas, pathlib\nTested with Python 3.9\n","USAGE: \npython dePepFP.py <path to folder containing psm.tsv file(s) like \"Z:/20220319_IP-UCHL1_MN/\" > <Hyperscore threshold for filet...
b54b6dc1b153f1113b2322c780d297c367a30a3c480c281df90c6e07439d057d
Python
3,412
114
import argparse import sys from dna_interpolation import DNAInterpolatorWrapper from interpolated_formatter import InterpolatedDataFormatter def get_args(): parser = argparse.ArgumentParser() parser.add_argument( "--records-file", "-r", help="Master table of records (required).", ...
91e04670211b52bdc008ac5f240a36835acfcfe22b4d36d2c64f81c5d5c7613a
Python
3,413
74
import torch import os,time from torch import nn import torch.nn.functional as F import torch.optim as optim import numpy as np from tqdm import tqdm from torch.utils.data import Dataset from torch.utils.data import DataLoader import random import argparse import running_function if __name__=='__main__': parser = ...
a529ef2b18a87667bbf646e8ff7c4245ec128f9fb654171ea5a510797bda7231
Python
3,418
78
#!/usr/bin/env python # Copyright 2017-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...
2475fef1e0291548a75e22c8595840ee0a3b36dcafa3a906c789b67d62a36cb5
Python
3,421
93
import torch from torch import nn class BabyUnet(nn.Module): """ Neural network for semantic image segmentation U-Net (PyTorch), with only three max-pooling layers Reference: Falk, T. et al. U-Net: deep learning for cell counting, detection, and morphometry. Nat Methods 16, 67–70 (2019). Paramet...
0e5b0b87b1cc35de765d8b75572594503ffe6eea4db93be9f004869c8322107c
Python
3,424
83
#!/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...
63dbf7f7743fb6d59d824656007f9077b7692adbfb1eea6f3b0d02db3855eabe
Python
3,425
87
from argparse import Namespace import pytest from chemprop.cli.train import _process_ffn_hidden_dims @pytest.fixture def base_args(): return Namespace( ffn_hidden_dim=[300], ffn_num_layers=1, atom_ffn_hidden_dim=[300], atom_ffn_num_layers=1, bond_ffn_hidden_dim=[300], ...
737c0363f5a4fc78c6c87a8114e200c7d634e488f332548a29453bb5be2acdbc
Python
3,433
85
############################################################################ # Copyright (c) 2022-2026 University of Helsinki # All Rights Reserved # See file LICENSE for details. ############################################################################ import logging import os import re import shutil from collect...
a70704957bedda56d5a886b009f350b58c0e76b208b72fdef88938507b9d6a2c
Python
3,446
118
from composer.models import ComposerModel import logging from torchmetrics import Metric import torch import torch.nn as nn import torch.nn.functional as F from transformers import PreTrainedTokenizer from metrics_and_callbacks import BiologicalDistance class GeneticDistanceModel(ComposerModel): def __init__( ...
4caa8368fc359fe2c76345d8138e234a1882ecc1b46b6ff2c79d1291db41181e
Python
3,450
87
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import unittest from densepose.data.datasets.builtin import COCO_DATASETS, DENSEPOSE_ANNOTATIONS_DIR, LVIS_DATASETS from densepose.data.datasets.coco import load_coco_json from densepose.data.datasets.lvis import load_lvis_json from densepose.data...
77fdb031f6850f17c5e377cdf458b21caacfce7b1a1ca1b2ffce6153a06e450a
Python
3,450
90
import torch from torch.utils.data import Dataset import logging class ProcessedDataset(Dataset): """ Data structure for a pre-processed cormorant dataset. Extends PyTorch Dataset. Parameters ---------- data : dict Dictionary of arrays containing molecular properties. included_speci...
96a857b2849c3ea3e5f5c1da80e7a7575c2aaab25a70b337ed0349ea722210b9
Python
3,450
89
############################################################################ # Copyright (c) 2022-2026 University of Helsinki # # All Rights Reserved # See file LICENSE for details. ############################################################################ """Unit tests for the shared polyA / TSS peak detector (term...
e6efa8cb0ea6a75f237a5909c79a8e39e54233f86cd7ee89c904305d9974c0bb
Python
3,458
110
from __future__ import annotations from dataclasses import dataclass, field from typing import Any @dataclass(slots=True) class MolecularRecord: access_code: str smiles: str source_row: int metadata: dict[str, Any] = field(default_factory=dict) @dataclass(slots=True) class RunReport: input_file...
a04be132206b414a7f0f67f545be9535305777e9519fab8044756660a2061cc4
Python
3,460
108
import numpy as np from pynestml.codegeneration.nest_code_generator_utils import NESTCodeGeneratorUtils def generate_code(neuron_model, synapse_model, sname, target_path, force_syn_vars=None): codegen_opts = {"delay_variable": {sname: "d"}, "weight_variable": {sname: "w"}} if force_syn_va...
da98f9da87b7b91ea91ac49b11db45d04bc662664cafe54f58b80c01a20383b9
Python
3,467
100
""" Neuron "Barcodes" ================= <!-- difficulty: intermediate --> Visualize a neuron's branching pattern as a topological "barcode". This technique turns a neuron's branching pattern into a unique "barcode" using topological sorting, based on [Cuntz et al. (2010) :octicons-link-external-16:](https://journals....
bb5688579d3675789b7d0cae39601179e774429548e3687e09da119fdde26899
Python
3,469
76
# Copyright 2021 HIP Applied Computer Vision Lab, 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...
ef8575abdfea3aecb01d98219f02d08f299c79ea43a2b054651661f5bfaf1b53
Python
3,472
124
# Copyright (c) Facebook, Inc. and its affiliates. import os import torch from detectron2.config import get_cfg from detectron2.engine import default_setup from detectron2.modeling import build_model from densepose import add_densepose_config _BASE_CONFIG_DIR = "configs" _EVOLUTION_CONFIG_SUB_DIR = "evolution" _HRN...
80f3b9684439165f4e5b3356ce554dedcfb2a3c2ccccd1e201f6460f3029cd78
Python
3,473
76
from nnunetv2.training.loss.compound_losses import DC_and_topk_loss from nnunetv2.training.loss.deep_supervision import DeepSupervisionWrapper from nnunetv2.training.nnUNetTrainer.nnUNetTrainer import nnUNetTrainer import numpy as np from nnunetv2.training.loss.robust_ce_loss import TopKLoss class nnUNetTrainerTopk10...
53848f4137852d817dafd6312d3dda04e2e8428513fa38696a590d114758e6a1
Python
3,474
100
from __future__ import annotations import argparse 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 to keep the Windows DLL load order deterministic. import src.utils.torc...
64c11d484a105cf97d9d7d4669e1b1b1eb33e75fe2b963ae5aebeae20f408fdb
Python
3,474
101
from sklearn.cluster import KMeans import ot import pandas as pd from sklearn.neighbors import NearestNeighbors import numpy as np import numba @numba.njit("f4(f4[:], f4[:])") def euclid_dist(t1, t2): sum = 0 for i in range(t1.shape[0]): sum += (t1[i] - t2[i]) ** 2 return np.sqrt(sum) # 1003 @num...
71bc84aa57c2c42d6d4c1b28b9fae77ad98dbee74b983a4a177cfea19b932e54
Python
3,474
129
"""Metric computation for model evaluation. Provides functions for classification metrics (accuracy, balanced accuracy, precision, recall, F1, AUROC, AUPRC), regression metrics (MAE, RMSE, R²), and calibration analysis (calibration curve, ECE). """ from typing import Dict, Optional, Tuple import numpy as np from skle...
c04562bdb8c181990770578dcd91a2c4b7cdc195f95edce28033cbe24cea412f
Python
3,477
98
# Copyright (c) Facebook, Inc. and its affiliates. import os import unittest import tempfile from itertools import count from detectron2.config import LazyConfig, LazyCall as L from omegaconf import DictConfig class TestLazyPythonConfig(unittest.TestCase): def setUp(self): self.curr_dir = os.path.dirname...
8cfea7f8f7085144a76d1054fcce58420c21d958a405bc1d82ad3e2098122f9f
Python
3,478
102
"""SessionResponses — top-level container for a session's response data.""" from .unit_response import UnitResponse from .window_config import WindowConfig from spikeinterface import full as si from pathlib import Path class SessionResponses: def __init__(self, session_path, sorting_analyzer_path, trial_df, ...
1672c5b263b8ed400326f5122f684e0d42b3d8c24ecaf8bab0f274a68d688a8c
Python
3,480
109
"""Abstract base class for visualization backends in Mesa. This module provides the foundational interface for implementing various visualization backends for Mesa agent-based models. """ from abc import ABC, abstractmethod import mesa from mesa.discrete_space import ( DiscreteSpace, OrthogonalMooreGrid, ...
ceb217c986de6db6928e8b0732d32542774acc5702e75402b34fd1c709d3d027
Python
3,483
121
# --- Python 标准库 --- import gc import random import warnings # --- 第三方核心科学计算库 --- import numpy as np import pandas as pd # --- 生物信息学与数据分析库 --- import anndata as ad # --- 深度学习库 (PyTorch) --- import torch import torch.nn as nn import torch.nn.functional as F # --- 脚本级别的设置 --- warnings.filterwarnings("ignore") gc.col...
8f0e3a13870b5a77f9beaf76f51b3a9dcc2284626eb58eec94900e694e90f2aa
Python
3,484
88
from typing import Any, Callable, List import numpy as np import numpy.typing as npt from hsnn.core.types import SpikeTrains from hsnn import ops from .patterns import SpatioTemporalPattern, PolyChronGroup __all__ = ["generate_poisson_train", "generate_uniform_train", "generate_poisson_pattern"...
6b282d755bf1443d793154e7159b70d43c40d02ee8e5ec27cf3bf94b3f8d91e9
Python
3,488
118
#!/usr/bin/env python # # Copyright (c) 2022 10X Genomics, Inc. All rights reserved. # """K-means clustering.""" from __future__ import annotations from typing import NamedTuple import numpy as np import scipy.spatial.distance as sp_dist import sklearn.cluster as sk_cluster import cellranger.analysis.clustering as ...
d39554157c71184a75e7ab0fa598cc88a6027c3e8ae0ceadb0b1ab269eb9b344
Python
3,490
138
from typing import List, Tuple, Dict import pytest import pandas as pd import numpy as np import navis from navis.connectivity import NeuronConnector from navis import NeuronList def test_neuron_connector(): nrns = [] for n in navis.example_neurons(): n.name = f"{n.name}_{n.id}" nrns.append(...
8b2dcda602bf42670763824ce50d6d1789face117998b35b236f53f867e5dc18
Python
3,492
146
"""Tests for model.py.""" import numpy as np from mesa.agent import Agent, AgentSet from mesa.model import Model def test_model_set_up(): """Test Model initialization.""" model = Model() assert model.running is True assert model.time == 0.0 model.step() assert model.time == 1.0 def test_m...
d4cc3d975057a8e9992def18008457f369d4985845fe955326eeb7f95616502a
Python
3,498
118
import gufe import pytest from gufe import ChemicalSystem, SolventComponent from gufe.tests.test_protocol import DummyProtocol from openff.units import unit @pytest.fixture def solv_comp(): yield SolventComponent(positive_ion="K", negative_ion="Cl", ion_concentration=0.0 * unit.molar) @pytest.fixture def solvat...
3f74e32b8c820e1ea95f8abfce7dd8e5a5ce806852fabefc99f48e01879a4887
Python
3,501
102
""" Aggregation of voxel features at vertex locations """ __author__ = "Fabi Bongratz" __email__ = "fabi.bongratz@gmail.com" from typing import Tuple import numpy as np import torch import torch.nn.functional as F from pytorch3d.ops import knn_points from utils.utils import int_to_binlist from logger import measur...
8e0db31f8285ca699e215055b777c23b4987da88ad763dfbfeaf48c3b2749c71
Python
3,501
107
import inspect from functools import wraps from typing import List, Optional, Tuple import torch import torch.nn.functional as F from loguru import logger def top_n_stoichiometry_combinations( logits: torch.Tensor, n: int = 5, class_labels: Optional[List[int]] = None, beam_width: int = 10, use_ra...
ba958ae6cff6b8e94e40bc978f1b34e24eb12ce306dba6a551378b559b505be4
Python
3,503
94
#@String(value="<html>This script retrieves nearest neighbor distances from a 2D/3D list of centroid<br>coordinates, calling another script to plot frequencies of calculated distances.<br>You will be prompted for input data in the next dialog prompt.", visibility="MESSAGE") info #@String(label="Column heading for X-coo...
1526bba9b8c45a11289fbd22e7fadbef6e41859bf1f8f4054c42b1aa750fd637
Python
3,512
86
#!/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 obt...
5ce87be1378c08382c39eb8a301e6c008bb1016e19f8f4d7d2a66a2322dc6107
Python
3,512
110
#%% 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...
8d17293268b80ea7be3362108ae158d2fa6cee75016b441ea3183c0600fb64dc
Python
3,515
102
# pynbs_parallel.py (Python 2.7) import os # Prevent BLAS/OpenMP oversubscription when using multiprocessing os.environ["OMP_NUM_THREADS"] = "1" os.environ["MKL_NUM_THREADS"] = "1" os.environ["OPENBLAS_NUM_THREADS"] = "1" os.environ["NUMEXPR_NUM_THREADS"] = "1" from pyNBS import data_import_tools as dit from pyNBS i...
9693eb89042820d611f4d69dbc43c8dcafb78fa9a126ac78338979c662e41b98
Python
3,527
107
# ruff: noqa: PLR2004 import json from pathlib import Path import pytest from snakebids.exceptions import RunError from snakebids.utils import output def dirlen(f: Path): return len([*f.iterdir()]) @pytest.fixture def fake_snakemake(tmp_path: Path): app1 = tmp_path / "app1" app1.mkdir() (app1 / "...
3791dd409536345dc1bd8b918142c74746de39d781e314b030a359e8131a8bee
Python
3,528
109
# 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...
f208bc7ed47b6a3dae45788a8153c8a08d1507977d7dcfed15200142c931aee0
Python
3,528
61
from nnunetv2.model_sharing.model_download import download_and_install_from_url from nnunetv2.model_sharing.model_export import export_pretrained_model from nnunetv2.model_sharing.model_import import install_model_from_zip_file def print_license_warning(): print('') print('####################################...
4ef0be0d7f9fc57adc0c332c8f9547f3af512fc79269f81fb3c4d7ccb500a4cc
Python
3,529
103
"""Custom visualization components.""" from __future__ import annotations from collections.abc import Callable from .altair_components import ( SpaceAltair, make_altair_plot_component, make_altair_space, ) from .matplotlib_components import ( SpaceMatplotlib, make_mpl_plot_component, make_mpl...
945061e029f54c590bfb24c8d900a82843174982ced53d841581b0508b57ba64
Python
3,530
117
# Run with streamlit run st_app.py import time import altair as alt import pandas as pd import streamlit as st from model import BoltzmannScenario, BoltzmannWealth model = st.title("Boltzman Wealth Model") num_agents = st.slider( "Choose how many agents to include in the model", min_value=1, max_value=10...
6d78c8b747d137ed256ee611a3257ee2b31feb7ac4c168ce91e8bc3517795692
Python
3,533
99
from pathlib import Path import matplotlib.pyplot as plt import numpy as np import torch import torchvision.transforms as transforms from .utils.activation_manager import ActivationManager from .utils.decomposition_handler import DecompositionHandler from .utils.pca import PCAHandler from .utils.ica import ICAHandler...
8a53e1a858b57bdaac6addedcf93d4c2c973aa440e3d7df618303f0d27daacde
Python
3,535
76
# Copyright (c) Facebook, Inc. and its affiliates. import unittest import torch from detectron2.structures import Boxes, BoxMode, Instances from densepose.modeling.losses.utils import ChartBasedAnnotationsAccumulator from densepose.structures import DensePoseDataRelative, DensePoseList image_shape = (100, 100) inst...
9fd9b25c7efbc35cdbb1f7f33e58a8ffc79add3dcec1e69d226cec89e1baf647
Python
3,544
168
#python codonusage.py CCDS_nucleotide.20221027.fna CCDS.20221027.txt import sys import csv file1 = sys.argv[1] file2 = sys.argv[2] ftout = f"{file1}.{file2}.aa.py.fasta" fcout = f"{file1}.{file2}.aa.py.txt" seqh = {} seqc = None val = {} cl = 3 c2a = { 'TTT': 'F', 'TTC': 'F', 'TTA': 'L', 'TTG': 'L', 'TCT'...
d9e1b8f397024321645ffe87da74c103cb2246388466309951614bdf46bdfa4e
Python
3,544
97
#!/usr/bin/env python # Crop T2-weighted images to a usable FOV # # Usage: crop_T2.py -i <input_dir> -x_min <x_min> -x_max <x_max> -y_min <y_min> -y_max <y_max> -z_min <z_min> -z_max <z_max> -o <output_dir> from nipype.interfaces.fsl import ExtractROI import nibabel as nii import argparse import pathlib import subproc...
1eb8b16c6c3afea0066cb507b6f785b4b96c9616908ca203bb6f37c410a4bbb5
Python
3,545
96
# Copyright (c) Facebook, Inc. and its affiliates. # pyre-unsafe from typing import Any, Tuple, Type import torch class BaseConverter: """ Converter base class to be reused by various converters. Converter allows one to convert data from various source types to a particular destination type. Each so...
4ce606200e73bcffbe734d3a489ddc129f06f971967eb51b7518c5072f2d84b3
Python
3,545
100
# This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/gufe import abc import collections import json from typing import Dict, Tuple from gufe.storage.errors import ChangedExternalResourceError, MissingExternalResourceError from gufe.storage.externalre...
a41b0f369cf8f2b9cab2414b7faecc9bd022416e443ac83ba82036012cac136a
Python
3,554
64
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 def convert_amos_task2(amos_base_dir: str, nnunet_dataset_id: int = 219): """ AMOS doesn't say anything abo...
9b9a665cd6325ae3ca87b5cf181c544923e5a11f6aeda1f3ecb179c4571abfb7
Python
3,555
108
from __future__ import annotations import argparse import json import logging import subprocess as sp import tempfile from typing import Any import attr from snakebids import bidsapp from snakebids.exceptions import SnakebidsPluginError from snakebids.plugins.base import PluginBase from snakebids.utils.utils import ...
810d23af53f849d66b4ccc54eac928123d2236e2ca988feebb96385f487e275c
Python
3,557
98
from __future__ import annotations import itertools as it from argparse import ArgumentParser from collections.abc import Iterable from pathlib import Path import pytest from hypothesis import given from hypothesis import strategies as st from snakebids.exceptions import ConfigError from snakebids.plugins.bidsargs i...
f285dbe34e15a6d40a4aa013b83e7395bd6765aba3b2eef5daf18dd6d02d9046
Python
3,558
95
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.fpn import LastLevelMaxPool from detectron2.modeling.backbone import Bas...
1c78cbaab8e6f5bc203b5aa0d422361f6a0cf4a391fcff2311c40065e69eccb1
Python
3,566
102
# Run a simulation in OpenMM with a trained force field import MDAnalysis as mda from openff.toolkit import Topology from openff.toolkit.topology import Molecule import networkx as nx from openmm.app import ForceField, PDBFile, PME, CutoffPeriodic, HBonds, Simulation, StateDataReporter, DCDReporter, CheckpointReporter...
d2b2c5ecb747147593e18c2d0ceb5bfa3fe77c582362bb1aee371d49ea7d1b8c
Python
3,573
78
import argparse from model_utils import build_model, adapt_input_model, compile_runner from dataset import load_data def train(images_path, masks_path, model_path, model_str, encoder_str, weights, in_channels, batch_size, epochs, learning_rate, fp16): # Load data and prepare loaders loade...
71239e74c19ab1d40836e025753c43c27dce1e94812018ddd84616de6075508c
Python
3,574
102
# Run a simulation in OpenMM with a trained force field import MDAnalysis as mda from openff.toolkit import Topology from openff.toolkit.topology import Molecule import networkx as nx from openmm.app import ForceField, PDBFile, PME, CutoffPeriodic, HBonds, Simulation, StateDataReporter, DCDReporter, CheckpointReporter...
ad93ca652c1a772154fd9360505cbbc2638d8eb8d7c1e9ed2e6e17988ce81695
Python
3,574
125
# flake8: noqa # Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup --------------------------------------------------------...
5714cf430329ec81cf81fb409025535d0df59b64c1fb814cbab51be1ff639b97
Python
3,576
81
### the network performance without variable selection (for comparison with the performance using SurvNet) import tensorflow as tf import numpy as np import math def IN(seed, train_X,train_Y,val_X,val_Y,test_X,test_Y, n_classes,n_hidden1,n_hidden2, learning_rate,epochs,batch_size,num_batches,d...
1a050616ca910a33741197f1626ee3d66f0a67a4e5647a0abeaafb0178cd20cb
Python
3,579
120
# -*- coding: utf-8 -*- """Functions for working with CIVET data.""" import os import numpy as np from neuromaps.points import get_shared_triangles, which_triangle def read_civet_surf(fname): """ Read a CIVET-style .obj geometry file. Parameters ---------- fname : str or os.PathLike Fi...
43ea20c7446705303105f32087dc912db6d00477d1e6e087179fdff447d5c84e
Python
3,583
98
from dataclasses import dataclass from typing import Optional import torch import torch.nn as nn from .activation_manager import ActivationManager from .decomposition_handler import DecompositionHandler @dataclass class AttackParams: alpha: float beta: float = 0.01 num_iterations: int = 50 class PGDAt...
25600c7b21780e225600d6b1ffa4417197a441db074e683d30c8836c1dc16553
Python
3,584
119
import torch.nn as nn import torch from torch.nn.utils.parametrizations import orthogonal import torch.nn.functional as F class GraphConv(nn.Module): def __init__(self, in_features, out_features): super(GraphConv, self).__init__() self.in_features = in_features self.out_features = out_featu...
b43b6f64254032c053b15de8fd4abb205f25726f402ef9ce468aee61256cfa40
Python
3,585
119
from __future__ import annotations from collections.abc import Iterator from enum import Enum, auto from typing import TypeAlias import importlib_resources as impr import more_itertools as itx from typing_extensions import NotRequired, TypedDict from snakebids.io.yaml import get_yaml_io from snakebids.paths import r...
bbd13c5965686d45b0ded667c34dad885eb05d9691e5a622574af6aba0d159f0
Python
3,590
125
"""Fig 4F: Longitudinal rasters of all modulated units across sessions. All modulated units sorted by cortical depth for ICMS92, stim condition (ch 11, 4 uA), at weeks 0, 1, 2, 3, 4. Spikes shown from -700 to 3400 ms. Usage: python python/fig4/longitudinal_rasters.py """ import sys from pathlib import Path sys.pa...