sha256 stringlengths 64 64 | language stringclasses 27
values | size int32 1 491k | lines int32 1 21.8k | content stringlengths 1 200k |
|---|---|---|---|---|
660f8bbf4f61abbb47407faf307f240fd5e42d6359df618c65c0d0e20d8a0469 | Python | 1,305 | 39 | import pandas as pd
import numpy as np
from scipy.stats import zscore
import bambi as bmb
import arviz as az
from plus_slurm import Job
class StatsAcross(Job):
#%% the run method starts here
def run(self, eog_n, brms_kwargs):
eog = pd.read_csv('/mnt/obob/staff/fschmidt/cardiac_1_f/data/eog_slopes_cam... |
f35b63653ea10e67009e3d608bc0a47fdb5f74ac6a316f801456eca3c8d5fe59 | Python | 1,306 | 38 | #!/usr/bin/env python
#
# Copyright (c) 2022 10X Genomics, Inc. All rights reserved.
#
"""Commonly used spatial specific constants."""
from __future__ import annotations
from cellranger.constants import AGG_CLOUPE_FIELD, AGG_H5_FIELD, aggr_files
# Spatial AGGR specific
AGG_SPATIAL_FIELD = "spatial_folder"
AGG_TISSU... |
2effe12c4bce099c85721e47cdc7703a2ce08b7cca42422376aca6390f6a7f1d | Python | 1,307 | 43 | # Copyright (c) Facebook, Inc. and its affiliates.
# pyre-unsafe
import random
import torch
from .densepose_base import DensePoseBaseSampler
class DensePoseUniformSampler(DensePoseBaseSampler):
"""
Samples DensePose data from DensePose predictions.
Samples for each class are drawn uniformly over all pi... |
dd78891ec70340f9a3ee23f8b27ab34eb06e1631f7f878d9199948a792959f24 | Python | 1,308 | 36 | from mesa import Model
from mesa.discrete_space import OrthogonalMooreGrid
from mesa.examples.basic.conways_game_of_life.agents import Cell
class ConwaysGameOfLife(Model):
"""Represents the 2-dimensional array of cells in Conway's Game of Life."""
def __init__(self, width=50, height=50, initial_fraction_aliv... |
76077483f628d7474662a875c6c7f37b5aa1d91524e6dba6fa038d9fb7d48ad6 | Python | 1,310 | 41 | #
# Copyright (c) 2016 10X Genomics, Inc. All rights reserved.
#
"""Code refactored out of align.py to avoid pulling in LibSSW.
Contains utilites that operate on CIGAR strings
"""
from __future__ import annotations
import re
from collections.abc import Iterator
from typing import TYPE_CHECKING
from six import ensure... |
f24a2e4a09bb9c3df04df60869ed6657defd7693ca7911de6d4d8947e69bc78d | Python | 1,310 | 47 | from pathlib import Path
import numpy as np
from steinbock import io
from steinbock.measurement import regionprops
class TestRegionpropsMeasurement:
def test_measure_regionprops(self):
img = np.array(
[
[
[0.5, 1.5, 0.1],
[0.1, 0.2, 0.3... |
97611b27632debd97f894087dc5608a95d3bf3b97d55912c16fe107f15c240f4 | Python | 1,311 | 61 | # -*- coding: utf-8 -*-
"""
Created on Sat Jul 10 12:37:44 2021
@author: youne
"""
import numpy as np
import matplotlib.pyplot as plt
from tabulate import tabulate
import math
from scipy.misc import electrocardiogram
from scipy.signal import find_peaks
import numpy as np
fullData = []
strcycleP = []
f = open("BubB... |
de11e1a932ee9a1eccbc0c30e423ee05be40cf40f108e02682929e93a46b58f2 | Python | 1,311 | 37 | from pyNBS import pyNBS_plotting as plot
import os
import pandas as pd
import numpy as np
from scipy.spatial.distance import squareform
from scipy.cluster.hierarchy import linkage
outdir = "pynbs_results/"
job_name = "HTT_900_wasp_replot"
save_args = {"outdir": outdir, "job_name": job_name}
if not os.path.exists(outdi... |
7885cf691f077cfb75ed3e363a8e81994b8e394ec40d8ea873983f2e2d447e42 | Python | 1,312 | 44 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 1 14:05:26 2022
@author: schmidtfa
"""
#%% imports
from cluster_jobs.preprocess_meg_camcan import Preprocessing
from plus_slurm import JobCluster, PermuteArgument
from os import listdir
#% get jobcluster#
job_cluster = JobCluster(required_ram='4G... |
22ac511bb9de1b876c84a53b2388589d613a21a9763daf19f4a6fc62b6297a21 | Python | 1,313 | 51 | import functools
__all__ = ["bounded"]
def bounded(lo: float | None = None, hi: float | None = None):
if lo is None and hi is None:
raise ValueError("No bounds provided!")
def decorator(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
x = f(*args, **kwargs)
... |
47ecc8afe829997cc7e2ecd55e27c30dafb81c408cc30e816300cc92bb61b0f2 | Python | 1,318 | 49 | import os
import pandas as pd
import numpy as np
from skimage import measure
from skan import Skeleton, summarize
from smma.utilities import measure_properties
# from smma.visualise import plot_branch_overview, plot_skeletonisation
from loguru import logger
logger.info('Import OK')
# root_path = open('raw_data/root_... |
876077faab9ff39213409f0784cdc893ba74bb19debe9320f530c408c60382e6 | Python | 1,318 | 43 | import cv2 # type: ignore
import numpy as np
from util import write_info_file
def average_tifs(inputs : list, output):
"""Averages a list of single channel tiff movies
Args:
inputs (list): A list of paths (str) to tiff movies
output (str): Location to output the tiff file
Raises:
IOError: If one of the inpu... |
a2000256c1a5ec19e983327ab1a6a6fdc81b60e53030cd0a85a690aecf5194a1 | Python | 1,320 | 46 | # This code is part of OpenFE and is licensed under the MIT license.
# For details, see https://github.com/OpenFreeEnergy/openfe
from plugcli.params import NOT_PARSED, MultiStrategyGetter, Option
def _load_protein_from_pdb(user_input, context):
if ".pdb" not in str(user_input): # this silences some stderr spam
... |
5eb501afdd3464e0519f56ce445abe8e7ab5b1697ea97e0b35a99245523d7c57 | Python | 1,321 | 39 | #!/usr/bin/env python
# Copyright 2011-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... |
0f85bb9a6ae2e537be18a924d25a22bb21611f3ce59f2dff151346d16f6ecd60 | Python | 1,322 | 49 | import nibabel as nib
import numpy as np
epsilon = 0.01
#load gifti surf
gii = nib.load(snakemake.input.gii)
arr = gii.get_arrays_from_intent('NIFTI_INTENT_POINTSET')[0]
vertices = arr.data
#get ref nii (for defining bbox)
img = nib.load(snakemake.input.ref_nii)
affine = img.affine
print(affine)
lower_coord = np.a... |
b848e3d88510045c17abcdd9653ea6e09ce83b218f3da0ba3cc0cb4260741890 | Python | 1,323 | 41 | """Regenerate `objects.rda`.
Run with `python tests/fixtures/r_data/generate.py` from the repo root. Needs
`rdata` >= 1.0 (i.e. Python >= 3.11) since that is what can write R data files.
The fixture exists so that the *reading* side of `navis.io.rda_io` is covered
on Python 3.10, where `rdata` is too old to write and... |
70aa15bef09282d1876728ad3eac45cc1b0c73dcad3cc42d5ee1d7f0c074fdc4 | Python | 1,325 | 47 | """Hypothesis strategies for snakemake template tests."""
from __future__ import annotations
from collections.abc import Collection
import hypothesis.strategies as st
def _format_strings(
*,
base_exclude: set[str],
extra_exclude: Collection[str] | None = None,
min_size: int = 0,
):
if extra_exc... |
78af2e40b14491222a9c1f83a237c2d41c5a39f789f287e14e477847188df2f7 | Python | 1,326 | 37 | import flywheel
import json
import pandas as pd
from datetime import datetime
import re
import os
import shutil
import logging
log = logging.getLogger(__name__)
# Module to identify the correct template use for the subject VBM analysis based on age at scan
# Need to get subject identifiers from inside running con... |
7b0802c0791b8a7e253e1ad1e9ee2cad6c95e8882e56b0b9e556d0d2220db4e6 | Python | 1,328 | 31 | from typing import List, Tuple, Union
from batchgenerators.transforms.abstract_transforms import AbstractTransform
import numpy as np
class ConvertSegmentationToRegionsTransform(AbstractTransform):
def __init__(self, regions: Union[List, Tuple],
seg_key: str = "seg", output_key: str = "seg", seg... |
185e263448ea2d2e15838bed75e0c07ad6f2fedebd27e2dc161b5020c3810cd5 | Python | 1,330 | 44 | from mesa.discrete_space import CellAgent
class MoneyAgent(CellAgent):
"""An agent with fixed initial wealth.
Each agent starts with 1 unit of wealth and can give 1 unit to other agents
if they occupy the same cell.
Attributes:
wealth (int): The agent's current wealth (starts at 1)
"""
... |
882ccfdb317f698b60420b4ff552ffb1b60fc756378bea1d6ab521097eb614f3 | Python | 1,331 | 63 | # -*- coding: utf-8 -*-
"""For testing neuromaps.resampling functionality."""
import pytest
from neuromaps import resampling
@pytest.mark.xfail
def test__estimate_density():
"""Test estimating density."""
assert False
@pytest.mark.xfail
@pytest.mark.workbench
def test_downsample_only():
"""Test downsa... |
97b2dbb2eb953c76c55573803f0d21de8bb0b8012f7d2d4170f359cb2113173f | Python | 1,333 | 39 | #!/usr/bin/env python3
import argparse
from tqdm import tqdm
# Argument parsing
def parse_arguments():
parser = argparse.ArgumentParser(description="Filter BED file based on sequences from TXT files.")
parser.add_argument("-b", "--bed", required=True, help="Path to the input BED file")
parser.add_argument... |
6d31f2e5b3ded8efa0c8fbbf693f9c8249f638bbf4a6b9b05937d3749500aed0 | Python | 1,340 | 43 | #!/usr/bin/env python3
import sys
import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams['pdf.fonttype'] = 42
# --- read TSV: label\tvalue per line ---
tsv_file = sys.argv[1] if len(sys.argv) > 1 else "data.tsv"
labels, values = [], []
with open(tsv_file) as f:
for line in f:
line = line.st... |
ada3614ad45982f18a7730822ccf8813979a4393ec2543c0b4cb4f1916306494 | Python | 1,340 | 49 | #!/usr/bin/env python
#
# Copyright (c) 2024 10X Genomics, Inc. All rights reserved.
#
"""Make umap colored by cell type."""
__MRO__ = """
stage GET_CELL_TYPES_UMAP_PLOT(
in path analysis,
in csv cell_types,
in string pipestance_type,
out json cell_types_umap_plot,
src py "stages/cas... |
88da86982ab4d3a8968fb67d3b933b567f2f403f468e16e5cd144f0e78058e29 | Python | 1,346 | 42 | from __future__ import annotations
from typing import Protocol, runtime_checkable
class ProtonationError(Exception):
"""Raised when a protonation backend fails."""
class Protonator(Protocol):
backend_name: str
def protonate_smiles(self, smiles: str, access_code: str) -> str: ...
@runtime_checkable
c... |
0254488e7e6f360df552dc27879ad21ccc6dd15cfb3c22bfe12197300644d7aa | Python | 1,347 | 54 | import numpy as np
import pandas as pd
import scipy.sparse as sp
from sklearn.neighbors import NearestNeighbors
import scanpy as sc
def concat_self_neighbor_expression(
adata,
x_key="x",
y_key="y",
k=15,
include_self=False,
layer=None,
layer_key_for_raw="raw_counts"
):
""... |
9421be657886d6bfc605642245e1e5f2af3abff10965d55e6ffbbd240445562f | Python | 1,347 | 43 | """TAPA - Text and Phonetic Analysis pipeline for speaker diarization and acoustic analysis.
Names are resolved on first use rather than at import. Importing the package
therefore costs nothing and, more importantly, does not require torch, whisper
or soundfile to be installed — so `python -m tapa.environment` can dia... |
c634dcdc6a8096c570d25bec9f154ffd18dd5d3489cdc11d900a4eb8aa626a35 | Python | 1,349 | 42 | import os
import nibabel as nib
from nilearn import plotting
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation, PillowWriter
from tristan_pipeline.utils.plotting_utils import *
from tristan_pipeline.io.params import *
def update(frame):
ax.clear()
disp = plotting.plot_stat_map(
... |
d9203e4e4d39b237157de183a2d2bdcfb1c4842aa15317ddc4253aa35230cabd | Python | 1,350 | 49 | from typing import Dict, Tuple, Optional, NamedTuple, Union
from PIL.Image import Image as pil_image
from torch import Tensor
try:
from typing import Literal
except ImportError:
from typing_extensions import Literal
Image = Union[Tensor, pil_image]
BoundingBox = Tuple[float, float, float, float] # x0, y0, w, h
C... |
60761d560dcd6f66ed5d52366dbaabb06740e95b33e7732beb88c592f77cddef | Python | 1,351 | 35 | """Tests for snakemake_io"""
from snakebids.utils import snakemake_io
def test_glob_wildcards():
"""Test glob_wildcards() with various patterns"""
file_path = "tests/data/bids_t1w/sub-001/anat/sub-001_acq-mprage_T1w.nii.gz"
empty_wildcards = {}
assert snakemake_io.glob_wildcards(file_path) == empty_w... |
6bf5948c40b13c2a1e7a274fef637634929a9577a78fdf567e9365a38b5a7c2d | Python | 1,353 | 46 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 1 12:58:40 2022
@author: schmidtfa
"""
#%%
from cluster_jobs.abstract_jobs.preprocess_abstract import AbstractPreprocessingJob
import mne
from mne_bids import BIDSPath, read_raw_bids
class Preprocessing(AbstractPreprocessingJob):
job_data... |
f0da2bc28ed498608a2bb7c3dfb1e0669036f972c11e97eda2bd1de456a9096d | Python | 1,354 | 38 | """Sample names reach the tree outputs exactly as the user wrote them.
dnapars gets its own fixed-width identifiers, so nothing needs to rewrite a name that starts
with a digit, and nothing may truncate one.
"""
import sys
import unittest
from pathlib import Path
import numpy as np
sys.path.insert(0, str(Path(__file... |
28f9c6e8771bf21d481f810a3ab138d518e553155338b79d8b71b70ca44549a1 | Python | 1,355 | 44 | import sys
import unittest
from pathlib import Path
import numpy as np
import pandas as pd
SCRIPTS = Path(__file__).resolve().parents[1] / "scripts"
sys.path.insert(0, str(SCRIPTS))
from summarize_table1 import summarize_full_sample_pisa_means
class FullSampleBrrSummaryTests(unittest.TestCase):
def test_table... |
370a9b20ead8a86309f0c306a0dd89cd133aad806d40c6da59e0a2164bd1e3be | Python | 1,357 | 40 | import os
import sys
import click
import pytest
from openfecli import OFECommandPlugin
from openfecli.utils import write
@click.command("test", short_help="Run the OpenFE test suite")
@click.option('--long', is_flag=True, default=False, help="Run additional tests (takes much longer)") # fmt: skip
def test(long):
... |
d94cfccf7b8aef7c41b688b6d0ed95f1ec40acd8982d25a05116600b24eae7c1 | Python | 1,360 | 29 | """ARPAbet to IPA phoneme mappings."""
ARPABET_VOWELS = {
"AA": "\u0251", "AE": "\u00e6", "AH": "\u028c", "AO": "\u0254",
"AW": "a\u028a", "AY": "a\u026a",
"EH": "\u025b", "ER": "\u025d", "EY": "e\u026a",
"IH": "\u026a", "IY": "i", "OW": "o\u028a", "OY": "\u0254\u026a",
"UH": "\u028a", "UW": "u",
}... |
94872de2af1f3b34b35fc89bf5492d62d84a85e723c1da78755f8fc5297d8e39 | Python | 1,361 | 45 | from os import PathLike
import pickle
import sys
import torch
class Unpickler(pickle.Unpickler):
name_mappings = {
"MSELoss": "MSE",
"MSEMetric": "MSE",
"MAEMetric": "MAE",
"RMSEMetric": "RMSE",
"BoundedMSELoss": "BoundedMSE",
"BoundedMSEMetric": "BoundedMSE",
... |
af8f7a0189ae069a11b0a93fdc8e06cff70911cc47896818c043d63c3b948449 | Python | 1,364 | 33 | import shutil
from batchgenerators.utilities.file_and_folder_operations import isdir, join, load_json, save_json
from nnunetv2.utilities.dataset_name_id_conversion import maybe_convert_to_dataset_name
from nnunetv2.paths import nnUNet_raw
if __name__ == '__main__':
dataset_name = 'IntegrationTest_Hippocampus_ig... |
b6a2fbe51d9007d0917cac4ce6da87dd0850798052a94798d8c82335c8befe11 | Python | 1,369 | 32 | import os
from batchgenerators.utilities.file_and_folder_operations import *
from nnunetv2.paths import nnUNet_raw
from nnunetv2.utilities.utils import get_filenames_of_train_images_and_targets
if __name__ == '__main__':
# creates a dummy dataset where there are no files in imagestr and labelstr
source_datas... |
8bfcc0d4be3cc3f282f66f52970642f1f36591cf52d5bee45b8e1ddb4fca0715 | Python | 1,372 | 71 | """ Created on Mon Oct 30 12:27:04 2023
@author: dcupolillo """
import numpy as np
import cv2
def median(
image: np.ndarray,
kernel: int
) -> np.ndarray:
"""
Image filtering.
Parameters
----------
image : np.ndarray
The input image to be filtered.
kernel : int
... |
908b7efc32f5d0e5633a483a8195ac96e00ca40fa75debc13bf6b7d74155e135 | Python | 1,375 | 44 | import numpy as np
from . import config
from .utils.alpha_function import AlphaFunction
from .utils.condition import AttackParamsLoader, TuneCondition
from .utils.pgd_attack import AttackParams
alpha_list: dict[str, float] = {}
def get_alpha_from_tune_cond(tune_cond: TuneCondition, params: AttackParams):
globa... |
a5e2cfca87dbbf611ec31f086a29e27257f1ccd9671e54fabd2362a5217bb5ef | Python | 1,375 | 31 | #https://towardsdatascience.com/detecting-heart-arrhythmias-with-deep-learning-in-keras-with-dense-cnn-and-lstm-add337d9e41f
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from os import listdir
data_path="L:/promec/Animesh/mit-bih-arrhythmia-database-1.0.0/mit-bih-arrhythmia-database-1.0.0/"
im... |
5bd859bb9070ad44e019212fefee0f418f99152b34113ce569236c689c6d63b2 | Python | 1,377 | 48 | from omegaconf import OmegaConf
import detectron2.data.transforms as T
from detectron2.config import LazyCall as L
from detectron2.data import (
DatasetMapper,
build_detection_test_loader,
build_detection_train_loader,
get_detection_dataset_dicts,
)
from detectron2.evaluation import COCOEvaluator
data... |
56b4f65fc021706c4e6982d5fb0bec72e1c95c30694d643a74c56621967bad69 | Python | 1,378 | 31 | import torch
import torch.nn as nn
from transformers import AutoModel
class BertTextCNN(nn.Module):
def __init__(self, pretrained_model='bert-base-chinese', num_labels=42,
kernel_sizes=(2,3,4), filters_per_kernel=100, dropout=0.5):
super().__init__()
self.bert = AutoModel.from_pret... |
aad8f2447161981f2e8ac62c79de9b9dbe15794228ac4f539850de1ac0f1a2eb | Python | 1,383 | 29 | #python diffExprRank.py "L:\promec\TIMSTOF\LARS\2025\250805_Kamila\DIANNv2p2\report rq.ha..gg_matrix.tsv4118ISNS0.10.50.1BioRemGroups.txt4LFQvsntTestBH.csvstringInput.tsv" <key>
#https://string-db.org/cgi/help?subpage=api%23valuesranks-enrichment-api
#https://version-12-0.string-db.org/api/json/get_api_key
import req... |
8f00ab9ea50f68624ada6342b78767a96fa1f181139976b237e7b0122495fef0 | Python | 1,384 | 52 | #!/usr/bin/env python3
#
# Copyright (c) 2022 10X Genomics, Inc. All rights reserved
#
"""Prepare input for _CRISPR_ANALYZER stage in aggr."""
from __future__ import annotations
from typing import TYPE_CHECKING
import martian
import cellranger.molecule_counter as cr_mc
import cellranger.rna.library as rna_library
... |
41fd5993faaf3e482ed370bd2af97b6cb943bb59a92cc48f7712802283325a9d | Python | 1,385 | 29 | from torch import nn
class DeepSupervisionWrapper(nn.Module):
def __init__(self, loss, weight_factors=None):
"""
Wraps a loss function so that it can be applied to multiple outputs. Forward accepts an arbitrary number of
inputs. Each input is expected to be a tuple/list. Each tuple/list mu... |
7871da8582f726062950f8fc955e95fcf53b196b8f81ace723c12ba0b0ff7536 | Python | 1,385 | 47 | #!/usr/bin/env python
#
# Copyright (c) 2019 10X Genomics, Inc. All rights reserved.
#
"""Definiton of the Metric class."""
from __future__ import annotations
REFERENCE_PATH = "reference_path"
class Metrics:
def update(self, other):
for k, v in other.__dict__.items():
if v is not None:
... |
bb158187102bbfc84e0ba3d46111741a75c97c80e74d4e449d80d02b7b89a51b | Python | 1,386 | 43 | import matplotlib.pyplot as plt
def time_series_plot(ts):
# plot ground truth and generated signals
# lower resolution for memory reasons
dim_x = min(ts.shape[1], 10)
figure = plt.figure(figsize=(10, 1.5 * dim_x), dpi=30)
for i in range(dim_x):
ax = figure.add_subplot(dim_x, 1, i + 1)
... |
ff3ea47cfe2f21e3172ae291bb1db0dbd1ed3584254589559c473415b2ed646e | Python | 1,388 | 31 | import yaml
from pathlib import Path
from . import config
from .utils.ica import ICAHandler
if __name__ == "__main__":
# Parameters
LAYERS = config["layers"]
COMPONENTS = config["selected_components"]
for layer_name in LAYERS:
print(f"Processing {layer_name}")
# ica_model_file_top_10... |
0bd13cc682bb0b3729eb1caa0c34b4d2f998adb522546033ae4a162ca98b6d30 | Python | 1,392 | 43 | from pathlib import Path
import pandas as pd
from steinbock import io
from steinbock.export import graphs
class TestGraphsExport:
def test_convert_to_networkx(self):
neighbors = pd.DataFrame(
data={
"Object": [1, 2],
"Neighbor": [2, 1],
"Distan... |
9dc3711e54ef12035901ab63f0d655947ebf1fbf2a4c64f01368ab079d992c22 | Python | 1,392 | 30 | # 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... |
eff0d249fe229039368ba93d9f9769008ef77c6a526acd68fed4e7004832d85d | Python | 1,394 | 43 | from pathlib import Path
from typing import List, Optional, Sequence
import cv2
import numpy as np
from ._base import BaseLoader
from ..transforms import BaseTransform
__all__ = ['ImageSet']
class ImageLoader(BaseLoader):
def __init__(self, flag: int = cv2.IMREAD_GRAYSCALE):
self.flag: int = flag
... |
e436d1debadbb9fba8726569235b92fbe0d311e6aff07061cc5dbb06465cbc61 | Python | 1,395 | 49 | from pandas import read_csv
import numpy as np
import pandas as pd
def reduceDataset(globalIndex, run) :
# data used for the predictions
if(globalIndex==0):
dfData = read_csv("../data/data_"+str(globalIndex)+".csv", header=None, sep=',')
ids=read_csv("../data/features_"+str(globalIndex)+".csv", header=None, ... |
4440760e71614f9a6471e03661a6a7cd67f1804d1efbbecd6143682f1319d9fb | Python | 1,396 | 41 | import pytest
import numpy as np
from brian2 import Network, seed
from hsnn.core import NeuronClass
from hsnn.core.config import ModelParams
from hsnn.core._brian2.groups import COBAFactory
from hsnn.core._brian2.layer import PoissonLayer, SpatialLayer
@pytest.fixture(autouse=True)
def set_seed():
seed(42)
@p... |
98dc8498007cd15759ff24fece9231a6cd4d5816def48ee5cbe858643c27c5ce | Python | 1,397 | 42 | import cv2 # type: ignore
import numpy as np
def extract_frame_of_movie(tiff_movie, frame_number, output_file):
"""Extract a certain frame of tiff_movie, and write it into a separate file. Used for testing find_frame_of_image
Args:
tiff_movie (str): path to input
frame_number (int): which frame to extract
Rai... |
3eec6f0bc34a6bb7e83d6ba96ffe4cdd06410d0bf9a8facbcf282a5303203711 | Python | 1,398 | 32 | import os
from batchgenerators.utilities.file_and_folder_operations import *
from nnunetv2.paths import nnUNet_raw
from nnunetv2.utilities.utils import get_filenames_of_train_images_and_targets
if __name__ == '__main__':
# creates a dummy dataset where there are no files in imagestr and labelstr
source_datas... |
18537c4e8cbf3b19acec2418787e5c929ce57ea07df654a811ffad09b797aaab | Python | 1,399 | 45 | import os
import re
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from smma.src import statistics, utilities
from loguru import logger
logger.info('Import OK')
input_folder = 'results/spot_detection/count_spots/'
output_folder = 'results/spot_detection/comparison/'
if n... |
330eca3630ab3f09139afc2dc02462d102343349ff4be3b0c0f8cf03c6deade3 | Python | 1,401 | 49 | import dataclasses
from typing import List
@dataclasses.dataclass
class MethyAnnoConfig:
"""
Hyperparameter configurations for the MethyAnno model.
"""
# 1. Random Seed
seed: int = 123
# 2. Network Architecture & Dimensions
subspace_dim: int = 8
hidden_dim: int = 256
dropout_ra... |
a9cd1976c4f8185e53021442bc724f70e620ec3ec32df381e5de106d61a2bb94 | Python | 1,402 | 55 | import pytest
from chemprop.models import MolAtomBondMPNN
from chemprop.nn import MSE, MABBondMessagePassing, MeanAggregation, RegressionFFN
@pytest.fixture
def mp():
return MABBondMessagePassing()
@pytest.fixture
def agg():
return MeanAggregation()
@pytest.fixture
def ffn():
return RegressionFFN()
... |
fd79265c40a9da40ade71d1d671ff2b86a5586db1bde497e7f158d789c9836a7 | Python | 1,403 | 49 | # Copyright (c) 2014 10X Genomics, Inc. All rights reserved.
"""Values used in many other modules."""
from __future__ import annotations
######################################################
# DO NOT add new items to this file.
#
# - If a constant is only used from a single module, put it in that module.
# - If a c... |
4d01494abe1a73c8dc2255aa354bfd7f3e1bfdb34f780ad6e4b0569371af94bd | Python | 1,405 | 42 | import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
data = pd.read_csv('tSNR.csv')
use_var = True
error = 'sd'
if use_var:
data.loc[data['dType'] == 's_signal/s_noise', 'Value'] **= 2
fig, axs = plt.subplots(1, 4, figsize=(16, 4))
for dtype, ax in zip(['mu_signal/s_noise',
... |
535de871c56e8bce5190397307ba1b9e67fbb65a1ab9841cb4ad8a0d5019c372 | Python | 1,406 | 45 | """
Scrapper for sphinx-gallery to capture vtk figures.
"""
# This is shamelessly copied from PyVista
from .base import Plotter
from ..vtk_interface.wrappers import BSScalarBarActor
def _get_sg_image_scraper():
return Scraper()
class Scraper(object):
def __call__(self, block, block_vars, gallery_conf):
... |
05efa645324a76903a7cd161783b34f765904bc595d4405bc68dbfada06ffb62 | Python | 1,408 | 34 | import psi4
from openmm.app import element
# This script uses Psi4 to compute the per-atom reference energies that appear in the downloader script.
# It is included here in case we want to add more elements in the future.
charges = {'B': (-1, 0, 1), 'Br': (-1, 0), 'C': (-1, 0, 1), 'Ca': (2,), 'Cl': (-1, 0), 'F': (-1,... |
c19cd8fe2bd15f39376fd02835962665366c9a666a04b13a12426d550a86ab93 | Python | 1,409 | 40 | import os
import pandas as pd
from loguru import logger
from src.utilities.databases import network_interactions, create_uniprot_xref
logger.info('Import OK')
input_path = 'results/preprocessed/ratio_summary.csv'
output_folder = 'results/protein_interactions/'
resource_folder = 'resources/bioinformatics_databases/'
... |
4c41f29f34a47eb8f05f3269128818ea716e48178338a9734ee51d3e8fac5d31 | Python | 1,410 | 53 | import torch
from torch import nn
class SimpleRegressor(nn.Module):
"""_summary_
Args:
nn (_type_): _description_
"""
def __init__(self, in_features=768, out_classes=40):
super(SimpleRegressor, self).__init__()
self.seq = nn.Sequential(nn.Linear(in_features, out_classes))
... |
e7b9e9d99c5e8f470bb21bffa522068f08d7fe6669178e32993924e202ba2660 | Python | 1,410 | 20 | #python fastaHeaderUniprot.py < L:\promec\TIMSTOF\LARS\2025\251103_STEVEN\Araport11_pep_20250411.fasta > L:\promec\TIMSTOF\LARS\2025\251103_STEVEN\Araport11_pep_20250411.uniprot.fasta
#python fastaHeaderUniprot.py < L:\promec\TIMSTOF\LARS\2025\251103_STEVEN\Araport11_pep_20250411_representative_gene_model.fasta > L:\pr... |
4706c437c83607c933db8e57c3e641530d260d07e4318c5ba4431bb0e0941f02 | Python | 1,412 | 37 | import torch
def compute_mean_mad(dataloaders, label_property):
values = dataloaders['train'].dataset.data[label_property]
meann = torch.mean(values)
ma = torch.abs(values - meann)
mad = torch.mean(ma)
return meann, mad
edges_dic = {}
def get_adj_matrix(n_nodes, batch_size, device):
if n_nodes... |
d4faa90f7bd506e44de4e1efe43471c2e01591c036129b3fa132c9d5edac24a8 | Python | 1,412 | 61 | """ Created on Sun Sep 24 14:51:36 2023
@author: dcupolillo """
import spyne
from pathlib import Path
date = "240827"
cell_n = "cell0002"
data_folder = Path("data")
imaging_folder = data_folder / date / cell_n
# ======================
# Dataset initialization
# ======================
dataset = spyne.ImagingData... |
b48cac5f1f133c272ecf3347ee01186794cfc81c295a9f1f245a6a7bcbd4174f | Python | 1,421 | 41 | # Copyright (c) Facebook, Inc. and its affiliates.
# pyre-unsafe
import torch
class ImageResizeTransform:
"""
Transform that resizes images loaded from a dataset
(BGR data in NCHW channel order, typically uint8) to a format ready to be
consumed by DensePose training (BGR float32 data in NCHW channel... |
ac28ee3e1722329526c90e2f9f5cd3f68f91196468b9d877e045dd709460a209 | Python | 1,422 | 56 | import argparse
from composer.utils import dist
from omegaconf import DictConfig
from omegaconf import OmegaConf as om
from pathlib import Path
from typing import cast
import logging
import torch
from train import TrainWrapper
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument("--yaml-fi... |
d77402ff336f979738c559160372ad2de8002dee78374dda645a6f8f72134b4a | Python | 1,423 | 69 | #!/usr/bin/env python
# By HT
import os
import pdb
import optparse
import multiprocessing
from multiprocessing import Process, Lock
import sys
################
# global variables
################
lock = Lock();
################
# functions
################
def runCommand(c):
lock.acquire()
lock.release()
... |
dd11409db5ca9b2d704aa9b1ac67a82b96b77165246c733fc87869981def43b7 | Python | 1,424 | 48 | from detectron2.config import LazyCall as L
from detectron2.layers import ShapeSpec
from detectron2.modeling.box_regression import Box2BoxTransform
from detectron2.modeling.matcher import Matcher
from detectron2.modeling.roi_heads import (
FastRCNNOutputLayers,
FastRCNNConvFCHead,
CascadeROIHeads,
)
from .... |
2afc5841fda3d5cb223618858780ab5f2c644769e43c64f3999d1efcde8c3de1 | Python | 1,427 | 52 | #!/usr/bin/env python
#
# Copyright (c) 2017 10X Genomics, Inc. All rights reserved.
#
import os
import cellranger.analysis.constants as analysis_constants
import cellranger.analysis.io as analysis_io
import cellranger.cr_io as cr_io
__MRO__ = """
stage COMBINE_CLUSTERING(
in h5 kmeans_h5,
in path kmean... |
b17f13637d8026d2f42067a2360058ac3883844111b46d074406bcaaff6b07de | Python | 1,432 | 45 | """Shared fixtures and the reference-runs discovery used by the parity tests."""
import os
import sys
from pathlib import Path
import pytest
REPO_ROOT = Path(__file__).resolve().parent.parent
# scripts/ is not a package; the config and parity tests import from it.
if str(REPO_ROOT / "scripts") not in sys.path:
s... |
19dd138a684ba2f05381c08845f04c2feaabdb89f0592f93ae9e573b72c1c7b0 | Python | 1,433 | 48 | from __future__ import print_function
import numpy as np
from PIL import Image
import numpy as np
import os
import matplotlib.pyplot as plt
import torch
def load_image(path):
if(path[-3:] == 'dng'):
import rawpy
with rawpy.imread(path) as raw:
img = raw.postprocess()
elif(path[-3:]... |
36b18a578843fa1c51cd849f670fb4622024aa7f36be75881a6285ba6acb3957 | Python | 1,434 | 46 | # Copyright (c) Facebook, Inc. and its affiliates.
# pyre-unsafe
import random
from collections import deque
from typing import Any, Collection, Deque, Iterable, Iterator, List, Sequence
Loader = Iterable[Any]
def _pooled_next(iterator: Iterator[Any], pool: Deque[Any]):
if not pool:
pool.extend(next(it... |
9f83c52356a8e8b36f8026a215139c1ca64daef6fb59c96e37528d9c3fcb5b4d | Python | 1,438 | 49 | # Record RMSD over validation simulations
import MDAnalysis as mda
from MDAnalysis.analysis import rms
import matplotlib.pyplot as plt
import numpy as np
import os
run_name = "64_7_ep12"
n_reps = 3
smooth_n = 10
selector = "backbone"
with open("proteins.txt") as f:
proteins = [l.rstrip() for l in f.readlines()]
... |
e726e9d906bd15d809bcf94e93ab8b97079b9d7c4f079ba3cee51b44adcbb0d8 | Python | 1,442 | 45 | import tifffile
from tifffile import TiffFile
def fetch_frame(tif_file):
"""Returns a generator of frames in a tif file
Args:
tif_file (str): path to the tif file of concern
Yields:
numpy ndarray: A matrix representing a frame in the image. Should be two dimensional if the input is graysc... |
4b8f1a89802b417eff1583cbbdbd201f40d32f3a272a6e8f6d4fbdff793836d6 | Python | 1,443 | 26 | import pandas as pd, numpy as np
pep = pd.read_csv('dynamicrangebenchmark/peptides.txt', sep='\t', low_memory=False)
msp = pd.read_csv('dynamicrangebenchmark/modificationSpecificPeptides.txt', sep='\t', low_memory=False)
# How many peptide sequences appear in both with different intensities?
int_cols_pep = [c for c i... |
7180646829e4f59dd4c002982a3877b5ff6e33be2a1d5b4e6e1422e24a05ba7e | Python | 1,444 | 52 | from pymol import cmd
from random import random
import time
# this shows how you can efficiently update the coordinates
# of an existing model for real-time viewing
# for asychronous execution, you may want to run this using the "spawn"
# command from inside PyMOL or with the "-l" option from the unix shell
... |
1c69b2246957e85fabf1909a5d6b02651255ade64c7ae55b76af8bd9f8a1000b | Python | 1,452 | 39 | from typing import Optional
import requests
from batchgenerators.utilities.file_and_folder_operations import *
from time import time
from nnunetv2.model_sharing.model_import import install_model_from_zip_file
from nnunetv2.paths import nnUNet_results
from tqdm import tqdm
def download_and_install_from_url(url):
... |
02e1298e3ded8748a8187e2824d774616a51901e42e3dd1a7be3d19fee47cdcd | Python | 1,453 | 57 | # In[74]:
import numpy as np
import tensorflow as tf
print(tf.__version__)
# In[74]:
from tflite_model_maker import configs
from tflite_model_maker import ExportFormat
from tflite_model_maker import model_spec
from tflite_model_maker import image_classifier
from tflite_model_maker.image_classifier import DataLoader
as... |
faecae91b71525a37537d44c6792fd71d083fd576cd426f625c8fc6b9130e805 | Python | 1,454 | 45 | import argparse
import csv
import glob
import os
import pandas as pd
parser = argparse.ArgumentParser()
parser.add_argument("--formats", nargs="+", required=True)
parser.add_argument("--lags", nargs="+", type=float, required=True)
parser.add_argument("--lags-final", nargs="+", type=float, required=True)
parser.add_ar... |
40ceca66c92b34f2322c2c533f4dbb35c330bb0d869840c1bca59ce118b2aa06 | Python | 1,457 | 43 | """Tests for plotting.colormaps registrations and BuGyRd interpolation (#91)."""
import numpy as np
from brainspace.plotting.colormaps import (
colormaps, yeo7_colors, eco_kos_colors, spec_5_colors, BuGyRd,
)
def test_registered_names():
for name in ('yeo7', 'eco_kos', 'spec_5', 'BuGyRd', 'cat35'):
... |
e6186415913c94c7316d77ab03d1dc75c023afe0bff6de2a60d107faaab4ed76 | Python | 1,457 | 54 | import pandas as pd
import numpy as np
from sklearn.impute import KNNImputer
from sklearn.preprocessing import StandardScaler
file_path = "PATH_TO_INPUT_CSV/..." #Data with missing values
output_path = "PATH_TO_OUTPUT_DIR/imputed.csv"
df = pd.read_csv(
file_path,
encoding="latin1",
header=1
)
df = df.dro... |
aeba295d3ff86ab7060a672fe1b9c1e220047d6dec4290cfa422f2c2be5cd9e7 | Python | 1,458 | 39 | ############################################################################
# Copyright (c) 2022-2026 University of Helsinki
# Copyright (c) 2019-2022 Saint Petersburg State University
# # All Rights Reserved
# See file LICENSE for details.
############################################################################
... |
950be40e42df1035ee9781f20ada5477bb86014b370fb464799ab2dda36a5039 | Python | 1,460 | 50 | # This code is part of OpenFE and is licensed under the MIT license.
# For details, see https://github.com/OpenFreeEnergy/openfe
import logging
import pathlib
import click
from plugcli.cli import CLI, CONTEXT_SETTINGS
from plugcli.plugin_management import FilePluginLoader
import openfecli
from openfecli.plugins impo... |
9a840a7b449a8939299c63761f3e6cf39a8f6921ddaf236ce8efd7468beb0084 | Python | 1,467 | 39 | import numpy as np
import pickle
from matplotlib import pyplot as plt
import os
from rCPGswCPG.Network import firing_rate
from rCPGswCPG.Network import construct_model
from rCPGswCPG.model_params.config_loader import load_model_cfg_file, model_params_from_cfg
from rCPGswCPG.utils.gen_utils import get_project_root
mode... |
0fdc2e99d835b33d8db1f8992a13d60619a587cd2f1b3230f1fea2d0e478f0da | Python | 1,468 | 37 | import shutil
from batchgenerators.utilities.file_and_folder_operations import isdir, join, load_json, save_json
from nnunetv2.utilities.dataset_name_id_conversion import maybe_convert_to_dataset_name
from nnunetv2.paths import nnUNet_raw
if __name__ == '__main__':
dataset_name = 'IntegrationTest_Hippocampus_reg... |
ab68461cfe23e5b1e76660c5833bc2e067cf85d1cbbfa53917a50315d1394895 | Python | 1,468 | 44 | """
Analysis module for spine detection.
This module contains functions for detecting and segmenting dendritic spines.
"""
from deepd3.inference.detection import inference
from deepd3.inference.post_processing import process_prediction, process_predictions
from deepd3.inference.post_processing_utils import (
thre... |
c72086089d1568ea9e6194251ef3dd6b2c1be732d4e34ef87db9639038bc90e9 | Python | 1,468 | 43 | import torch
import lpips
from IPython import embed
use_gpu = False # Whether to use GPU
spatial = True # Return a spatial map of perceptual distance.
# Linearly calibrated models (LPIPS)
loss_fn = lpips.LPIPS(net='alex', spatial=spatial) # Can also set net = 'squeeze' or 'vgg'
# loss_fn = lpips.LPIPS... |
fa9473c3fc9cff0361e56b69e4cbaad7e4746b953dd266ab38bcfd8d26d4a540 | Python | 1,470 | 52 | """Shared plotting utilities and global style."""
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
PALETTE = sns.color_palette("deep")
def apply_global_style():
"""Apply consistent matplotlib styling for all figures."""
mpl.rcParams.update({
'font.fami... |
c9e59b647f075d051af2675f2c34bf74e3db9bc484836d10016051becad5d304 | Python | 1,471 | 35 | # 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... |
280972ab707cdbb2be2e9f4a23919dc075ab5eafa79619775e69a29310afcd50 | Python | 1,474 | 43 | #%% imports
import sys
sys.path.append('/mnt/obob/staff/fschmidt/cardiac_1_f/')
from cluster_jobs.bay_pred_cam_can_irasa import BayesPred
from plus_slurm import SingularityJobCluster, PermuteArgument
import os
#%% get jobcluster
job_cluster = SingularityJobCluster(required_ram='4G',
request_t... |
8d7e3b997421949be17585e98ebb7bc61ee663c0a3a7605368f10b21a8758b98 | Python | 1,474 | 45 | from collections import defaultdict
from typing import Iterable, Sequence
from hsnn.analysis import png
from hsnn.core.logger import logging
logger = logging.getLogger()
def chunks(lst, k):
"""Yield k nearly-equal slices of lst.
"""
n = len(lst)
step = (n + k - 1) // k
for i in range(0, n, step)... |
43e606d8b9cd7f5f454bd46f753e67a5d21955dfc81e6bfc8d2c2741c28215d8 | Python | 1,475 | 51 | #https://docs.pymc.io/notebooks/stochastic_volatility.html
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_context('talk')
import pymc3 as pm
from pymc3.distributions.timeseries import GaussianRandomWalk
from scipy import optimize
import pandas as pd
n = 400
returns = pd.read_csv(pm.ge... |
54cbf64b70cb30f4039ee2f9da2433a0139d107fb2abba77eb44db36354c9080 | Python | 1,475 | 43 | #%
from plus_slurm import Job
#%
from os import listdir
from mne_bids import BIDSPath, read_raw_bids
import mne
import numpy as np
import pandas as pd
#%%
class MovementJob(Job):
def run(self,
subject_id):
#% read data
base_dir = '/mnt/obob/camcan/cc700/meg/pipeline/release005/BIDSsep/... |
3b250ae241f75c71d27e7399b294b368a0e713dc1cc034490ffcce7fe55f6ebc | Python | 1,477 | 35 | from pathlib import Path
import numpy as np
import torch
from . import config
from .utils.pca import PCAHandler
if __name__ == "__main__":
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Parameters
LAYERS = config["layers"]
NUM_COMPONENTS_FULL = config["pca"]["num_components... |
38986850bc1336bd26dfb14bef416a16f820a5c1047fc9b024687198d7059bef | Python | 1,480 | 60 | import os, logging
from urllib.request import urlopen
def download_data(url, outfile='', binary=False):
"""
Downloads data from a URL and returns raw data.
Parameters
----------
url : str
URL to get the data from
outfile : str, optional
Where to save the data.
binary : boo... |
45ba92e9e91641fc21138de7f26130b058a4b5cd2ce433ffdb6445affaa453bf | Python | 1,480 | 45 | import os
import argparse
import nibabel as nib
def extracted_brain_output(directory, output_file):
# Find files with "brain" in the name
brain_files = [f for f in os.listdir(directory) if "brain" in f and "mask" not in f and os.path.isfile(os.path.join(directory, f))]
if len(brain_files) < 2:
rais... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.