sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
7553fbaeebee8b6ae01532baf6b70b80316c20ecfc8b65c6227f5a84a33d2a4f | Python | 2,462 | 26 | from testsetclass import TestsetClass
class IL16(TestsetClass):
def __init__(self):
self.weak = 1.0
self.molecules = ['202B', '150', '228A', '227B', '229', '227', '230A', '213B', '228', '152B', '212A', '008A', '214B', '150A', '202', '008', '231B', '187A', '187', '144B', '144', '229B', '147B', '148... |
447c6d54e24e0d1e575bea52fd3980196f97207ed06deadfd9e60744b8befdaf | Python | 2,464 | 94 | # -*- coding: utf-8 -*-
"""TODO"""
import os
from datetime import datetime
from enum import Enum
from functools import total_ordering
@total_ordering
class LogMessageType(Enum):
VERBOSE = 1
INFO = 2
NOTIFICATION = 3
SETTINGS = 4
PROGRESS = 5
WARNING = 6
ERROR = 7
def __lt__(self, oth... |
c435a1c309c15fb1806f0eec4d2cc5ee66279b587c85fca0a5f99f3fe8cbc8df | Python | 2,464 | 80 | import jax.numpy as jnp
import matplotlib.pyplot as plt
import os
plt.rcParams["font.sans-serif"] = ["DejaVu Sans"] # Best available
plt.rcParams["font.family"] = "sans-serif"
plt.rcParams.update({
"font.size": 10,
"axes.titlesize": 10,
"axes.labelsize": 8,
"xtick.labelsize": 8,
"ytick.labelsiz... |
7807fd9e9ed7950828f7c59324db83f7905c68fcfe4cef3c0ae4efd77b00008b | Python | 2,465 | 60 | #!/usr/bin/env python3
# https://github.com/CoBiG2/cobig_misc_scripts/blob/65d94918dfe31f3ec5c6a113a7402ae01d0b34ea/FDR.py
# Copyright 2017 Francisco Pina Martins <f.pinamartins@gmail.com>
# This file is part of structure_threader.
# structure_threader is free software: you can redistribute it and/or modify
# it unde... |
3c34c01c542ac5e007ddcca1ae78c9792ee41f88ea7c80124a43667caa8a492a | Python | 2,466 | 72 |
from pathlib import Path
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
cur_path = Path.cwd() / "data" / "txt_fig4a.txt"
with open(cur_path) as f:
lines = [line.split("\t") for line in f]
data_set = np.zeros((len(lines), 2))
for ith_ele in list(range(0, len(lines))):
cur_list = li... |
4bb5666208e4e93469ec76edc704806c4eb654b82dbed86bfe6d1e9f1b211017 | Python | 2,466 | 83 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Converts a RGB image encoded as a 4D image to a RGB image encoded as
a 3D image, or vice versa.
Typically, most software tools used in the SCIL (including MI-Brain) use
the former, while Trackvis uses the latter.
Input
-Case 1: 4D image where the 4th dimension contai... |
90f9199adc997839fc4d1de67d780637ab27f610eb9556d6be3aa9e8d6a0735e | Python | 2,466 | 90 | #!/usr/bin/env python
"""
The filmSettings object.
Hazen 04/17
"""
class FilmSettings(object):
def __init__(self,
acq_mode = "fixed_length",
basename = "",
filetype = "",
film_length = 0,
overwrite = True,
pixel... |
2fe18375ff9b6e3f08f866438024366df4dbbbba31ce5aef710e9f5c8f51b668 | Python | 2,467 | 76 | import pytest
from tests.test_models.model_testing_utils import (
check_eir_model,
prepare_example_test_batch,
)
@pytest.mark.parametrize(
"create_test_data", [{"task_type": "multi_task"}], indirect=True
)
@pytest.mark.parametrize(
"create_test_config_init_base",
[
# Case 1: Classificatio... |
a56e60e4542d1239b3e28e388ceb7211b7b671f7bb0293c1ee8fd2db2071edce | Python | 2,467 | 75 | # coding: utf-8
# (C) Copyright 2019 IBM Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... |
00067963491f8fd789727f02d2b236cc5604d31ccc2f8d2fff3bda219ab4f4d8 | Python | 2,468 | 57 | import networkx as nx
from zigzag.classes.workload.layer_node import LayerNode
from typing import Dict, Any
from networkx import DiGraph
class DNNWorkload(DiGraph):
def __init__(self, workload: Dict[Any, Dict], mapping: Dict[Any, Dict], **attr):
"""
Collect all the algorithmic workload informatio... |
06d0b94af4ece44b2621f8387422736e9921a10646c899db122541bdb1492219 | Python | 2,468 | 57 | import datajoint as dj
from neuro_data.static_images.data_schemas import StaticMultiDataset
from staticnet_experiments import models as static_models, zd_models
from staticnet_analyses import base
schema = dj.schema('zhiwei_neurostatic_base')
@schema
class TestNeurons(dj.Lookup):
definition = """
-> StaticMul... |
31bdda0b36c83d03e7bfa3f9b4103620c5d67ea592e4b420cf07293247ef25e0 | Python | 2,468 | 63 | import torch
from batchgeneratorsv2.helpers.scalar_type import RandomScalar, sample_scalar
from batchgeneratorsv2.transforms.base.basic_transform import ImageOnlyTransform
class MultiplicativeBrightnessTransform(ImageOnlyTransform):
def __init__(self, multiplier_range: RandomScalar, synchronize_channels: bool, p... |
c5df9f67f2317932d7265f903ae1e6afdc59720eeb6781541219647acf62df94 | Python | 2,468 | 85 | #!/usr/bin/env python3
from optparse import OptionParser
USAGE = """
python write-chunk-coords.py --fai <genome fai index> --gaps <gap bed file> --out <output segments file>
--mingap <int default=2000>
writes list of genome segments seperated by gaps
for use when splitting up genom... |
321bc2014be9ff60905a5ae747176c663ebd992f888fbfab200a0c08feb72be2 | Python | 2,469 | 98 | import arbor as A
from arbor import units as U
import matplotlib.pyplot as plt
from pathlib import Path
import numpy as np
import ctypes
E = np.zeros(shape=(3,), dtype=np.float64)
buf = ctypes.c_double * 3
addr = ctypes.addressof(buf.from_buffer(E))
ctr = "(location 0 0.5)"
here = Path(__file__).parent
mrf = A.load... |
76010daacfb6e85909dfc7ad4d44d88c8f834ab349635f01b0dc570fb2eef0eb | Python | 2,469 | 75 | from __future__ import annotations
import functools
from PySide6 import QtCore
from ._save_request import SaveRequest
from ._save_request import write_save_request
def _write_and_notify(
request: SaveRequest, completed: QtCore.SignalInstance, /
) -> None:
try:
write_save_request(request)
except... |
76f39c54fe5b5989284d9f9271d4208ab776d3cb7f818f5890c326c1ae3d8788 | Python | 2,470 | 71 | from torch.utils.data import DataLoader
from geoseg.losses import *
from geoseg.datasets.potsdam_dataset import *
from geoseg.models.FTUNetFormer import ft_unetformer
from catalyst.contrib.nn import Lookahead
from catalyst import utils
# training hparam
max_epoch = 45
ignore_index = len(CLASSES)
train_batch_size = 4
v... |
4b2945ea440e67045d6e27f4cc76875271156ad0495087ff73d3407a1fbce909 | Python | 2,473 | 81 | """
Download the demo data
"""
import os
import shutil
import zipfile
from tensorflow.keras.utils import get_file
PROJECT_DIR = "demos/paired_mrus_prostate"
os.chdir(PROJECT_DIR)
DATA_PATH = "dataset"
ZIP_PATH = "example-data-mrus"
ORIGIN = "https://github.com/yipenghu/example-data/archive/mrus.zip"
zip_file = ZIP_... |
9f1d156f467e99cd3e26ca26e2323f0e0939fcf5210eba6b88f7699beb234cbf | Python | 2,473 | 75 | # Copyright (C) CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT
import math
from collections.abc import Iterator
import numpy as np
import PIL.Image
from skimage import measure
from torch import Tensor
import cvat_sdk.auto_annotation as cvataa
import cvat_sdk.models as models
from cvat_sdk.masks import encode_m... |
aa81a379a6a55ca5cb9259938b7219a72003b766121572be260746d18fbb3bd3 | Python | 2,473 | 66 | # image_prep.py
import argparse
import numpy as np
import torch
from utils import get_calibration_data_loader
def main():
parser = argparse.ArgumentParser(description="Prepare calibration tensors for PTQ.")
parser.add_argument("--calibration_data_size", type=int, default=20, help="Number of images to save.")... |
9097b2a599fa989092cdcbd0758eaa563c49fde34e02b78edea029e1cf521404 | Python | 2,474 | 73 | import nibabel as nib
import numpy as np
import AFQ.recognition.other_bundles as abo
# Example data for testing
this_bundle_sls_sample = np.array(
[[[0, 1, 2], [1, 2, 3], [2, 3, 4]], [[1, 2, 3], [2, 3, 4], [3, 4, 5]]]
)
other_bundle_sls_sample = np.array(
[[[0, 1, 2], [1, 2, 3], [2, 2, 2]], [[1, 1, 1], [2, 2,... |
d8b46702deb0893362df042fce8a4cc83c19afa94d85839b70eb1549402f5283 | Python | 2,474 | 77 | #!/usr/bin/env python3
"""
Example case: validate one preprocessed BraTS image/mask pair.
Usage:
python src/examples/example_case.py --image path/to/image.npy --mask path/to/mask.npy
"""
from __future__ import annotations
import argparse
from pathlib import Path
import numpy as np
def parse_args() -> argparse.Nam... |
103400aef35fc71588610c5eaceffab1972d4c5f34e547797f91d28b439c3dc6 | Python | 2,475 | 57 | import sys
from distutils.core import setup
import py2exe
import numpy # WARNING: requried to avoid a dll error message
import os
from os.path import expanduser
# data_files = [("Microsoft.VC90.CRT", glob(r'C:\Program Files\Microsoft Visual Studio 9.0\VC\redist\x86\Microsoft.VC90.CRT\*.*'))]
# data_files = [("Micros... |
b5039f8524cf0276c2d21dd2a20b9d68dbf9e3a36cf692bb0d77af33a2dec037 | Python | 2,475 | 50 | import nighres
import os
import nibabel
import numpy
import glob
import scipy.ndimage
indir = '/home/pilou/Projects/Cerebellum/Cerebellar-segmentation-ABC/ahead/topology/'
prevdir = '/home/pilou/Projects/Cerebellum/Cerebellar-segmentation-ABC/ahead/tissues/'
outdir = '/home/pilou/Projects/Cerebellum/Cerebellar-segment... |
ed0a737c7be930624cac4e5cac6a702c1adaef89b996335d71574abb9c1c97be | Python | 2,475 | 71 | from collections import OrderedDict
import numpy as np
from brainscore_core.supported_data_standards.brainio.assemblies import walk_coords
def collect_coords(assembly, ignore_dims, rename_coords_list, kind):
coords = assembly.coords
filtered_coords = filter_coords(coords, ignore_dims=ignore_dims)
rename... |
5d0f096211919cad369e548d920de5e09396ec19467a58cdb7daf67f675ee352 | Python | 2,476 | 61 | '''
====================================================================================================================================
Version: 12/01/2024
Author: Lucas Berg (@bergolho)
====================================================================================================================================... |
d258108110216fbef82101520918301150490270c934bd49ebd8efd6cd6057da | Python | 2,476 | 88 | '''
Script to convert a set of images in EXR to PNG
Starts by opoening all images and saving the max and min values.
We will use this values to normalize all images
'''
import os
import numpy as np
os.environ["OPENCV_IO_ENABLE_OPENEXR"] = "1"
import cv2
from os.path import join
import matplotlib.pyplot as plt
impor... |
e5602a09f45790cb43d530a71af4633b477a23555f1265379c269bb78c66302b | Python | 2,476 | 53 | # Copyright (c) 2026 Rohit Jena. All rights reserved.
#
# This file is part of FireANTs, distributed under the terms of
# the FireANTs License version 1.0. A copy of the license can be found
# in the LICENSE file at the root of this repository.
#
# IMPORTANT: This code is part of FireANTs and its use, reproduction, or... |
057d64fd268dddb843ec827d48f3aeadaa1da4ce2390f4fd728a902cbc1b315d | Python | 2,477 | 67 | """A module that contains unit tests for the :py:mod:`corelay.processor.laplacian` module."""
import numpy
import pytest
import scipy
from sklearn.datasets import make_blobs
from corelay.processor.affinity import SparseKNN
from corelay.processor.distance import SciPyPDist
from corelay.processor.laplacian import Rando... |
6361672b8fa3a8a54ae16aa9f4564f84e87f9839c46186d89e8ae76eafc47822 | Python | 2,477 | 73 | import re
import runpy
import sys
from glob import glob
from pathlib import Path
import pytest
from magicgui import type_map, use_app
@pytest.mark.parametrize(
"fname",
[
f
for f in glob("docs/**/*.md", recursive=True)
if "_build" not in f and Path(f).read_text(encoding="utf-8").star... |
49b9fb1977db8d45492d86f7aac619c0efc0c0d247565a9c7b6feddd668d778d | Python | 2,478 | 83 | from typing import TYPE_CHECKING
import pytest
from torch.utils.data import DataLoader
from eir.data_load import datasets
from eir.data_load.data_utils import consistent_nan_collate, get_finite_train_sampler
from eir.setup import config, input_setup
from eir.setup.output_setup import set_up_outputs_for_training
if T... |
e341ae12cd08b6c5040ecd46359cff6796c56582fa0aa3a780dffb96f537fae5 | Python | 2,478 | 50 | import nighres
import os
import nibabel
import numpy
import glob
import scipy.ndimage
indir = '/home/pilou/Projects/Cerebellum/Cerebellar-segmentation-ABC/ahead2/topology/'
prevdir = '/home/pilou/Projects/Cerebellum/Cerebellar-segmentation-ABC/ahead2/tissues/'
outdir = '/home/pilou/Projects/Cerebellum/Cerebellar-segme... |
771e57775497b61ef86ee3c94206bcde4f4eeb35578e3f35c127e50d44e5b399 | Python | 2,479 | 124 | """These are the main Widgets provided by magicgui.
While the primary API is to use the :func:`@magicgui <magicgui.magicgui>` decorator,
one can also instantiate widgets directly using any of these objects.
The :func:`create_widget` function is a helper function that will auto-pick and
instantiate the appropriate wid... |
c05cb0e1173247c8627ea6854f1c0d5689a005323e4115c3ba26ace0e44f7627 | Python | 2,479 | 88 | #!/usr/bin/env python
"""Direct LocalBackend demo: thermochemistry screen of 5 small molecules.
Runs entirely on the laptop, no LLM, no HPC. Submits 5 MACE
``driver="thermo"`` jobs to a ``LocalBackend`` ProcessPoolExecutor,
gathers the results, prints a property table, and writes a CSV.
Run::
python scripts/demo... |
03d5c992f30794e6282198173eb1a5460e9cc4ac8497e769b5fa733a01ebf5d7 | Python | 2,480 | 73 | import numpy as np
import nibabel as nib
from scipy.ndimage import distance_transform_edt
import sys
import argparse
def argument_parser(argv):
parser=argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter,
description='Dilate parcellation by specific number of voxels (or mm). \nNOTE: Resul... |
65cb950993f04f291b447a6b51ea97d0a7708886e265e86dd2b17e81645db790 | Python | 2,480 | 94 | """Fitter adapters for the A/B test framework."""
from .base import (
SCHEMA_VERSION,
CaseMeta,
FitCase,
FitInputs,
FitResult,
FitterAdapter,
ParamSpec,
ReferenceResult,
load_case,
save_case,
)
from .lmfit_adapters import (
LmfitBaselineAdapter,
LmfitPoissonWeightedAdapt... |
ed294026bcb1788d0d55b470ab02886d5da15767d2ede30ce4973b04786240c1 | Python | 2,481 | 64 | _base_ = [
'RepLKNet_cascade_mask_rcnn_coco.py',
'../_base_/datasets/coco_instance.py',
'../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py'
]
model = dict(
backbone=dict(
channels=[192,384,768,1536],
drop_path_rate=0.7,
),
neck=dict(
in_channels=[192,384... |
f91f50926956d0b9321a5a916f38f0102fade397452a982a549108e4f954b46c | Python | 2,481 | 55 | """Package the Li2026 v3 TEMPORAL assembly (built on EC2 from GoodUnit PSTHs) to S3.
Reuses the already-uploaded Li2026_Stimuli stimulus set.
Source: /Volumes/Hagibis/triple-n/build/Li2026_temporal_assembly.nc
"""
import json
from pathlib import Path
import numpy as np, pandas as pd, xarray as xr
from brainscore_core.... |
5d92a3b5362da6c1e766a4259ac310b7abf587aa6f8ccf6ff5458005da13d5bc | Python | 2,482 | 82 | """
Venous mask from phase data
A binary mask of venous voxels is created from time series phase data. First the
data is scaled to [-pi; +pi]. Then, the time series standard deviation is taken.
Venous voxels are classified by applying a threshold to identify voxels with
large dispersion over time (phase_threshold). Op... |
ec24f43bbf6d5ce8122a9a0266c27e6a7a54b2056fe04f7b4eb0b43981efc2dc | Python | 2,482 | 66 | from __future__ import print_function, absolute_import
import time
from .utils.meters import AverageMeter
from clustercontrast.utils.loss import *
class TLTrainer(object):
def __init__(self, encoder, tri_loss=None, memory=None):
super(TLTrainer, self).__init__()
self.encoder = encoder
self.... |
f40800482bc3f94446652d44e97c9a6980717f450ec7c0071ca0bbb532d34335 | Python | 2,483 | 65 | """ Binary Cross Entropy w/ a few extras
Hacked together by / Copyright 2021 Ross Wightman
"""
from typing import Optional, Union
import torch
import torch.nn as nn
import torch.nn.functional as F
class BinaryCrossEntropy(nn.Module):
""" BCE with optional one-hot from dense targets, label smoothing, thresholdin... |
768134da1d5f3ff630d7f29958a960c6335410875b05424f851602b344f8c9ec | Python | 2,484 | 63 | import torch
class SAM(torch.optim.Optimizer):
def __init__(self, params, base_optimizer, rho=0.05, adaptive=False, **kwargs):
assert rho >= 0.0, f"Invalid rho, should be non-negative: {rho}"
defaults = dict(rho=rho, adaptive=adaptive, **kwargs)
super(SAM, self).__init__(params, defaults)... |
7d71325c6fc5de36dc3cebd3816a87ca663513756c0e9ccf41db178811144755 | Python | 2,484 | 61 | import tensorflow as tf
from keras.layers import Layer
from keras.constraints import Constraint
# TODO: handle frozen parameters
class NemsKerasLayer(Layer):
def __init__(self, nems_layer, new_values=None, new_bounds=None,
regularizer=None, *args, **kwargs):
"""TODO: docs."""
# D... |
005a1581f6c9daf31fe76f2673135126e03f40930d164579e9f6e20c04f8d1f0 | Python | 2,485 | 91 | # coding=utf-8
"""
Tests for deepreg/model/loss/deform.py in pytest style
"""
from test.unit.util import is_equal_tf
import pytest
import tensorflow as tf
import deepreg.loss.deform as deform
def test_gradient_dx():
"""test the calculation of gradient of a 3D images along x-axis"""
tensor = tf.ones([4, 50,... |
555949a64a435e09c069903d4d6b2bafc1e33c3345bb9889dd00860ea8458d9f | Python | 2,485 | 60 | import os
import random
from PIL import Image
import tkinter as tk
from tkinter import filedialog
def select_folder(prompt):
root = tk.Tk()
root.withdraw() # Hide the root window
folder_path = filedialog.askdirectory(title=prompt)
return folder_path
def crop_images(input_folder, output_folder, crop_s... |
9798eabe0bd0910e6b119f1d68582253dbc9ba4f6148338eaa52803366d88a8f | Python | 2,485 | 84 | # @Author : LG
from setuptools import find_packages, setup
def get_version():
try:
from ISAT.__init__ import __version__
return __version__
except ImportError:
raise ImportError("ISAT/__init__.py not found, cannot determine version.")
with open("README.md", encoding="utf-8") as f... |
d7c87a7cf966fb2b878bc78a39dc34b5e71191d1027bf11f4ca51db2004f885f | Python | 2,485 | 73 | """
Tests for `bx.align.lav`.
"""
import unittest
from bx.align import lav
test_lav = "test_data/lav_tests/apple_orange.lav"
class lavTestCase(unittest.TestCase):
def testReader(self):
reader = lav.Reader(open(test_lav))
a = next(reader)
assert a.score == 10286, f"a.score is wrong: {a.... |
7b43da2085657376dd81b583af2be22878dc2af6f4758d391eda3fb9f7bfad07 | Python | 2,486 | 81 | import pandas as pd
from sklearn.ensemble import RandomForestClassifier
import numpy as np
from argparse import ArgumentParser
import json
from sklearn.metrics import accuracy_score, f1_score, recall_score, precision_score
from tqdm import tqdm
parser = ArgumentParser()
parser.add_argument('--dataset', type=str)
args ... |
c1f79943b8ec550a1b0866b1e485c10c37b3f4beebffd518391d6414f973b2f8 | Python | 2,486 | 92 | #! /usr/bin/env python
# Copyright 2015 Numenta Inc.
#
# Copyright may exist in Contributors' modifications
# and/or contributions to the work.
#
# Use of this source code is governed by the MIT
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/MIT.
"""Prepares NAB for a new detec... |
dad5d8955ee789019e7af6899f36015efe9f97323bd10674a3414044b358caac | Python | 2,486 | 76 | from typing import Union, Tuple
from pathlib import Path
import torch
import torch.nn as nn
import os
def get_latest_snapshot(snapshot_path: Union[str, os.PathLike]) -> Union[os.PathLike, None]:
"""
Function to get the latest snapshot file name
Args:
snapshot_path (Union[str, Path]): ... |
136292f10a3a6df559bc2cbbd5cd73a14ec73a59b1aa7fa009c8e89b3b8fc1d4 | Python | 2,487 | 100 | #!/usr/bin/env python3
import sys
sys.path.insert(0, '../optimizer/')
import tensorflow as tf
from tensorflow import keras as K
from auxiliary_functions import collect_data, save_weights_turbomole
from custom_callbacks import PrintMeanPredictionCallback, CustomSaveCallback
from model_creator import ModelCreator
# Se... |
45f15ab19fc096b400bd4a5226a1df97b2b47a2f50e6e86eedf3f77f9e05cc3f | Python | 2,487 | 77 | """
Regression Head for AVPENet.
Transforms the 512-d fused representation into a continuous
pain score in [0, 10].
Architecture: 512 → 256 → 128 → 1 (scaled sigmoid output)
Reference: Section "Pain Regression Head", Equations 21–23.
"""
import torch
import torch.nn as nn
class RegressionHead(nn.Module):
"""T... |
4e7c9a5d93509e4392dea05785ca4723cf03931f0f7b596b4f7c46b32b9db908 | Python | 2,487 | 74 | #!/usr/bin/python
#
## @file
#
# Active X based APTUser control. I never really got this to work.
#
# Hazen 8/09
#
from PyQt5 import QtCore, QtGui, QAxContainer
import sys
import time
#class Cube405(QAxContainer.QAxObject):
# def __init__(self, parent = None):
# QAxContainer.QAxObject.__i... |
bf0887733c7a9050621c6e860d206ffba4908c70361ae3962ef65836cfb638f1 | Python | 2,487 | 87 | #!/usr/bin/env python3
"""Compute TPM from a gene count matrix and gene lengths.
TPM is computed as:
RPK = counts / (gene_length_in_kb)
TPM = (RPK / sum(RPK)) * 1e6
Inputs
------
1) counts matrix TSV
- first column: gene_id
- other columns: samples (numeric counts)
2) gene length TSV
- columns: gene_id,... |
42bf5555b08a2e8f17b67d27b9a23d625d1ab05231fe81f49f2cb5689953555f | Python | 2,488 | 80 | INFO_FILENAME = 'info.txt'
# Default filenames
CDNA_FILENAME = 'cdna.fa'
INTRON_FILENAME = 'introns.fa'
SORTED_FASTA_FILENAME = 'sorted.fa'
SORTED_GTF_FILENAME = 'sorted.gtf'
COMBINED_FILENAME = 'combined.fa'
INDEX_FILENAME = 'transcriptome.idx'
WHITELIST_FILENAME = 'whitelist.txt'
FILTER_WHITELIST_FILENAME = 'filter_... |
7c33f5752cd4a52c5a78d78ffbcff907b0ac99b3fe6ff4a4ee20976ba067a188 | Python | 2,488 | 64 | from sc.fiji.snt import Tree
from sc.fiji.snt.analysis import TreeStatistics, SNTChart
from sc.fiji.snt.io import NeuroMorphoLoader
from sc.fiji.snt.util import ColorMaps
"""
file: Branch_Angles_vs_Distance_To_Soma.py
author: Tiago Ferreira
version: 20250421
info: A Jython demo on how to display two... |
b7796ccf8a43dcfd6acc0e9696407352cb54ba6f7881815fc0c35ea1d23ed7f3 | Python | 2,488 | 79 | import os
from parsl.config import Config
from parsl.providers import LocalProvider
from parsl.executors import HighThroughputExecutor
from parsl.launchers import MpiExecLauncher
from parsl.addresses import address_by_interface
from chemgraph.hpc_configs.loader import resolve_worker_init
def get_aurora_config(
r... |
3f13d64ab7ba3f8da539ea6241091b68fa12c18258de9468a3cd9bd05db5e258 | Python | 2,489 | 83 | #!/usr/bin/env python3
"""
filter-mtp-tables
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Convert MTP TSV table to JSONL
"""
__author__ = ('Eric Wafula (wafulae@chop.edu)')
__version__ = '1.0'
__date__ = '03 March 2023'
import os
import sys
import csv
import git
import gzip
import json
import argparse
import numpy as np
import... |
c2ace21b074f6ee41991622e1e67f59006239ad8136d35d8a126b2b2ba297cbb | Python | 2,489 | 79 | from qtpy.QtWidgets import (
QVBoxLayout, QHBoxLayout,
QLabel,
QComboBox,
QWidget, QGroupBox,
)
import napari
from typing import TYPE_CHECKING
if TYPE_CHECKING:
import napari
class InputDataLayout:
def __init__(self, viewer: "napari.viewer.Viewer"):
self.viewer = viewer
... |
0b7544a6a0eeff3c6018885e15ad7442feb0aec4235c4b9ca26e90e480ad4945 | Python | 2,490 | 84 | import pandas as pd
from sklearn.ensemble import RandomForestClassifier
import numpy as np
from argparse import ArgumentParser
import json
from sklearn.metrics import accuracy_score, f1_score, recall_score, precision_score
from tqdm import tqdm
parser = ArgumentParser()
parser.add_argument('--dataset', type=str)
args ... |
49ea0a24427fdccf8ccdf4ab4f4a11ee951bdba8ab2a99f3ec0f66306dfb44e4 | Python | 2,490 | 70 | import torch
import torch.nn as nn
import torchvision.models as models
# 定义 CoCa 风格的 Transformer 块
class ParallelTransformerBlock(nn.Module):
def __init__(self, dim=256, heads=4, ff_mult=4):
super().__init__()
self.norm = nn.LayerNorm(dim)
self.attn = nn.MultiheadAttention(embed_dim=dim, n... |
5d250cfcae2e8f0c682c414c1af8129d91fca9d26d492ad761d825e45e33684c | Python | 2,491 | 77 | # HyperparameterTuning.py
# short script for model selection and hyperparameter tuning for unit ensemble classifier
# Created on 20DEC23
# 2020 Knowblesse
import os
import numpy as np
import sklearn
if (sklearn.__version__ != '0.23.2'):
raise Exception("scikit-learn package version must be 0.23.2")
from scipy.io ... |
9ffffe1fb5966dc27aadca84aee191f1a982aba973d04aeda3482e37efd35951 | Python | 2,491 | 61 | # src/utils/model_utils.py
"""Reproducibility, early stopping, checkpoint helpers."""
from __future__ import annotations
import random
from pathlib import Path
import numpy as np
import torch
# ───────────────── reproducibility ─────────────────
def set_seed(seed: int) -> None:
random.seed(seed)
np.random.s... |
deac1c5d0c54de4933ffe2c68bb2cf57471672828e7e226586e1303c3214f42e | Python | 2,492 | 68 | from brainvoice.configuration.configuration import Configuration
import numpy as np
import os
import torch
import argparse
import shutil
def init_from_config(device, experiment_subdir, experiment_name):
experiment_name = f'experiments/{experiment_subdir}/{experiment_name}'
experiment_path = os.path.join(exp... |
e60809d7859ca56af36aee45d5fddc3ab0668ad26a484d49498de76ee4a7aaff | Python | 2,492 | 61 | import pytest
from pytest import approx
from brainscore_vision import benchmark_registry, load_benchmark, load_model
@pytest.mark.parametrize('benchmark', [
'Lonnqvist2024_InlabInstructionsBehavioralAccuracyDistance',
'Lonnqvist2024_InlabNoInstructionsBehavioralAccuracyDistance',
'Lonnqvist2024_InlabInst... |
ed0042aebdac3a7e20778a3a053f86b8fe516fb530a674c46e7c6fbdbe2306db | Python | 2,492 | 64 | import pandas as pd
from conftest import fasta_file, exon_file
from mmsplice.exon_dataloader import ExonDataset
def test_ExonDataset():
dl = ExonDataset(exon_file, fasta_file)
required_cols = ('Chromosome', 'Exon_Start', 'Exon_End',
'Strand', 'pos', 'ref', 'alt')
assert all(c in dl.ex... |
9614e2e6bb76b6c1fb7651f7b9a135d2324f6deba391b809ae391e7e39c7940e | Python | 2,493 | 60 | from functools import reduce
import torch
import soma_op
import torch.nn as nn
# define approximate firing function
class SomaActFun(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
# 不使用zeros_like和zeros,因为这两个API都会调用核函数vectorized_elementwise_kernel影响性能,
# 但要确保后端会对tensor的所有数据进行处理,而... |
1d0ffbee534318d2ee2d9680442d631737afb925836261eda6d7721d45092544 | Python | 2,494 | 59 | # cifar10 dataloader
# from sqlalchemy import true
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
from torch.utils.data.distributed import DistributedSampler
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
def Cifar_Data_Load(args, is_training=True):... |
9ccfeb55018bec3ea71c20eb1bdbfac4461169253eacaf443f02fe9e42558145 | Python | 2,496 | 69 | import json
import os
import shutil
import tempfile
from scilpy import SCILPY_HOME
from scilpy.io.fetcher import fetch_data, get_testing_files_dict
# If they already exist, this only takes 5 seconds (check md5sum)
fetch_data(get_testing_files_dict(), keys=['tracking.zip'])
tmp_dir = tempfile.TemporaryDirectory()
de... |
9e826b31697f01d6f29c5731a86fa8d372585e5b584a81be043ff131e9c1d3de | Python | 2,496 | 49 | import os
import sys
import json
from mako.template import Template
sys.path.append(os.path.abspath(os.path.dirname(os.path.realpath(__file__))))
from macularCellFactoryGenerator import load_jsons
def generate_header(json_data, target_dir, mako_dir):
with open(os.path.join(mako_dir, 'macularWidgetsMenuCellParame... |
bbfa0f52385c7b7bb0e93a175e78db90d0ba0ee22d422e6019fb6ed111c8873d | Python | 2,496 | 31 | from testsetclass import TestsetClass
class RC21(TestsetClass):
def __init__(self):
self.weak = 1.0
self.molecules = ['1p2', '2e', '1p3', '7p6', '1p1', '6e', '9p1', 'pr', '7p3', '10e', '7p4', '3p2', '5e', '8p1', '7p2', '2p1', 'me', '3int3', '7p5', 'ethylene', '3p1', '9e', '6p1', '8e', '6p3', '3int... |
16cce351733ddc9119abd284f4c04230d9c7e043b412c7973700310e7f7958ac | Python | 2,497 | 45 | from zigzag.classes.stages import *
import argparse
def main():
# Get the onnx model, the mapping and accelerator arguments
parser = argparse.ArgumentParser(description="Setup zigzag inputs")
parser.add_argument('--model', metavar='path', required=True, help='path to onnx model, e.g. inputs/examples/my_onn... |
b16ca4f936023fa503ed016438603e4f982d4ee65312b69fee8ae19b7bc43b96 | Python | 2,498 | 77 | # -*- coding: utf-8 -*-
"""
Created on Wed Oct 9 11:38:28 2024
@author: Administrator
"""
from pathlib import Path
import dxchange
import numpy as np
import tomopy
# Loads tomo_00089 dataset from Tomobank for processing
# data was taken in following patter...
# set energy
# take 10 reference flats
#... |
3866d79d0ec347b21149a2b553ac25f480d2c3916011fa7cf352ba0d8f67ec40 | Python | 2,499 | 83 | import numpy as np
import pyranges
from kipoiseq.dataclasses import Interval, Variant
from mmsplice.utils import pyrange_remove_chr_from_chrom_annotation, \
left_normalized, get_var_side, encodeDNA
def test_pyrange_remove_chr_to_chrom_annotation():
pr_exons = pyranges.data.exons()
pyrange_remove_chr_from_... |
14c68632c659429a7dabd2145213764effbb49daa6a4ec32313bc422e4539700 | Python | 2,500 | 57 | from re import A
import pymeshlab as pm
from sys import argv
import glob
import os
import vtk
def fix_ply(ply, xyz, plyout, deldist = 1.5, num_faces = 150000, simplify = True):
"""Fix plys that have been scaled badly and not properly masked or simplified
Arguments:
ply {str} -- Input ply filename
xyz... |
8cc1b96cff756cd7e48cb5ef7660579bdef80e2af18d4f43ee2dfe4057d3a322 | Python | 2,500 | 79 | import numpy as np
import h5py
import yaml
import sys
import os
import matplotlib.pyplot as plt
pathpath = 'PATHS/filepaths_carlen.yml'
myrun = 'runC00dM3_brain'
with open(pathpath, 'r') as myfile: pathdict = yaml.safe_load(myfile)
tessellation_dir = pathdict['tessellation_dir']
rundict_path = pathdict['configs... |
d63b1d50140d20dafb40e8ce3cb01ec6077d4fc5a623bb72b4d89a54b86bd733 | Python | 2,500 | 101 | import random
from collections import Counter
from typing import List, Tuple, Sequence, Hashable
from typing import List, Tuple, Dict, Hashable, Sequence
from typing import List, Tuple, Dict, Hashable
def build_group_ids_from_groups(
dataset,
groups: List[List[Tuple[Hashable, Hashable]]],
treat_unassigned... |
0b186e21f2e36fbeea909b64a6311397057b29ebe8020dd25919935289c624fd | Python | 2,501 | 77 | #!/usr/bin/env python
"""
Handles coordinate manipulations, mostly converting back
and forth between pixels and microns.
Hazen 02/13
"""
class Point(object):
"""
There is a lot of conversion back and forth between real positions
(in microns) and display positions (in pixels). This class is
designed to... |
6527ad2d737e8d79b36364c35f229b93128e35d5d03f2f4498984b801fcbd379 | Python | 2,501 | 77 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Reshape / reslice / resample *.nii or *.nii.gz using a reference.
This script can be used to align freesurfer/civet output, as .mgz,
to the original input image.
>>> scil_volume_reslice_to_reference wmparc.mgz t1.nii.gz wmparc_t1.nii.gz\\
--interpolation nearest
... |
2c1a91abc2adc96260fa5237ce3f41d36d618695d6a73db4ca9de35468d42651 | Python | 2,502 | 59 | """Reject direct-URL dependencies before uploading ChemGraph distributions."""
import argparse
from email.parser import BytesParser
from pathlib import Path
import tarfile
import zipfile
from packaging.requirements import Requirement
GRASPA_ASSETS = (
"simulation.input", "H2O.def", "force_field.def",
"force_... |
5db00420a001b74a99b4c5174217878fb7cade7afcc49de0e7e2ee4d7ba2f6da | Python | 2,502 | 80 | from __future__ import annotations
from typing import TYPE_CHECKING, Generic, TypeVar, overload
if TYPE_CHECKING:
from collections.abc import Iterator, MutableSequence
from typing import Protocol
class Named(Protocol):
name: str
T = TypeVar("T", bound="Named")
class NamedList(Generic[T]):
... |
d473792261de6f30fdb0ef1624d413cc52021fd8a68c262443380852705fbe5a | Python | 2,503 | 93 | # -*- coding: utf-8 -*-
# external inputs
import numpy as np
from scipy.interpolate import griddata
def regrid_2d(data_array, nx, ny):
"""Regrid 2D.
This function loads a two-dimensional numpy array and interpolates it to a
new grid array with defined sizes using nearest neighbour interpolation.
... |
4803d8bc8df79d640b6e551cc4dedc062250eb629614e53d9e9b5c457ccc3392 | Python | 2,504 | 67 | #!/usr/bin/env python
"""
Purpose
----
Estimate the respiration waveform from the phase difference of a complex EPI time series.
Authors
----
Mike Tyszka, Caltech Brain Imaging Center
License
----
MIT License
Copyright (c) 2024 Mike Tyszka
Permission is hereby granted, free of charge, to any person obtaining a copy... |
9697b858400faa8f10600d6f581cc247e605930c5efa656f573c6870f2f5d258 | Python | 2,504 | 103 | #!/usr/bin/env python
#
# battery_test.py
#
# Copyright F. Nedelec, March 19 2011 --- 22.05.2018
"""
battery_test.py:
run a battery of .cym files to check cytosim
Example - live:
battery_test.py bin/play live cym/*.cym
Example - runs:
battery_test.py bin/sim cym/*.cym
make_image.py 'play frame=100... |
c1232e05fc57b7b27b4492a95d935b3ce961ca7f0a381fe75a4a271142455d80 | Python | 2,504 | 88 | import torch
from torch._C._nn import pad
from eir.setup.input_setup_modules.setup_sequence import (
ComputedSequenceInputInfo,
SpecialTokens,
get_special_tokens,
)
def prepare_sequence_input_for_sequence_output(
input_object: ComputedSequenceInputInfo,
cur_seq: torch.Tensor,
input_name: str,... |
d0ccaf6f9bcecf744fd54376fe7e486edcb8abd76447160a106d63ff150a884b | Python | 2,504 | 89 | from pathlib import Path
from shutil import move
import os
import sys
import time
from tqdm import tqdm
import requests
import numpy as np
HF_DATASET_REPO = "neheller/KiTS-Challenge-Imaging"
HF_DATASET_REVISION = "main"
HF_DATASET_BASE_URL = (
"https://huggingface.co/datasets/{}/resolve/{}"
.format(HF_DATASET... |
bfeb01a49b75799d8ef184ad99733a59a8d82055cfd6099ebef3c6c8158b3151 | Python | 2,505 | 79 | import numpy as np
import pdb
import re
# from argparse import ArgumentParser
# argparser = ArgumentParser('train sentence generator')
# argparser.add_argument('--src', default='data/SemEval15/ptb_3.3.0/test.gold.conllu')
# argparser.add_argument('--tgt', default='results/test.conllu')
# argparser.add_argument('--end'... |
cf10713caf3eb8121d9e38ca92d3823b2a8985fb0979335770adfcba2fa7502c | Python | 2,506 | 89 | #!/usr/bin/env python2
import sys
import os
import signal
from optparse import OptionParser
USAGE = """
extract-from-bam.py --in <BAM file>
--rg <read group ID extract, leave blank if all >
--reference <reference fasta file, needed for CRAM support>
"""
par... |
1e9828bd40cd4bb07f9a63b0813fc978c79a5f90fffb35ed2ff696c815979de2 | Python | 2,508 | 67 | import random
import matplotlib.pyplot as plt
def show(data: list, slices=[-1], titles=[], figsize=(5,5), cmap='inferno', show_titles=True, show_ids=True, transpose=False):
"""
Display selected slices from multiple 3D image volumes using matplotlib.
This function visualizes specific z-slices from a list o... |
37ec3cabba98a06f8b64704a0dc22eb2da19b8d1cf21354ad2bafbf47b9f95d4 | Python | 2,508 | 75 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Apply bias field correction to DWI. This script doesn't compute the bias
field itself. It ONLY applies an existing bias field. Please use the ANTs
N4BiasFieldCorrection executable to compute the bias field.
"""
import argparse
import logging
import nibabel as nib
im... |
384dcc89d656f986833bc4c3bec7cc73ba024033de37bed1552f49d6774b1802 | Python | 2,508 | 94 | import torch
import torchvision
from torch.utils.data import Dataset
from dataset import CarvanaDataset
from torch.utils.data import DataLoader
def save_checkpoint(state, filename="my_checkpoint.pth.tar"):
print("=> Saving checkpoint")
torch.save(state, filename)
def load_checkpoint(checkpoint, mode... |
7cc4f0e9a440f06cff5025e9aa345d6fb0206aca73df6fe7b375678475ca57cb | Python | 2,508 | 87 | """load_transform
"""
import nibabel as nib
import numpy as np
__all__ = ["load_transform","load_sourcedata"]
def load_transform(casenum, tfile):
"""load the transform file
Args:
casenum ([type]): [description]
tfile ([type]): [description]
Returns:
[type]: [description]
""... |
0b4caca4ab9e554b9640ce638794a7808c1821ab0670500e12353d34bf7d6217 | Python | 2,510 | 71 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import glob
import os
import tempfile
from scilpy import SCILPY_HOME
from scilpy.io.fetcher import fetch_data, get_testing_files_dict
# If they already exist, this only takes 5 seconds (check md5sum)
fetch_data(get_testing_files_dict(), keys=['connectivity.zip'])
tmp_dir... |
843b6541b72746f35954890158e93af8ec5bfc186d391ab22538d6f189cc4342 | Python | 2,511 | 45 | """LAION-fMRI data registry.
Five subjects × two stim-pool families = 10 assembly identifiers, plus one
stimulus set registered under both family names (since ``benchmark.py``
derives the stim-set identifier from the dataset prefix).
Loader factories + DUA-gated stimulus handling live in ``_helpers/`` to keep
this fi... |
e01decdcefa1796c0aa524937f0afc7e41d609a3e771542ea8e736aef929391c | Python | 2,511 | 68 | import torch
from pathlib import Path
from torchvision.models import resnet18
from brainscore_vision.model_helpers.activations.pytorch import PytorchWrapper
from brainscore_vision.model_helpers.brain_transformation import ModelCommitment
from brainscore_vision.model_helpers.activations.pytorch import load_preprocess_im... |
6b78ddd1a3bb7867ecd33ad97b4783aa7a640f391f3417e08260d11ddd439926 | Python | 2,512 | 76 | #############################################################################
# Copyright (C) 2020-2026 MEmilio
#
# Authors: Maximilian Betz
#
# Contact: Martin J. Kuehn <Martin.Kuehn@DLR.de>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Li... |
1097ef86d1873a2f31e417408f047fc5d9e621535fb4199333bbffd80aca5c89 | Python | 2,513 | 82 | #!/usr/bin/env python
import argparse
import logging
import sys
from collections import OrderedDict
from itertools import product
import numpy as np
from bx.align.epo import (
Chain,
EPOitem,
)
logging.basicConfig(level=logging.INFO)
log = logging.getLogger()
def outFile(s):
if (s in ("-", "stdout")) ... |
4084b883d0fc4829752b62b581d4972dbcd79d5b033a2c254348f647b641f170 | Python | 2,513 | 95 | from impedancefitter.utils import get_equivalent_circuit_model
import pytest
from lmfit import CompositeModel, Model
import numpy as np
def test_single():
model1 = 'R'
model = get_equivalent_circuit_model(model1)
assert isinstance(model, Model)
def test_single2():
model1 = 'Randles'
model = get_... |
62d224be016824d31143e9b786f3f85c600ab4a6619c23a212462a3c0594601a | Python | 2,513 | 62 | import numpy as np
import matplotlib.pyplot as plt
import nibabel as nib
from voxeldepths_from_surfaces import load_fs_surf_in_grid
def plot_surf_slice(surf, z_slice, color='k'):
"""
Plot a slice of a surface at z=z_slice
surf: a dictionary with keys 'vertices' and 'tris'
z_slice: the z value of the s... |
8a2ea85691b39c77571e62f156da8e8aced76c2effafaf5eeb51a06c6c06abff | Python | 2,513 | 89 | import pytest
import tensorflow as tf
from pyment.models.sfcn import (
BinarySFCN,
CategoricalSFCN,
MultiTaskSFCN,
RegressionSFCN,
)
INPUT_SHAPE = (32, 32, 32)
NUM_CLASSES = 4
@pytest.fixture(scope='module')
def binary_sfcn():
return BinarySFCN(input_shape=INPUT_SHAPE)
@pytest.fixture(scope='m... |
4635112b8f0444d3529e9b1385b159d597072d99a6ffd32bd5d5535cbf11d0c8 | Python | 2,517 | 70 | import sys
import yaml
import os
import numpy as np
pathpath,myrun = sys.argv[1:]
#pathpath = 'PATHS/filepaths_carlen.yml'
#myrun = 'runCrespZP_brain'
with open(pathpath, 'r') as myfile: pathdict = yaml.safe_load(myfile)
rundict_path = pathdict['configs']['rundicts']
srcdir = pathdict['src_dirs']['metrics']
savep... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.