sha256 stringlengths 64 64 | language stringclasses 27
values | size int32 1 491k | lines int32 1 21.8k | content stringlengths 1 200k |
|---|---|---|---|---|
21b8e817e454558ec6ac3dbd12a068efd82f3fe3fbf4fd0f5e0bc2341a5f7c3e | Python | 1,657 | 48 | # Python05-3.py
# IJ BAR: https://github.com/tferr/Scripts#scripts
####################################################
# 5.3 Scripting ImageJ: Creating an empty image (III)
####################################################
# Previously, we assembled all the code required to
# generate a new image. This is how it l... |
c80536a9b1f1ae7dde115e58587dca644564c289495c6d84c04aad9d51e96fe6 | Python | 1,657 | 47 | from fvcore.common.param_scheduler import MultiStepParamScheduler
from detectron2.config import LazyCall as L
from detectron2.solver import WarmupParamScheduler
def default_X_scheduler(num_X):
"""
Returns the config for a default multi-step LR scheduler such as "1x", "3x",
commonly referred to in papers,... |
7342124dcb58180d9081d461da8adeaaaf65fffaf580c144efd5cd674452503c | Python | 1,658 | 50 | # Copyright (c) Facebook, Inc. and its affiliates.
import logging
import unittest
from detectron2 import model_zoo
from detectron2.config import instantiate
from detectron2.modeling import FPN, GeneralizedRCNN
logger = logging.getLogger(__name__)
class TestModelZoo(unittest.TestCase):
def test_get_returns_model... |
b1a9186d88c7337d98f289811332e11bbb4fe75b83e0bca4a83011c87d6cf8f9 | Python | 1,658 | 55 | import copy
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
"""cnn"""
class CNN(nn.Module):
def __init__(self, batch_size=128, embedding_size=20, num_tokens=100, num_filters=100, filter_sizes=(2, 3, 4), num_classes=2, num_heads=4):
super(CNN, self).__init__()
... |
a1a15da84eb11a6fdad2b30394609eec3abdf3ebf8142019ff87a0baf31278d5 | Python | 1,660 | 44 | import os
import argparse
import urllib.request
NEWS_DATASETS = {
"PTB": {"README": "README",
"url": "https://catalog.ldc.upenn.edu/LDC95T7"},
"BLLIP": {"README": "README.1st",
"url": "https://catalog.ldc.upenn.edu/LDC2000T43"}
}
NEW... |
49f6ed1b5933aeb68034f64456e862dead0b34d7350a1070b6dc90ffc19ff674 | Python | 1,661 | 49 | import os
from importlib import resources
import click
import pytest
import openfe
from openfe import SmallMoleculeComponent
from openfecli.parameters.molecules import load_molecules
def test_get_dir_molecules_sdf():
with resources.as_file(resources.files("openfe.tests.data.serialization")) as dir_path:
... |
0d7f902103dd1079a85ab3a1a24b301c30974132762afae6a38dee4193f55ac6 | Python | 1,663 | 42 | # Copyright (c) Facebook, Inc. and its affiliates.
import unittest
from typing import List
import torch
from detectron2.config import get_cfg
from detectron2.modeling.matcher import Matcher
class TestMatcher(unittest.TestCase):
def test_scriptability(self):
cfg = get_cfg()
anchor_matcher = Matche... |
1b73f780fab9480b4d1253af723da4152bed7953c857a2acee3b646190d3c434 | Python | 1,665 | 39 | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 30 10:51:23 2023
@author: walte
"""
import nibabel as nib
import numpy as np
import scipy.ndimage
def vol2vol(mov_path, targ_path, out_path, interp='nearest'):
# Load the input and target volumes
mov_img = nib.load(mov_path)
targ_img = nib.load(targ_... |
5906f24d3e2796742f90d1d3b38ca7953bd229e43612f7d6ec970f51ff91e59d | Python | 1,669 | 47 | from mesa.discrete_space import CellAgent
class SchellingAgent(CellAgent):
"""Schelling segregation agent."""
def __init__(
self, model, cell, agent_type: int, homophily: float = 0.4, radius: int = 1
) -> None:
"""Create a new Schelling agent.
Args:
model: The model in... |
d7cd375a627e410d8bd82c70611edcf9e2ce7cfb06a92248c7e9947d6effedbd | Python | 1,672 | 50 | # -*- coding: utf-8 -*-
# Copyright (c) Facebook, Inc. and its affiliates.
from detectron2.config import CfgNode as CN
def add_tensormask_config(cfg):
"""
Add config for TensorMask.
"""
cfg.MODEL.TENSOR_MASK = CN()
# Anchor parameters
cfg.MODEL.TENSOR_MASK.IN_FEATURES = ["p2", "p3", "p4", "p... |
5d9d92af52b8f496d8cdda21ae00d985a131e64fa16e9c9b99c0bc0d5cf635bb | Python | 1,673 | 46 | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from config import INPUT_PATH
from support.config import COUNTRIES
from support.method_distribution import method_distribution
def prepare_data(data=None) -> pd.DataFrame:
if data is None:
data = pd.read_csv(INPUT_PATH, low_memory=Fal... |
f534de187443c700a0f839ce3d0b0174a29b69dbbb36804d1737e31734b31b74 | Python | 1,673 | 45 | from setuptools import setup
def readme():
with open('README.md') as f:
return f.read()
setup(name='neuroHarmonize',
version='2.5.1',
description='Harmonization tools for multi-center neuroimaging studies.',
long_description=readme(),
long_description_content_type='text/markdown',
... |
ea7aa0a3f03e045629cfbcbe17c17c9a1cff89add5746d22d5b173f1d23592c6 | Python | 1,675 | 55 | import numpy as np
import torch
from torch.autograd import Variable
import matplotlib.pyplot as plt
import argparse
import lpips
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--ref_path', type=str, default='./imgs/ex_ref.png')
parser.add_argument('--pred_... |
59e0c0ecb46952c4d45d97950814eba5db6145012b64b7ed55e9abd4d17acff7 | Python | 1,678 | 42 | from typing import Sequence
from ._base import AbstractSNN
from ..groups import group_registry, GroupFactory
from ..layer import stimulus_registry, SpatialLayer
from ...config import ModelParams
from ...definitions import Projection
__all__ = ["SpatialNet"]
_TOPOLOGY_ID = 'spatial'
class SpatialNet(AbstractSNN):
... |
60604b6d6991a37b02f2e5bda4355b1f23fefd8ea77ebd81528c454e1f09d23b | Python | 1,682 | 63 | from typing import Dict, List
CANONICAL_ALPHABET = [
'A', 'C', 'D', 'E', 'F',
'G', 'H', 'I', 'K', 'L',
'M', 'N', 'P', 'Q', 'R',
'S', 'T', 'V', 'W', 'Y','X'
]
SPECIAL_SYMBOLS = ["<unk>", "<pad>", "<sos>", "<eos>"]
VOCAB = SPECIAL_SYMBOLS + CANONICAL_ALPHABET
def get_id2token() -> Dict[int, str]:
... |
9ea1bcafc592a465ad4da9a122ea59bf6567294d881802270c6d83317d6cf3ff | Python | 1,682 | 52 | import logging
from os import PathLike
from pathlib import Path
from typing import Generator, Sequence, Tuple, Union
import numpy as np
import pandas as pd
from skimage.measure import regionprops_table
from .. import io
logger = logging.getLogger(__name__)
def measure_regionprops(
img: np.ndarray, mask: np.nda... |
f8930da88658cae9c1bb987ff28076d53452c2748fafd17f44b5a51ba3698400 | Python | 1,682 | 58 | """ Brummer's Method
brummer1993automatic,
title={Automatic detection of brain contours in MRI data sets},
author={Brummer, Marijn E and Mersereau, Russell M and Eisner, Robert L and Lewine, Richard RJ},
journal={IEEE Transactions on medical imaging},
volume={12},
number={2},
pages={153--166},
year={1993},
publisher={I... |
981eaddc416db41be371956e32d783ee4cf03ba5dfeb25334d9c8bc69468564d | Python | 1,684 | 61 | import numpy as np
import matplotlib.pyplot as plt
def from0to1(arr):
arr = np.asanyarray(arr)
arr[np.isclose(arr,0)] = 1
return arr
def subps(nrows,ncols,rowsz=3,colsz=4,d3=False,axlist=False):
if d3:
f = plt.figure(figsize=(ncols*colsz,nrows*rowsz))
axes = [[f.add_subplot(nrows,ncols... |
d54d6f434198cbc5c120dcd6e432829566ffbf106cfa531c1eed4a17b1549632 | Python | 1,685 | 44 | #!/usr/bin/env python3
"""Build relative train/validation/test HDF5 manifests for portable configs."""
from __future__ import annotations
import argparse
import json
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__)
ap.... |
cf93846e2c77e7686f677e54ba3f73a88559335ddaf9490bdf6961b5a67bf8ce | Python | 1,689 | 39 | from dataclasses import dataclass, field
from typing import List
import torch
from .activation_manager import ActivationManager
from .decomposition_handler import DecompositionHandler
from .condition import Condition
@dataclass
class AttackResult:
original_image: torch.Tensor
original_loss: float
pertur... |
74016f02bfaf73686ab9369c718cf41e294b5b9e8d07a484de49c98d8137030c | Python | 1,691 | 48 | #!/usr/bin/env python
#
# Copyright (c) 2026 10x Genomics, Inc. All rights reserved.
#
"""Compute segmentation plots for Visium HD data."""
import json
import os
__MRO__ = """
stage VALIDATE_SEGMENTATION_DIRECTORY(
in path segmented_outputs,
out ValidateSegmentationOutputs validate_segment... |
7de0ee9e3a9e685c0ab6a45144006cc5599da2bdedb51fefca3eac485c887fdf | Python | 1,691 | 60 | #!/usr/bin/env python
#
# Copyright (c) 2016 10X Genomics, Inc. All rights reserved.
#
from __future__ import annotations
# Performance logging
import resource
import time
class LogPerf:
"""Print before/after maxrss and elapsed time for code blocks to stdout."""
def __init__(self, note) -> None:
se... |
ee1dc191aa48d68e026e88e580427cafa7e0f3fcf11feae3987111513d9022fd | Python | 1,691 | 58 | #import tensorflow as tf
import numpy as np
import math
import random
from sklearn import preprocessing
seed=1 # set a seed
np.random.seed(seed)
whole_X=np.random.uniform(-1,1,(10000,784))
n=whole_X.shape[0]
p0=whole_X.shape[1] # the number of original variables
random.seed(seed)
art=np.array(random.sample(range(p0)... |
6ca823041f66c7094ebb60a7a78ebdc4f105916711af08e72b23cf555da5fed9 | Python | 1,695 | 43 | # 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... |
2b2d8cff6f6f5219f205d7452a8382840f5cec58dd4615ebe41277c32937e12e | Python | 1,696 | 73 | from mesa.examples.basic.conways_game_of_life.model import ConwaysGameOfLife
from mesa.visualization import (
SolaraViz,
SpaceRenderer,
)
from mesa.visualization.components import AgentPortrayalStyle
def agent_portrayal(agent):
return AgentPortrayalStyle(
color="white" if agent.state == 0 else "bl... |
0794cb0300f1e083a450048241231a750c1ef3e5e780ce16c864a06f201b673d | Python | 1,702 | 51 | # Copyright 2011-2014 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 obtain a copy of the Licen... |
100c7828182627daa2493c35c0850a78dcc0b392b037564046de73ee492b0369 | Python | 1,703 | 57 | import numpy as np
import torch.nn as nn
import torch
import torch.nn.init as init
from sklearn.metrics import pairwise_distances
def create_activation(name):
if name == "relu":
return nn.ReLU()
elif name == "gelu":
return nn.GELU()
elif name == "prelu":
return nn.PReLU()
elif na... |
22801cb765425a495881c29f500931c70e3addb2f4caec40693874d9b0c3b630 | Python | 1,710 | 51 | from detectron2.config import LazyCall as L
from detectron2.data.detection_utils import get_fed_loss_cls_weights
from detectron2.layers import ShapeSpec
from detectron2.modeling.box_regression import Box2BoxTransform
from detectron2.modeling.matcher import Matcher
from detectron2.modeling.roi_heads import FastRCNNOutpu... |
3ddda2bd53827e802fa8e770dbea9e0146d090c42bf5ea4d02ec5ee95f27ad07 | Python | 1,710 | 40 | from pathlib import Path
class TestMosaicsUtils:
def test_try_extract_tiles_from_disk_to_disk(
self, imc_test_data_steinbock_path: Path
):
# img_files = io.list_image_files(imc_test_data_steinbock_path / "img")
# gen = mosaics.try_extract_tiles_from_disk(img_files, 50)
# for im... |
617fcd2692399bfb2e45e4ac39bb6610c0389d8f36e8ffcf9734061e1c4bef62 | Python | 1,710 | 51 | from detectron2.config import LazyCall as L
from detectron2.data.detection_utils import get_fed_loss_cls_weights
from detectron2.layers import ShapeSpec
from detectron2.modeling.box_regression import Box2BoxTransform
from detectron2.modeling.matcher import Matcher
from detectron2.modeling.roi_heads import FastRCNNOutpu... |
f4b65c2a90df52d34f62bb4c871b6134ca84e36fea34013fa344bd58e7898b76 | Python | 1,710 | 51 | from detectron2.config import LazyCall as L
from detectron2.data.detection_utils import get_fed_loss_cls_weights
from detectron2.layers import ShapeSpec
from detectron2.modeling.box_regression import Box2BoxTransform
from detectron2.modeling.matcher import Matcher
from detectron2.modeling.roi_heads import FastRCNNOutpu... |
db0b9c0f1681d757fa30b37a3b5ee8ff3c05c11adc78f75f2bc427f6191eddd2 | Python | 1,713 | 55 | from functools import partial
import torch.nn as nn
from fvcore.common.param_scheduler import MultiStepParamScheduler
from detectron2 import model_zoo
from detectron2.config import LazyCall as L
from detectron2.solver import WarmupParamScheduler
from detectron2.modeling import MViT
from .common.coco_loader import dat... |
7fe51fe0d61a787173c4383adcdd3517ffa714e5155001a6dd9ca41a5d06c0f6 | Python | 1,716 | 26 | #python msmsCount.py "L:\promec\TIMSTOF\LARS\2024\241002_zrimac\DIANN1p9p2\report.parquet"
#rsync -Pirm --include='*.parquet' --include='*/' --exclude='*' ash022@login.saga.sigma2.no:cluster/FastaDB/ /mnt/l/promec/TIMSTOF/LARS/2024/241002_zrimac/
import sys
from pathlib import Path
if len(sys.argv)!=2: sys.exit("USA... |
8f57d31326bc002828f869a86f9cb963131c196b87fbe8de397ed64f1f1b0971 | Python | 1,717 | 44 | import numpy as np
from torch.utils.data import DataLoader
import torch
from .activation_manager import ActivationManager
from .decomposition_handler import DecompositionHandler
def generate_target_gram_matrix(
data_loader: DataLoader, # 1-image
layer_name,
activation_manager: ActivationManager,
han... |
0a36d78b154a6580b70a88be5acfdcd536cd3ddd572887bc05070054c1d6246a | Python | 1,718 | 59 | """
XKCD Style
==========
<!-- difficulty: beginner -->
Render neurons in the hand-drawn XKCD sketch style, just for fun.
If you don't already know: `matplotlib` has an [xkcd mode](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.xkcd.html)
that makes plots look like they were drawn by hand - a fun way to ... |
1316e93294cc61150a3536dbf8d729bb54fec4aae56db2b9872a5664fe8e970b | Python | 1,718 | 50 | import logging
from os import PathLike
from pathlib import Path
from typing import Generator, Sequence, Tuple, Union
import numpy as np
import pandas as pd
from .. import io
logger = logging.getLogger(__name__)
def match_masks(mask1: np.ndarray, mask2: np.ndarray) -> pd.DataFrame:
nz1 = mask1 != 0
nz2 = ma... |
25b6db8fe5ddb35806a76cf70969f9edc07d0da1410f93808ea231b09537a8fa | Python | 1,719 | 54 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# pyre-unsafe
from dataclasses import dataclass
from typing import Union
import torch
@dataclass
class DensePoseEmbeddingPredictorOutput:
"""
Predictor output that contains embedding and coarse segmentation data:
* embedding: float ... |
b6e2969c026683e341ab183758273c3ae4b84ec16bf5687e6bc019364f008c5e | Python | 1,719 | 51 | #!/usr/bin/env python
#
# Copyright (c) 2021 10x Genomics, Inc. All rights reserved.
#
"""Prepare inputs to run the PCA for batch correction."""
import numpy as np
import cellranger.rna.library as rna_library
from cellranger.library_constants import ATACSEQ_LIBRARY_TYPE
from cellranger.matrix import CountMatrix
__MR... |
dd8f8785f6360e23b0358fe781274d5a2a96d68b4b51ac0f15a906672df9f32f | Python | 1,721 | 36 | import argparse
def main(args):
import json
import numpy as np
with open(args.jsonl_input_path, 'r') as json_file:
json_list = list(json_file)
my_dict = {}
for json_str in json_list:
result = json.loads(json_str)
all_chain_list = [item[-1:] for item in list(result) if i... |
87f0185732fd983d238b4197643158dace8018844144621726cf2ef0cece2d5e | Python | 1,722 | 60 | import shutil
import uuid
from pathlib import Path
import pandas as pd
from src.database.spreadsheet_source import SpreadsheetSource
from src.utils.config import PROJECT_ROOT
def _build_settings(file_path: Path) -> dict:
return {
"input": {
"file_path": str(file_path),
"sheet_nam... |
5f201ea1c78a7e60873e998f384f47cfd6420ecb9897e16730e3046eb8c827bd | Python | 1,725 | 58 | import argparse
import os
import lpips
import numpy as np
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-d','--dir', type=str, default='./imgs/ex_dir_pair')
parser.add_argument('-o','--out', type=str, default='./imgs/example_dists.txt')
parser.add_argumen... |
0ec9a1f4745152ad4edf38dcd2d929d14b1aad693afb69db0ce73b8d01d4cf6a | Python | 1,730 | 37 | from __future__ import annotations
import numpy as np
def _split_parameters(vector: np.ndarray, input_dim: int, hidden_width: int):
vector = np.asarray(vector, dtype=np.float32).reshape(-1)
first_weight_count = hidden_width * input_dim
hidden_weight = vector[:first_weight_count].reshape(hidden_width, inp... |
3cc2c7f4a3ae13e68eb9a49007ee299406d9b1f998fababd77080837077e6021 | Python | 1,734 | 54 | #!/usr/bin/env python
"""The run script."""
import logging
import os
# import flywheel functions
from flywheel_gear_toolkit import GearToolkitContext
from utils.parser import parse_config
from utils.command_line import exec_command
from utils.join_data import housekeeping
from utils.Inspect_segmentations import SegQ... |
997a70a3072a1d03651a45a3bd09a935fa71feed8097a8a28b46acadcff990fc | Python | 1,736 | 53 | #!/usr/bin/env python
#
# Copyright (c) 2018 10X Genomics, Inc. All rights reserved.
#
MATRIX_MEM_GB_MULTIPLIER = 2.6 # Increased from 2.0 to enable high-diversity samples
VIS_HD_MATRIX_MEM_GB_MULTIPLIER = 1.0
NUM_MATRIX_ENTRIES_PER_MEM_GB = 50e6
# Empirical obs: with new CountMatrix setup, take ~ 50 bytes/bc
NUM_MA... |
7fc67b8f2b02960df120bc389965f35e7c59048cf1899751cb75cdabae60748b | Python | 1,740 | 58 | import logging
import os
from typing import Any, Iterable
import xarray as xr
from .. import io
from .trial import TrialView
from .artifacts import get_results_path
__all__ = ['load_results', "load_detections"]
logger = logging.getLogger(__name__)
def load_results(trial: TrialView, state: str | Iterable[str] = ('... |
d3a89fe3229d39a6075a194987b1d5efd9d87d9e0996e0c31a61828724cef632 | Python | 1,741 | 47 | import re
import os, glob, h5py
import gzip
import shutil
from nilearn.image import mean_img, load_img, clean_img,math_img,new_img_like,resample_to_img
from nilearn.interfaces.fmriprep import load_confounds
from nilearn.maskers import NiftiSpheresMasker,NiftiMasker
import numpy as np
import nibabel as nib
from scipy.si... |
d0e9a8287ee30f8d193d2cdd749de446332a5fd19be6b05c0c429acc343681eb | Python | 1,742 | 57 | import os
import pickle
import pandas as pd
import numpy as np
import scanpy as sc
pkl_path = "PATH_TO_INPUT/SAMap_processed.pkl"
output_dir = "PATH_TO_OUTPUT_DIR/SAMap/"
os.makedirs(output_dir, exist_ok=True)
print(f"Loading SAMap result: {pkl_path}")
with open(pkl_path, "rb") as f:
sm = pickle.load(f)
samap_... |
d6aebf820e32905bd4c3489b05a00e1dc612a4633e0dc910200875da3cb7ef7c | Python | 1,745 | 46 | import cv2
import numpy as np
import matplotlib.pyplot as plt
import math
def create_pixel_value_histogram(input_tifs, frames_per_hist=100, bin_width=8):
"""Creates a histogram for the pixel values in a tif file
Args:
input_tifs (str path to .tif files): input
frames_per_hist (int, optional): number of frames t... |
b90d95ed5dab62d5824dd859f95b49e5c32b94b548b920fe0cf6e6adb8d29ae8 | Python | 1,748 | 45 | #!/usr/bin/env python
#
# Copyright (c) 2025 10X Genomics, Inc. All rights reserved.
#
"""Constants associated with the segmentation data."""
FILTERED_CELLS = "filtered_cells"
CELLS_EXPANDED_UNDER_TISSUE = "cells_expanded_under_tissue"
FILTERED_CELLS_EXPANDED_UNDER_TISSUE = "filtered_cells_expanded_under_tissue"
FRAC... |
6b2385a56e2e6ce1177c57bc7ab0d22de16be98afc638add73f764d117a4ee52 | Python | 1,750 | 51 | import os
# Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
html_baseurl = os.environ.get("READTHEDOCS_CANONICAL_URL", "/")
# -- Project information -----------------... |
142f8f65909b3ff31b422e0849d1e0f23c3095cd33063b65f11a1ff82d12b652 | Python | 1,751 | 61 | import sys
import os
sys.path.append(".../benchmark_script/evaluation/ASW_NMI/evaluation_ASW_NMI.py")
from evaluation_ASW_NMI import createAnnData, silhouette_coeff_ASW, nmi
import pandas as pd
data_dir = "PATH_TO_INPUT_DIR/temp_files/"
save_dir = "PATH_TO_OUTPUT_DIR/"
os.makedirs(save_dir, exist_ok=True)
file_list... |
94b628b98a00c231438a1fda37231c6ac6c40d6467d94070ec118314b95a7b31 | Python | 1,753 | 73 | import numpy as np
import torch
import matplotlib.pyplot as plt
format = lambda x: x.replace("_", " ")
readSignal = lambda data, recordNo, channelNo: data["dataset"][recordNo]["eeg"][
channelNo
].numpy()
def prepare_frequencies(sampling_rate, duration):
time = np.linspace(0, duration, int(sampling_rate * dur... |
9f26fb7ac6eaaa554a6a15062a972b8b8b5a48fb5ec3a38127493cb2a3adfe7c | Python | 1,755 | 49 | from detectron2.config.lazy import LazyCall as L
from detectron2.data.detection_utils import get_fed_loss_cls_weights
from detectron2.data.samplers import RepeatFactorTrainingSampler
from detectron2.evaluation.lvis_evaluation import LVISEvaluator
from ..COCO.cascade_mask_rcnn_swin_b_in21k_50ep import (
dataloader,... |
c7a2c9a2bd09fb4e83a8c985edea521d694aaca9a2181c2fa8a185fc40413b3c | Python | 1,759 | 49 | # ------------------------------------------------------------------------------
# Title: Direct Spatial Communication Analysis (Commot - P0)
# Author: Yiran Song
# Date: March 18, 2025
# Description:
# This script runs direct ligand-receptor communication analysis on the Xenium dataset
# at time point P0 using the Com... |
9f1eb418c303e55113653273f2ffbb76f3caae0bfa837186f1475e33f2599848 | Python | 1,760 | 46 | import os
import shutil
import subprocess
from pathlib import Path
import nibabel as nib
import numpy as np
def dice_score(y_true, y_pred):
intersect = np.sum(y_true * y_pred)
denominator = np.sum(y_true) + np.sum(y_pred)
f1 = (2 * intersect) / (denominator + 1e-6)
return f1
def run_tests_and_exit_... |
fd3526eb6734ec03c1af8b75f152f33ced8cc5243c1812016104f30f27923284 | Python | 1,764 | 41 | from WORC.classification.crossval import test_RS_Ensemble
import pandas as pd
import os
classification_data = r"C:\Users\Martijn Starmans\Documents\GitHub\WORCTutorial\WORC_Example_STWStrategyHN_220915_DoTstNRSNEns\classify\all\tempsave\tempsave_0.hdf5"
# Read the data and take first predicted label
classification_da... |
a41c907ae7325b950306797dd316d118924d247a4cf0d2eea9299fb7902454dd | Python | 1,766 | 55 | from mesa.discrete_space import FixedAgent
class Cell(FixedAgent):
"""Represents a single ALIVE or DEAD cell in the simulation."""
DEAD = 0
ALIVE = 1
@property
def x(self):
return self.cell.coordinate[0]
@property
def y(self):
return self.cell.coordinate[1]
def __in... |
10aae1bf5177615bc433104595b73dd206cc2c2cd13004fbcfa52ad8998f424b | Python | 1,767 | 42 | 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)
dir_path = "/home/nomura/Proj/mmvelo/experiments/multiome_brain_rep_wo_IN/2023-05-07T15:19:02_s43_k100_fo... |
88297a7a27873ad4dc51c882ed785a8826cae7f5048a3437518237c037ff6dc4 | Python | 1,767 | 55 | # Copyright 2011-2014 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 obtain a copy of the Licen... |
cb85c9b59b77867340baf91af434fe26761eaa224be31364ada6718bea41bb36 | Python | 1,771 | 66 | import numpy as np
import pandas as pd
import scanpy as sc
import scib
from scib.metrics import kBET
adata_path = "PATH_TO_INPUT_DIR/samap_LISI_input.h5ad"
adata = sc.read_h5ad(adata_path)
print(f"AnnData loaded: {adata.shape}")
print("Available obsm keys:", list(adata.obsm.keys()))
batch_key = "batch"
label_key = "... |
6e0f8c524473b04f93353be9945c70ac4284778cba08c2b52e771a02ed370e73 | Python | 1,772 | 39 | #https://sequenceanddestroy.substack.com/p/issue-79-modeling-latent-variation?utm_source=post-email-title&publication_id=1508290&post_id=201450642&utm_campaign=email-post-title&isFreemail=true&r=a55q5&triedRedirect=true&utm_medium=email
import numpy as np
import pandas as pd
np.random.seed(42)
n_samples, n_proteins = 2... |
a2028023181f27f4f996d7686ecd84d26fd97a1ebba52f5d6dcf9d3c341d4b91 | Python | 1,772 | 49 | """RDKit canonical-tautomer backend.
A dependency-free tautomer selector: RDKit's ``TautomerEnumerator`` enumerates
tautomers and scores them with its built-in heuristic, returning a single
canonical (dominant) tautomer. Used as the always-available tautomer backend
and as the enumeration source for the sPhysNet-Taut ... |
1c9941e94e651e7c2e19b621f681ea0720f607e3b1167b7aaf1c3f0d17182c1a | Python | 1,774 | 55 | from glob import glob
import os
from setuptools import setup
with open('README.md', 'r') as f:
long_description = f.read()
# Read the version from the main package.
with open('react/__init__.py') as f:
for line in f:
if '__version__' in line:
_, version, _ = line.split("'")
br... |
d0928630eab9356633335be6f1cefbc818a41423f3735c4c39e6d08839c4a1ff | Python | 1,774 | 65 | import argparse
import pandas as pd
"""
This is a small helper script that reads test_imbalanced.csv (i.e.,
is the paired version of our test set), extracts the unique DNA samples,
and concatenates them into a dataframe that lists unpaired samples.
"""
def get_args():
parser = argparse.ArgumentParser()
parse... |
585156349e1c3f9feaf6f7121cc88bf378227b622d6715f380bdef5923871764 | Python | 1,775 | 71 | """ Brummer's Method
brummer1993automatic,
title={Automatic detection of brain contours in MRI data sets},
author={Brummer, Marijn E and Mersereau, Russell M and Eisner, Robert L and Lewine, Richard RJ},
journal={IEEE Transactions on medical imaging},
volume={12},
number={2},
pages={153--166},
year={1993},
publisher={I... |
1c92358c0bd956debacd59482fb802d6b3778181e88700da88945a8a8f3e920a | Python | 1,776 | 85 | from __future__ import annotations
import math
import os
import os.path as op
from PIL import Image
def get_img_path(
path_root: str,
imgid: str,
) -> str:
"""Get image path of NOD.
Parameters
----------
path_root : str
Root path of the image.
imgid : str
Image ID of NOD... |
df86dbb1b1a42c76542af6a2227e8094846ba403f7b408f0ef36ecd8ed2fa127 | Python | 1,776 | 40 | # Copyright (c) Facebook, Inc. and its affiliates.
import torch
import torch.nn as nn
class DeepLabCE(nn.Module):
"""
Hard pixel mining with cross entropy loss, for semantic segmentation.
This is used in TensorFlow DeepLab frameworks.
Paper: DeeperLab: Single-Shot Image Parser
Reference: https://g... |
ee45540f3c13f1508fa988ce3b2cf763dd5b29a134bf089c78e758e9c7f1a35b | Python | 1,777 | 39 | from pathlib import Path
import torch
from . import config
from .utils.ica import ICAHandler
if __name__ == "__main__":
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Parameters
LAYERS = config["layers"]
NUM_COMPONENTS_FULL = config["ica"]["num_components_full"]
NUM_COM... |
5c401d7e1e4803615616f68894bc56f6419b7785cbcf705aad7aa999250a2bbd | Python | 1,781 | 60 | # Original model presented in: C. Spampinato, S. Palazzo, I. Kavasidis, D. Giordano, N. Souly, M. Shah, Deep Learning Human Mind for Automated Visual Classification, CVPR 2017
import sys
import os
import random
import math
import time
import torch
torch.utils.backcompat.broadcast_warning.enabled = True
from t... |
311ba64bc2be9f714a22abf4a3309418820a5c82307abffeef14eb6f67e8fd36 | Python | 1,784 | 54 | from __future__ import annotations
from pathlib import Path
from PIL import Image, ImageDraw
PROJECT_ROOT = Path(__file__).resolve().parents[1]
ASSETS_DIR = PROJECT_ROOT / "assets"
PNG_PATH = ASSETS_DIR / "caffeine_icon.png"
ICO_PATH = ASSETS_DIR / "caffeine_icon.ico"
def main() -> int:
ASSETS_DIR.mkdir(paren... |
16180d8a98f6adca44cf3beb54fec349ab88b804a36af728831d9bb841a71c63 | Python | 1,785 | 69 | # This code is part of OpenFE and is licensed under the MIT license.
# For details, see https://github.com/OpenFreeEnergy/openfe
# MOVE SINGLEMODULEPLUGINLOADER UPSTREAM TO PLUGCLI
import importlib
import shutil
import urllib
import click
from plugcli.cli import CLI, CONTEXT_SETTINGS
from plugcli.plugin_management im... |
09113c1f9c7c5b173c1e990d979d255670f19281b0ca65ae23c6a451479bcbd5 | Python | 1,786 | 57 | from __future__ import annotations
import importlib.metadata as impm
from typing import Any, cast
import attrs
from snakebids import bidsapp
from snakebids.plugins.base import PluginBase
@attrs.define(kw_only=True)
class Version(PluginBase):
"""Expose app version in config.
A version string can either be ... |
9b6b0af8bd11edd52093126a5071ab37207c3bddda5194dd7d4751d51af4fdd7 | Python | 1,792 | 54 | """
Write out the file that is used to test the quickrun command.
This will need to be run if the serialized transformation changes such that
the old file can't be read.
USAGE:
python write_transformation_json.py ../data/
(Assuming you run from within this directory.)
"""
import argparse
import json
import pat... |
28c01cf5ac87ccd368cdce7c7a7665e6328db62e814d6c077ec30cf1da093585 | Python | 1,793 | 53 | import os.path
import torchvision.transforms as transforms
from data.dataset.base_dataset import BaseDataset
from data.image_folder import make_dataset
from PIL import Image
import numpy as np
import torch
from IPython import embed
class JNDDataset(BaseDataset):
def initialize(self, dataroot, load_size=64):
... |
2f20ec8fd97cb4e2fbd8320de57e6c0460e3c4ddcfecb34935629fc6fc0266fd | Python | 1,797 | 61 | """"" Sijbers's method
sijbers2007automatic,
title={Automatic estimation of the noise variance from the histogram of a magnetic resonance image},
author={Sijbers, Jan and Poot, Dirk and den Dekker, Arnold J and Pintjens, Wouter},
journal={Physics in medicine and biology},
volume={52},
number={5},
pages={1335},
year={20... |
e6c6742a3356aa26d677b676db2750f1e96a80eb129fc5c828a186765c39655d | Python | 1,802 | 50 | # 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... |
69580b9c43d4b779a049c5e617710c8262ed467ffcb37b617430a4360b90ed33 | Python | 1,803 | 56 | # This code is part of OpenFE and is licensed under the MIT license.
# For details, see https://github.com/OpenFreeEnergy/openfe
import pytest
from openfe.protocols import openmm_afe
from openfe.protocols.openmm_afe import (
AbsoluteSolvationProtocol,
)
@pytest.fixture()
def default_settings():
return Absolu... |
85799cf6573643d6e9df41c46a9bc6acd1f1d6389426d6e14517fd6037030c7a | Python | 1,803 | 45 | #!/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... |
227c37b582d9ba773b0cbecc7bee7992ba0b6dec07225dcf46b105f51e42d153 | Python | 1,804 | 88 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 26 16:21:04 2021
@author: Younes Valibeigi
"""
import csv
import numpy as np
import matplotlib.pyplot as plt
#fullData = np.array()
fullData = [];
with open('Jun 26, 2021 4-30-49 PM.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
fullD... |
9ecb009f549dcfb941cb62e51f02be30788533b885cb4664bf09cca937b55006 | Python | 1,807 | 51 | # Copyright (c) Facebook, Inc. and its affiliates.
import unittest
import torch
from torch import nn
from detectron2.layers import ASPP, DepthwiseSeparableConv2d, FrozenBatchNorm2d
from detectron2.modeling.backbone.resnet import BasicStem, ResNet
"""
Test for misc layers.
"""
class TestBlocks(unittest.TestCase):
... |
b82c46ec51438962f0093e26599ad8c0f8628bbe32cad70e368badd35c77074b | Python | 1,813 | 44 | import pandas as pd
import sys
from pathlib import Path
fileName = 'evidence.txt'
df.columns = df.columns.str.strip('_x')
# counting the peptideHits for each file, can change to other columns like "Sequence","Proteins"...
colStrName = ["Raw file","Proteins"]
if len(sys.argv) != 2:
dirName = 'F:/promec/Elite/LARS/20... |
4f663af62328c997e1355b66d2a0eae1de69c592dbbbd2146fca6d4539376c39 | Python | 1,814 | 64 | # Add these settings to enable autodoc for all scripts
add_module_names = False # Remove module names from generated docs
autodoc_default_options = {
'members': True,
'undoc-members': False,
'show-inheritance': True,
'imported-members': False,
}
# Project information
project = 'Micaflow'
copyright ... |
c953d90a2288e77a9796c52eb37bdd359dfd206d1c2e8636c105de6191e26a1b | Python | 1,814 | 65 | from enum import Enum
from mesa.discrete_space import FixedAgent
class State(Enum):
SUSCEPTIBLE = 0
INFECTED = 1
RESISTANT = 2
class VirusAgent(FixedAgent):
"""Individual Agent definition and its properties/interaction methods."""
def __init__(
self,
model,
initial_stat... |
ebf0a66f982d7656b8b1d558ab5d4a3374bca395922bd82aa37f3741424b8818 | Python | 1,816 | 50 | import os
import numpy as np
import pandas as pd
import umap
import matplotlib.pyplot as plt
import anndata as ad
import scanpy as sc
import scvelo as scv
import scanpy.external as sce
from scipy.io import mmwrite, mmread
from scipy.sparse import csr_matrix
np.random.seed(42)
# load anndata
dir_path = "/home/nomura/P... |
222f499f5fa4915b09f6a976fb2464a85472c2610b1688d7c13502b7ef3f684e | Python | 1,820 | 63 | # This code is part of OpenFE and is licensed under the MIT license.
# For details, see https://github.com/OpenFreeEnergy/openfe
from importlib import resources
from typing import Iterable, NamedTuple
import pytest
from rdkit import Chem
from openfe import LigandAtomMapping, LigandNetwork, SmallMoleculeComponent
fro... |
64afff3e7b514867f19e3601f4eb1d4e0d1ca8a3ce5ad533dbfe5e360ef4dd1c | Python | 1,820 | 48 | # Copyright (c) Facebook, Inc. and its affiliates.
import contextlib
import os
import tempfile
import unittest
import torch
from torchvision.utils import save_image
from densepose.data.image_list_dataset import ImageListDataset
from densepose.data.transform import ImageResizeTransform
@contextlib.contextmanager
def... |
7d83aa980112484df2a998acc86de361519ebf17789f3a1cc9e34dbb04607868 | Python | 1,820 | 59 | # Copyright (c) 2019 10X Genomics, Inc. All rights reserved.
"""Shared ploting code for the web summary."""
from __future__ import annotations
import copy
from websummary.summarize import DEFAULT_FONT as DEFAULT_WEB_FONT
BUTTON_RESET_SCALED_2D = "resetScale2d"
BUTTON_TO_IMAGE = "toImage"
TO_IMAGE_BUTTON_OPTIONS = ... |
e29a8e53b6411e381c2adaba84b52dddd99d9cddef59d4afb8a9e50d70773f15 | Python | 1,822 | 71 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
"""
TridentNet Training Script.
This script is a simplified version of the training script in detectron2/tools.
"""
import os
from detectron2.checkpoint import DetectionCheckpointer
from detectron2.config import get_cfg
from detectron2.engine... |
21c87ba308f98225ef6b48d03773cf7f6fdb4d24ad4cf8b6502447828fb9e8fa | Python | 1,825 | 66 | #!/usr/bin/env python
#
# Copyright (c) 2016 10X Genomics, Inc. All rights reserved.
#
from __future__ import annotations
import os
import socket
import martian
from six import ensure_str
import tenkit.bcl as tk_bcl
import tenkit.preflight as tk_preflight
__MRO__ = """
stage MAKE_FASTQS_PREFLIGHT(
in path ... |
327d228a27ea6a7363633efd3d139c664a22e48303425017a40f9c6e9c1d26ce | Python | 1,827 | 49 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 7 13:33:47 2022
@author: schmidtfa
"""
#%% imports
from preprocess_eeg import Preprocessing
from plus_slurm import JobCluster, PermuteArgument
from os import listdir
#%% get jobcluster
job_cluster = JobCluster(required_ram='10G',
... |
8abfb15ea614e0cb6846c06317a8f762e8ce49a3bcd9462e36b727da1f7a2132 | Python | 1,828 | 48 | import scanpy as sc
import pandas as pd
import os
files = {
"scVI": "PATH_TO_SCVI_H5AD",
"scanorama": "PATH_TO_SCANORAMA_H5AD",
"bbknn": "PATH_TO_BBKNN_H5AD",
"scANVI": "PATH_TO_SCANVI_H5AD",
"saturn": "PATH_TO_SATURN_H5AD"}
output_dir = "PATH_TO_OUTPUT_DIR/temp_files/"
os.makedirs(... |
07179ff10830cb26c9ea76d10f2390b6715f84713642239713f4e4b281108f4d | Python | 1,829 | 73 | import argparse
import nibabel as nib
import numpy as np
from scipy.ndimage import gaussian_filter
from skimage.measure import label
def main_cluster(data):
label_image = label(data)
max_label = sorted([[np.sum(label_image == val), val]
for val in np.unique(label_image)[1:]])[-1][1]
... |
cb2cae0d1bf8982f0fdff74fced185bfcbf227e41f7a1dd8a32421d3fb12caf5 | Python | 1,829 | 64 | from pathlib import Path
import click
import click_log
from .. import io
from .._steinbock import SteinbockException
from .._steinbock import logger as steinbock_logger
from .utils import catch_exception
@click.command(name="view", help="View image using napari GUI")
@click.option(
"--img",
"img_dir",
t... |
09075d3b742490f91a74a097843fdd4edca18956b8a5e2d1e0c526ef01ddc07a | Python | 1,830 | 58 | from pathlib import Path
import numpy as np
from steinbock import io
from steinbock.measurement import intensities
from steinbock.measurement.intensities import IntensityAggregation
class TestIntensitiesMeasurement:
def test_measure_intensites(self):
img = np.array(
[
[
... |
56249b6cb27736c77e7943839de24e29f023f01fe75b1793e47c0d3a10df004c | Python | 1,832 | 43 | #!/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... |
71e3124a9f84ae98a6900004459c7899e9ec3f2e44cb8075aa06cbed713c97bd | Python | 1,833 | 51 | from typing import Sequence
import pytest
from hsnn.core.config import ModelParams
from hsnn.core.definitions import NeuronClass, SynapseClass, Projection
_NAMESPACES_CLASS_MAPPING = {
'neurons': NeuronClass,
'synapses': SynapseClass
}
class TestModelParams:
@pytest.fixture(autouse=True)
def setup_m... |
df3245994e82dc5ac7149266e7210102df78f438e2198682ec21e75281940d8e | Python | 1,833 | 49 | import json
import sys
import tempfile
import unittest
from pathlib import Path
import pandas as pd
SCRIPTS = Path(__file__).resolve().parents[1] / "scripts"
sys.path.insert(0, str(SCRIPTS))
from aggregate_heldout_metrics import aggregate_held_out_metrics
class AggregateHeldOutMetricTests(unittest.TestCase):
... |
d00fb96b7d7ccd920a84c91ca2447d3d953d0acb46894918da84adcabe343a80 | Python | 1,834 | 72 | """_summary_"""
import argparse
import random
import torch
import numpy as np
is_label_found = lambda l: np.vectorize(lambda x: x["label"] in l)
is_found = lambda l: np.vectorize(lambda x: x in l)
parser = argparse.ArgumentParser(description="Template")
parser.add_argument(
"-id",
"--input-dataset",
he... |
3864a87b6a099843827ba988047f585e4def1d27db15b98f152a28a8088677cb | Python | 1,842 | 48 | from typing import Optional
import numpy as np
import numpy.typing as npt
from ._base import assert_recording
from .conversion import as_spike_events, spike_events_to_trains, get_rates
from ..core.types import Recording, SpikeEvents, SpikeTrains, FiringRates
__all__ = [
"get_submask",
"mask_recording",
"... |
4434a32c942d1e3f2754a2c7cd6f88287681aab204ba3b120ec5dec888ba751a | Python | 1,842 | 52 | import numpy as np
import os, glob
GLOB_DIR = "/home/zamor/nasShare/INM-GlobalShare/Boulantetal_Tristan_2025/bids"
RAW_PATH = os.path.join(GLOB_DIR, 'rawdata')
DATA_DIR = f"/home/zamor/Documents/TRISTAN/imag_dataset"
grp_dir = os.path.join(DATA_DIR,"grp_output")
stimfile = "/home/zamor/nasShare/INM-GlobalShare/Boula... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.