sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
76ffb942c01a779e2aa5e4fd73ee95692a33eea29e4d36d5cf43ba427abe4c27 | Python | 3,179 | 127 | import argparse
import logging
import os
import re
import sys
from concurrent.futures import ThreadPoolExecutor
from typing import cast
import nibabel as nib
import numpy as np
from nibabel.spatialimages import SpatialImage
from tqdm import tqdm
from pyment.loaders.mgh import load_mgh
logging.basicConfig(
format... |
84f87e9290a8952c2e64f62144c17b81a6afc9e090006904ba9c20d95b38309c | Python | 3,180 | 93 | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 25 10:40:54 2026
By Guido Meijer
"""
import scipy
import numpy as np
from pathlib import Path
import matplotlib.pyplot as plt
import spikeinterface.full as si
from spikeinterface.sortingcomponents.motion import estimate_motion, interpolate_motion
# Settings
PROBE_PATH ... |
b679046b32356921d9eeb07424d4533bcfb358236093d15482c4147ef8e3f19f | Python | 3,181 | 98 | # %% ### import modules
from pathlib import Path
import pandas as pd
# %% read results table
results_dir = Path(__file__).resolve().parents[1] / "results"
# %% data
df = pd.read_excel(results_dir / "long_c_results_mci.xlsx")
# %% round intercept and coef to 3 decimal places. same for intercept_ste and coef_ste
df["o... |
c1357dbe0946530e1595fce1cbab23fa9e19bd76d3c717cf948ff7118fac759a | Python | 3,181 | 99 | #!/usr/bin/env python
# coding: utf-8
'''
Dependencies:
pip install SimpleITK nrrd requests matplotlib pandas cv2
chmod +x script.py
In this code we leverage the rotated resampled and aligned annotation volumes.
We have to guess the anontations in each voxel though as they were changed to an INT between 0 and 3000 f... |
349ca425c5dffcfc19ddfe5500ad0b3776c898166a471f35c0625b8fce0edb18 | Python | 3,182 | 80 | # /------------------------------------------------------------------------------+
# | 22-AUG-2022 |
# | Copyright (c) Bone Imaging Laboratory |
# | All rights reserved ... |
4f2cb4f0ccb3cfbdc96f93aef34615c64f0be3c16d18ee734be93be2a37cdb89 | Python | 3,183 | 81 | from numpy.linalg import inv
import matplotlib.pyplot as plt
import os
import OptimalBattery.design as ds
## Make and show design matrices for the two designs
design = [[[1, 2], [3,4]], # Blocked design
[[1, 2, 3, 4]] * 2] # Interspersed design
title = ['Blocked','Interspersed']
plt.figure(figsize=(10, 5)... |
98ecc8baffb9ca06a06066eed820dcfd2ad22dac69e8458ea05cc6ed1d4eb53b | Python | 3,184 | 68 | from functools import lru_cache
import torch
from torch.utils.data.sampler import SubsetRandomSampler, SequentialSampler
import numpy as np
import random
class DataSplit(object):
"""
Inspired from https://palikar.github.io/posts/pytorch_datasplit/
"""
def __init__(self, dataset, test_train_split=0.8,... |
a80540b4213033276b9701b6fb264ad11972f334607eda53eeaed679d1b1387a | Python | 3,184 | 100 | from pathlib import Path
import os
import re
import numpy as np
import tifffile
from deep_events.database.folder_benedict import get_dict, save_dict
import xmltodict
def extract_ome(file: str):
"Get all the first tif file in a folder and get OME metadata from it, transfer to yaml"
folder_dict = get_dict(os.p... |
d42310d509269ccc79ece0eca22fbb19c556631dcfd6587a3699f3fa11658f54 | Python | 3,184 | 109 | import os
import numpy as np
import faiss
import torch
def swig_ptr_from_FloatTensor(x):
assert x.is_contiguous()
assert x.dtype == torch.float32
return faiss.cast_integer_to_float_ptr(
x.storage().data_ptr() + x.storage_offset() * 4)
def swig_ptr_from_LongTensor(x):
assert x.is_contiguous()
... |
2cbfe1455424cb6aff80af9051109cb12bf9635912de7bb3d2ba0c641f4862ac | Python | 3,185 | 106 | from langgraph.graph import StateGraph, START, END
from langchain_openai import ChatOpenAI
from langgraph.checkpoint.memory import MemorySaver
from chemgraph.tools.ase_tools import (
run_ase,
save_atomsdata_to_file,
file_to_atomsdata,
)
from chemgraph.tools.cheminformatics_tools import (
molecule_name_t... |
459034a1a7edbe70df8286eeaacf72bc851e6d7b3eb9ba288860365eb0ad31cb | Python | 3,185 | 90 | #@File (style="directory", required=false, label="Reconstructions directory (Leave empty for demo):") inputdir
#@String (label="Strategy:", choices={"Skeletonization + Dilation + Gaussian smoothing", "Skeletonization + Gaussian smoothing"}) filters
#@Float (label="Sigma (Gaussian blur):", value=30) sigma
#@SNTService s... |
830e807af05a8fee4b75aaf2175f9536c3a6eb3b5314dcf6270c5a1af1123c33 | Python | 3,186 | 91 | import os
import numpy as np
parallel_starts = 16
available_gpus = ['4,7', '7,4']
# args dict
args_dict = {'device': 1, # gpu
'log_steps': 1,
'num_layers': 3,
'hidden_channels': 256,
'dropout': 0.0,
'batch_size': 64 * 1024,
'lr': 1.e-03,
'e... |
8335caaf9631df44acba9621d17ca1ed39240470a56ebd6c6b6ecb7dcc54c74e | Python | 3,186 | 81 | from copy import deepcopy
import torch
from batchgeneratorsv2.transforms.base.basic_transform import BasicTransform
class Convert3DTo2DTransform(BasicTransform):
def apply(self, data_dict, **params):
if 'image' in data_dict.keys():
data_dict['nchannels_img'] = deepcopy(data_dict['image']).sh... |
c1e2b06d152890fa23f6bb9fd4b1dafe7f9b8af17fe9db12d06750c12d5a3455 | Python | 3,186 | 76 | import sys
import h5py
import os
import json
from tqdm import tqdm
from mmsdk.mmdatasdk import log
from mmsdk.mmdatasdk.configurations.metadataconfigs import *
from mmsdk.mmdatasdk.computational_sequence.integrity_check import *
def read_CSD(resource,destination=None):
if (resource is None): raise log.error("No reso... |
29319042c8a10df037716b8525869f944926fd49083794d89dc76f2ccd7ec974 | Python | 3,187 | 82 | """Tests for mcmlnet.utils.haemoglobin_extinctions module."""
import os
import tempfile
import numpy as np
import pytest
from mcmlnet.utils.haemoglobin_extinctions import (
get_haemoglobin_extinction_coefficients,
)
class TestGetHaemoglobinExtinctionCoefficients:
def test_default_path_requires_data_dir_at_... |
2b9099034d624bcb1bf6dae358d631e6c702517f893340d20ea220cec05762bf | Python | 3,187 | 87 | #!/usr/bin/env python
"""
optimise_thresholds.py
──────────────────────────────────────────────────────────
基于交叉验证保存的 fold*_val_preds.npz 进行统一阈值优化:
1. 读取 results/cv/fold*_val_preds.npz,合并所有验证集的
y_true 及 y_prob。
2. 对每个标签执行 Beta Calibration,返回 [w1, w2, b] 系数。
3. 在 0.40–0.70(步长 0.01)的细网格上搜索
Matthews CorrCoef 最优阈值。
... |
478a38ef611741debaf6094fe00ec761b214eb91e8b6b0ea61b4412b0a2bdd34 | Python | 3,187 | 81 | import sys
from torch.utils.data import DataLoader
from geoseg.models.MixerUnet import reparameterize_model
from geoseg.losses import *
from geoseg.datasets.isic2018_dataset import ISIC_Dataset
from geoseg.models.Unet import UNet
from catalyst.contrib.nn import Lookahead
from catalyst import utils
from torchinfo import... |
8bcbb244cfb6922ccd003daeb986ece9b143c63c40351b2f061d7e8a3140f078 | Python | 3,187 | 74 | '''
embeddings::multiprocessing.py
Functions and classes utilised in multiprocessing.
'''
from .internal import *
from dataclasses import dataclass, field
from typing import Any, Union, Callable
from multiprocessing import Pool, get_context
@dataclass
class Processor:
'''
This is a prototype cl... |
9912a49a202eb5f8bc00d3c676e8e2bf26f1d540022b9788ed588069db7c3890 | Python | 3,187 | 116 | #!/usr/bin/env python
#
# reduce.py
#
# copyright F. Nedelec, 2010-2013
"""
reduce.py:
reduce the size of cytosim file 'objects.cmo' in selected directories
Usage:
reduce.py [min=INTEGER] [commit] DIRECTORIES
The word 'commit' must be given otherwise the directories will not be processed
Specifying '... |
ca82c3d8537e0aba124a154eb20a8fb66f581f7dd970e731ba9313b0a018c3a1 | Python | 3,187 | 119 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib.ticker
models = ['Random Forest', 'XG-Boost', 'Logistic Regression', 'MLP']
strictnesses = ['strict', 'lenient']
feat = "minimal_feat"
defacing_method_tag = ""
dfs = list()
for strictness in strictnesses:
... |
5b2f63d8090172ffe98e2d8a2aca8742e544e45b1530c3029f2050a15cf42761 | Python | 3,188 | 83 | import sys
import json
import os
import pandas as pd
import anndata
import time
import numpy as np
from scipy import stats
download_base = os.environ.get("SHMDIR", "/gpfs/bbp.cscs.ch/data/project/proj84/csaba/aibs_10x_mouse_wholebrain/")
write = "/gpfs/bbp.cscs.ch/data/project/proj84/csaba/aibs_10x_mouse_wholebrain/"... |
c94c070812a17177ca4d5e46f28a0279a5fd2be1391657e43d1647132cbe7f3c | Python | 3,188 | 90 | import functools
import importlib
from brainscore_vision.model_helpers.activations.pytorch import load_preprocess_images
from brainscore_vision.model_helpers.check_submission import check_models
import torch.hub
import ssl
from brainscore_core.supported_data_standards.brainio.s3 import load_weight_file
from torch.nn im... |
f441984e0d783478343aed89bb60de90cb341af722cb056d91c4e34e196243e5 | Python | 3,189 | 108 | #!/usr/bin/python
#
## @file
#
# Labjack U3 Interface.
# Everything happens on the FIO4 pin.
#
# Hazen 5/12
#
import u3
import time
## PWM
#
# This class encapsulates using a Labjack for PWM modulation on the FIO4 pin.
#
class PWM():
## __init__
#
# Try to connect to the Labjack & co... |
53090f5f43b5682a1f99e3aebea7d8f764abc680977bb055bd7c75f1681187f2 | Python | 3,191 | 87 | #this script with assistance from ChatGPT
# a spreadsheet is where the first row is a header and first column is participant id
# the goal is to predict the column "wab_aq" based on imaging data
# we treat "age_at_stroke" as a predictor
import pandas as pd
import numpy as np
import tensorflow as tf
from sklearn.model_... |
5079b8d8f547b03070013ac3af53da9b2525a52a30a0bb0d52a1cb5abadcb4d9 | Python | 3,192 | 70 | # -*- coding: utf-8 -*-
"""
Merge outliers from vaso
Regressors of no interest from spatial correlation analysis and motion
correction are derived from single contrasts separtely. Here, outlier lists are
merged together.
"""
# python standard library inputs
import os
import sys
# external inputs
import numpy as np
... |
ccd9018c4c80948a0777f0769f2d891b84f125cb309e87711b1325bbe37fa027 | Python | 3,192 | 86 | import itertools
import numpy as np
import seaborn as sns
from matplotlib.axes import Axes
from numpy import median
from argclz import AbstractParser
from neuralib.plot import plot_figure, ax_merge
from rscvp.util.cli import TreadmillOptions, Suite2pOptions, DataOutput
from rscvp.util.cli.cli_camera import CameraOpti... |
d22f59b0b194a6c2decdefa6a46a014e30f8bbc37406b54273a2ff1496fb4b45 | Python | 3,194 | 88 | # # a nipype interface to unzip files (.nii.gz -> .nii)
# import os
# import subprocess
# from nipype.interfaces.base import (
# CommandLine, CommandLineInputSpec, TraitedSpec,
# File, traits, Str
# )
# class UnzipInputSpec(CommandLineInputSpec):
# file = File(exists=True, desc="Input file to unzip", args... |
3a56556bce864ed1f4c5e00da180a337f0a79122a72330cdeec8d139ecc807d0 | Python | 3,196 | 105 | import os, sys, math, random, argparse, numpy as np
import bpy
print(os.getcwd())
import blender_util as bu
from lib_alban import *
# parse arguments
parser = argparse.ArgumentParser()
parser.add_argument('--nobjects', type=int, default=14, help='number of objects in the scene')
parser.add_argument('--filename', type... |
be74abc67f85fcd9b88df5d2617be52a131e60af99a09fb165fac676b1d208dd | Python | 3,196 | 66 | import torch
from torch._dynamo import OptimizedModule
from torch.nn.parallel import DistributedDataParallel as DDP
def load_pretrained_weights(network, fname, verbose=False):
"""
Transfers all weights between matching keys in state_dicts. matching is done by name and we only transfer if the
shape is also... |
1b7fb0ddb4b9bc29a0c515e94e8804360447f0cbbad379383578f617a5293140 | Python | 3,197 | 99 | # Copyright (C) 2018-2022 Intel Corporation
# Copyright (C) CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT
import logging
import sys
from contextlib import contextmanager
from pathlib import Path
from django.conf import settings
from cvat.apps.engine.utils import directory_tree
class _LoggerAdapter(logging.L... |
1d6809c043608ccc9574f69dcde101ac58e3af80fc8420292544a723f59b802c | Python | 3,197 | 88 | '''
Cropping anatomical images to decrease number of voxels (and therefore
processing demands)
'''
from nipype.interfaces.fsl import ExtractROI
import nibabel as nb
import numpy as np
# Set data path
DATADIR = '/Users/sebastiandresbach/data/s1Anfunco/Nifti'
# Set subjects to work on
subs = ['sub-07','sub-09','sub-... |
a6e9cc9630a9fe3a0cde9635c4720d11f5836df929b73fcdf1fb3722b68ecdb1 | Python | 3,198 | 91 | import os
import numpy as np
parallel_starts = 16
available_gpus = ['5,7', '7,5']
# args dict
args_dict = {'device': 6, # gpu
'log_steps': 1,
'num_layers': 3,
'hidden_channels': 256,
'dropout': 0.0,
'batch_size': 64 * 1024,
'lr': 1.e-03,
'e... |
d0172819ce8e33d03c96d929fe55e00bbc6336fd556462cef140da0c5e4f9943 | Python | 3,198 | 110 | # cec2017.transforms
# Author: Duncan Tilley
# Contains rotation, shift and shuffle data loaded from data.pkl.
# Note that these correspond to the many .txt files provided along with the
# original implementation and should be used for final benchmark results.
import numpy as np
import pickle
import os
with open(os.p... |
1a1a431142b6746c1438a029740dd3a7139d34f1b1c67132ac53cb9ec95b66de | Python | 3,199 | 115 | # ACSF descriptor functions
# Imports
import json
import glob
import numpy as np
import numpy.typing as npt
import ase
import ase.io
import dscribe.descriptors
from modules.build_data.fhi_aims.descriptors.default_settings import (
DEFAULT_ACSF_SETTINGS,
)
from modules.tools.strings import xyz2formula
from modu... |
71467e4d7f26c7632bd8214998ae13c1b21e9b432f845eb1f037a3d792f8effa | Python | 3,199 | 91 | import os
import numpy as np
available_gpus = ['4,6', '4,6']
parallel_starts = 8
# args dict
args_dict = {'device': 1, # gpu
'log_steps': 1,
'num_layers': 3,
'hidden_channels': 256,
'dropout': 0.0,
'batch_size': 64 * 1024,
'lr': 1.e-03,
'epo... |
dbc6aeb91a70b8ee28c2484c4baa04035e880604bd329f0a9da631777b47a0cd | Python | 3,199 | 95 | #!/usr/bin/env python3
"""
save_graphs.py
--------------
Convert R-exported CSVs into per-sample PyG graphs (.pt).
Inputs (in --in_dir):
- gene_order.csv : column ['gene']
- edge_list.csv : columns ['src','dst','weight']
- sample_labels.csv : columns ['sample_id','label']
- expression_matrix... |
81c7d421071abb2300cf5c856f10d6e32c5bbdffa43387a5e625979b88d60327 | Python | 3,200 | 77 | # Copyright (c) DP Technology.
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from collections.abc import Collection
from typing import List
from unicore.optim.lr_scheduler import UnicoreL... |
5b7bb0d80549a910bf4027f3416fd19954c74de60a64f0c642a04a087c983588 | Python | 3,201 | 115 | # Copyright (C) CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT
from datetime import datetime, timezone
from django.db import transaction
from django.http import HttpRequest
from rest_framework.renderers import JSONRenderer
from rest_framework.request import Request
from rest_framework.throttling import BaseThro... |
828124a0d7ffdb36b1bad6d5c2d76512c7bf38c45354c17b5e4e41bafa2d0162 | Python | 3,202 | 79 | """Average echoes for before registration.
NOTE: The average echo image is used to determine the registration
tranformations because it has better SNR in most cases than either of the
echos.
"""
import os
import numpy as np
import nibabel as nb
# =====================================================================... |
1fe10e863d4338709d0954557e13e00919d049e992278cdad03068e5cf7350e3 | Python | 3,203 | 79 | """
Tools for "threading" out specific species from alignments (removing other
species and fixing alignment text).
"""
from copy import deepcopy
def thread(mafs, species):
"""
Restrict an list of alignments to a given list of species by:
1) Removing components for any other species
2) Remove... |
6e7f2fbf3b6ada1a34888f50ceef9d954b6dab37cf27f1a76718f7512b1102ca | Python | 3,203 | 91 | import os
import numpy as np
parallel_starts = 16
available_gpus = ['7,1', '1,7']
# args dict
args_dict = {'log_steps': 1,
'num_layers': 3,
'hidden_channels': 32,
'batch_size': 32,
'lr': 1.e-03,
'epochs': 100,
'eval_steps': 10,
'runs': 1}
... |
704d50073f2f4bfa5c50b75dc23d6646bd101845ea54f1bf470f031dc3b95b57 | Python | 3,203 | 91 | """Path cleaning, against paths with known repeats."""
import numpy as np
from ccf_streamlines.processing import remove_duplicate_voxels_from_paths
def test_consecutive_duplicates_are_removed_and_the_row_is_refilled():
"""Duplicates collapse and the row is left-packed, padded back to width."""
paths = np.ar... |
a051277d65fa49f249b3f985ef6f62591f32cc548e8622281e9e4aa32c42d439 | Python | 3,203 | 101 | """
HMM: Plotting fMRI Networks
===========================
We normally plot networks from an HMM trained on fMRI directly from the dual-estimated means/covariances. This tutorial covers:
1. Load means/covariances
2. Spatial maps
3. Functional connectivity networks
Note, we assume a group ICA parcellation was used a... |
0741fa62fb86013193ef0c916e1b5f51228ffadad38a964452c6e1aadf2e42c3 | Python | 3,204 | 132 | #!/usr/bin/env python3
import os,sys
import re
import matplotlib.pyplot as plt
import argparse
import subprocess
import numpy as np
import collections
parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter,
description="plot likelihood profile for sequence ")
... |
2d6f61c4f24bea02769890b8e5dee0edc4547653867004ccd1cd3fc1d0706131 | Python | 3,204 | 91 | import sys
sys.path.append('..')
import warnings
warnings.filterwarnings("ignore")
import os, math, random
from tqdm import tqdm
import bz2
from argparse import ArgumentParser, Namespace
from multiprocessing import Process
import torch
import numpy as np
from common.utils import compress_edges, csr_to_coo
def extract_... |
a07a3894f6bdebfc1e326d76ed279b2e8884bf9772430d52d937d02685cc618a | Python | 3,204 | 112 | # -*- coding: utf-8 -*-
"""
Created on Sat Oct 15 17:56:08 2022
@author: tianj
"""
import numpy as np
import torch.nn as nn
# Residual block class definition
class ResBlock(nn.Module):
def __init__(self,in_ch,out_ch):
super(ResBlock,self).__init__()
self.conv1=nn.Conv2d(in_ch,out_ch,3,1... |
38ce40c0832492c7121d38d7cc9551cbeed33c1f35a02c129c7f3b050b562033 | Python | 3,207 | 74 | """Tests for the area-weighted per-region aggregator (pandas only)."""
import numpy as np
import pandas as pd
from surface_morphometrics import patch_statistics as ps
def _df():
return pd.DataFrame({
"patch_number": [1, 1, 2, 2, 0],
"curvedness_VV": [0.1, 0.3, 0.2, 0.0, 0.9],
"thickness":... |
2877b14acc0f5ce5f7723feacf98307fcd52c7dbff9348ee7d75511b0866bbd5 | Python | 3,208 | 74 | import torch
import torch.nn as nn
import torch.optim as opt
from torch.distributions.bernoulli import Bernoulli
class Striatum_lNN(nn.Module):
def __init__(self, input_s, IT_inpt_s, ln_rate, h_size, thalamic_input_lr=1e-3):
""" Implement a Striatal network as a linear neural network, lNN, trying to predi... |
75ad1ea0bd3af044a35678cd7bb183ccdcfb1f667cb5812ffb5838654c67e709 | Python | 3,208 | 93 | import os
import numpy as np
parallel_starts = 8
available_gpus = ['6,0', '0,8']
# args dict
args_dict = {'device': 6, # gpu
'log_steps': 1,
'num_layers': 3,
'hidden_channels': 256,
'dropout': 0.0,
'batch_size': 64 * 1024,
'lr': 1.e-03,
'ep... |
5329f0b0c66869e9fae41f674a9a136c38ef2714c2ca4fd23af3a19bafac5fc4 | Python | 3,209 | 93 | import os
import yaml
class Config():
def __init__(self, path):
with open(path, 'r') as f:
cfg = yaml.load(f, Loader=yaml.Loader)
self.CLASSES = cfg['CLASSES']
self.LABEL_COLUMN = cfg['LABEL_COLUMN']
self.SAMPLE_RATE = cfg['FREQUENCY']
self.TRAIN_DATA = cfg['TRA... |
11548d1d91fa0095b33ff1acfc4854bc1bf5155ff36f87f47418f7bbe0b3f4ae | Python | 3,211 | 92 | import os
import numpy as np
parallel_starts = 8
available_gpus = ['6,1', '6,1']
# args dict
args_dict = {'device': 1, # gpu
'log_steps': 1,
'num_layers': 3,
'hidden_channels': 256,
'dropout': 0.0,
'batch_size': 64 * 1024,
'lr': 1.e-03,
'ep... |
1a5aeca8d623fca129095aeea959a1c0fb873ff7f32e67808b9f137e0ca4f2f2 | Python | 3,211 | 94 | from builder.models.seizurenet import conv_bn_relu_pool
import numpy as np
import torch.nn.functional as F
import torch
import torch.nn as nn
from torch.autograd import Variable
class RESNET18_CONV1D_V1(nn.Module):
def __init__(self, args, device):
super(RESNET18_CONV1D_V1, self).__init__()
self.ar... |
a759abe784cbe27c7711ad1f072d09ba519827c1eae3ff6bb22362a19b085bee | Python | 3,211 | 104 | import warnings
from contextlib import nullcontext
from functools import partial
from typing import Any, Optional
import torch
from torch.utils.data import DataLoader
from torch_geometric.typing import WITH_IPEX
class DeviceHelper:
def __init__(self, device: Optional[torch.device] = None):
with_cuda = t... |
c8e0a9096e5ac5e331c23b5835240fe3521130fe1d12a78ffdceb93fb67bd7d6 | Python | 3,212 | 74 | """Deterministic random-number generation for the pipeline.
Several pipeline stages are stochastic: Step 3's probabilistic thresholding
(circular-shift surrogates), Step 4's modularity/consensus clustering, the
null-model randomizations behind the normalized participation coefficient and
small-worldness, NMF initializ... |
ad70ff7904ace8b2b042be474350c0cec3f891f359681221f42a63bee80feb23 | Python | 3,214 | 94 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Count the number of non-zero voxels in an image file.
If you give it an image with more than 3 dimensions, it will summarize the 4th
(or more) dimension to one voxel, and then find non-zero voxels over this.
This means that if there is at least one non-zero voxel in t... |
c681d34cc50898357324cd57e9960f7ea99ab5cd7ccc59404ddfc55f332f8798 | Python | 3,214 | 91 | import os
import numpy as np
parallel_starts = 8
available_gpus = ['4,7', '7,4']
# args dict
args_dict = {'log_steps': 1,
'num_layers': 3,
'hidden_channels': 32,
'batch_size': 32,
'lr': 1.e-03,
'epochs': 100,
'eval_steps': 10,
'runs': 1}
#... |
e8ff6ce436a7ada472a8babe3eebccc94f572c1abb90526cd7cd61d68a17053d | Python | 3,214 | 72 | import numpy as np
from brainscore_vision import load_dataset, load_stimulus_set
from brainscore_vision.benchmark_helpers import bound_score
from brainscore_vision.benchmark_helpers.screen import place_on_screen
from brainscore_vision.benchmarks import BenchmarkBase
from brainscore_vision.metrics import Score
from bra... |
ea90ad9a4d25008b3556879244c6fef7fc4d499dc7087fd4479ae15ba700d1c7 | Python | 3,214 | 89 | # Copyright (C) 2021-2022 Intel Corporation
# Copyright (C) CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT
import zipfile
from datumaro.components.annotation import AnnotationType, Label, LabelCategories
from datumaro.components.dataset import Dataset
from datumaro.components.transformer import ItemTransform
f... |
fb0d57174c493176d0caab9712f32a0fabe4f7583e9b8dc30649147ca65534d1 | Python | 3,214 | 94 | import os
import numpy as np
parallel_starts = 8
available_gpus = ['4,7', '7,4']
# args dict
args_dict = {'device': 1, # gpu
'log_steps': 1,
'num_layers': 3,
'hidden_channels': 256,
'dropout': 0.0,
'batch_size': 64 * 1024,
'lr': 1.e-03,
'e... |
1b3187b5e0c8dc7cb98b2936edc06a70d640aefc2371ff19b1234d878c2c7e2c | Python | 3,216 | 81 | """Using for merged ab-ig graph
"""
import sys
sys.path.append('..')
import torch
import torch.nn.functional as F
import torch.nn as nn
from torch_geometric.nn import global_mean_pool
from models.graph_models import GraphModel
from layers.pooling_pyg import SumPoolingPyg, WeightAndSumPyG, AttentiveFPPoolingPyG
def md... |
700fd5579cf91f7cbd06b7d6e4f8bf121c23289b957e3678ae8b01156698e395 | Python | 3,217 | 105 | import sys
from typing import Optional
import pytest
import torch
from packaging.version import Version
from pkg_resources import get_distribution
"""
Adapted from:
https://github.com/PyTorchLightning/pytorch-lightning/blob/master/tests/helpers/runif.py
"""
from tests.helpers.module_available import (
_DEEPS... |
89a18bdd9ba2c71efdf86fbdd3ea930e93eacb46078e3b95d409795930659e9c | Python | 3,217 | 114 | #!/usr/bin/env python
import matplotlib.pyplot as plt
import numpy as np
import argparse
import sys
numX = 12
numY = 12
numZ = 12
CPUs = 32
ROWS = 6
COLS = 2
def plotit(layer):
data = rank_[layer:layer+1].reshape(numY,numZ)
# heatmap = plt.imshow(data,interpolation='nearest')
heatmap = plt.pcolormesh(data, edge... |
38541e5a1223de07e16dd15c30eb6d92ce45fcde5e55d464cc597af957a604c2 | Python | 3,218 | 91 | import os
import numpy as np
parallel_starts = 16
available_gpus = ['7,1', '1,7']
# args dict
args_dict = {'log_steps': 1,
'num_layers': 3,
'hidden_channels': 32,
'batch_size': 32,
'lr': 1.e-03,
'epochs': 100,
'eval_steps': 10,
'runs': 1}
... |
cbe74b53f6b2d43edf28ae24e9a68fd575611360450edddfe4311be3dbee5185 | Python | 3,218 | 84 | import click
import panta_rhei as pr
import simple_mri as sm
import dolfin as df
import numpy as np
import scipy
import tqdm
from petsc4py import PETSc
from dolfin import inner, grad
from glymphopt.utils import with_suffix
def scipy_sparse_csr_to_dolfin(A: scipy.sparse.csr_matrix) -> df.Matrix:
petsc_mat = PETSc.... |
9499d0b9c71acc70276f679d8a4999492df408dab0c7971eadd0b1e146f84058 | Python | 3,219 | 89 | import torch
from utils.module_with_records import ModuleWithRecords
class BaseDistance(ModuleWithRecords):
def __init__(
self, normalize_embeddings=True, p=2, power=1, is_inverted=False, **kwargs
):
super().__init__(**kwargs)
self.normalize_embeddings = normalize_embeddings
s... |
329f5c0ee34585e25bf304bb9c47050c7605d681b50d012b8c6fa65057ff8123 | Python | 3,220 | 104 | import numpy as np
from sklearn.metrics import roc_auc_score as auc
from sklearn.ensemble import RandomForestClassifier
import json
import argparse
import pandas as pd
def get_accuracy(AL, y, verbose=1):
try:
AL = np.array(AL)
y = np.array(y)
AL = AL.reshape(-1)
y = y.reshape(-... |
d51e53e7f4378d4de34d3f968dbf2b302da61686081e5894f636aba1d18da4d2 | Python | 3,220 | 86 | import logging
from os import listdir
from os.path import splitext
from pathlib import Path
import numpy as np
import torch
from PIL import Image
from torch.utils.data import Dataset
class BasicDataset(Dataset):
def __init__(self, images_dir: str, masks_dir: str, scale: float = 1.0, mask_suffix: str = ''):
... |
ecd2a3c5266ad8da15cf1b4241c420eb1a411cd5fd477dda551dc010169fe492 | Python | 3,220 | 135 | # Copyright (C) 2022 Intel Corporation
# Copyright (C) CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT
from __future__ import annotations
import contextlib
from collections.abc import Generator, Iterable
from typing import TypeVar
T = TypeVar("T")
class ProgressReporter:
"""
Use as follows:
with ... |
165d505255db8e9f38d1dc041a7f1541904aa2f229aff725262ce00bbf2cdd70 | Python | 3,221 | 107 | '''GoogLeNet with PyTorch.'''
import torch
import torch.nn as nn
import torch.nn.functional as F
class Inception(nn.Module):
def __init__(self, in_planes, n1x1, n3x3red, n3x3, n5x5red, n5x5, pool_planes):
super(Inception, self).__init__()
# 1x1 conv branch
self.b1 = nn.Sequential(
... |
9215b09be468893ac55308c6f79bf9a7332e9ca3e8a8bf690000b44f5de278cf | Python | 3,222 | 96 | from __future__ import annotations
import collections
import numpy as np
import osam
from loguru import logger
from numpy.typing import NDArray
class OsamSession:
_model_name: str
_model: osam.types.Model | None
_embedding_cache: collections.deque[tuple[str, osam.types.ImageEmbedding]]
def __init__... |
c9bd6be35cab1503669f25b7af3cc600e53bfdf6dedd109153a701a88ac3a550 | Python | 3,222 | 94 | import os
import numpy as np
parallel_starts = 8
available_gpus = ['5,7', '7,5']
# args dict
args_dict = {'device': 6, # gpu
'log_steps': 1,
'num_layers': 3,
'hidden_channels': 256,
'dropout': 0.0,
'batch_size': 64 * 1024,
'lr': 1.e-03,
'e... |
d57025df8cf3b37d276bc10e1c65cacfffbafa4bb9ededeab2a8cea8df95596d | Python | 3,222 | 92 | import os
import numpy as np
parallel_starts = 8
available_gpus = available_gpus = ['6,0', '0,6']
# args dict
args_dict = {'device': 1, # gpu
'log_steps': 1,
'embedding_dim':128,
'walk_length':40,
'context_size':20,
'walks_per_node':10,
'batch_size':12... |
bfdb58fe3f498125a15b10ab769807ec67528042fab9e9f01d3fc955c721bdfe | Python | 3,225 | 85 | import os
from pathlib import Path
from typing import Union, List, Optional
from .utilities import run_cmd
def run_humann_pipeline(
input_file: Union[str, Path],
output_dir: Union[str, Path],
meta_profile: Union[str, Path],
threads: int = 8,
chocophlan_db: Optional[Union[str, Path]] = None,
un... |
0823cc9a7124e1d33552bbcea58eec7c6648f0a2d07a42484fbadf960fb8a83c | Python | 3,226 | 85 | import fnmatch
import re
from collections import OrderedDict
from typing import Union, Optional, List
import torch
class AttentionExtract(torch.nn.Module):
# defaults should cover a significant number of timm models with attention maps.
default_node_names = ['*attn.softmax']
default_module_names = ['*att... |
902a995b0d35cb9869d68a33398930f352d401f2524890dfe65d5aba2adc291d | Python | 3,226 | 85 | import os
from argparse import ArgumentParser
import numpy as np
import torch
from Functions import generate_grid_unit, save_img, save_flow, transform_unit_flow_to_flow, load_4D
from miccai2020_model_stage import Miccai2020_LDR_laplacian_unit_disp_add_lvl1, \
Miccai2020_LDR_laplacian_unit_disp_add_lvl2, Miccai202... |
b68730953461f65047183c11cb414a50a872c51e1f53a79996f6523a9e4ffdbe | Python | 3,226 | 119 | import matplotlib.pyplot as plt
from cycler import cycler
COLORS = {
"primary": "#0072B2", # Blue
"secondary": "#D55E00", # Orange
"tertiary": "#009E73", # Green
"accent": "#E69F00", # Yellow
"accent2": "#CC79A7", # Pink
"accent3": "#56B4E9", # Light blue
"accent4": "#F0E442", # Ligh... |
1874c0a14555c1a05226d70ee4a777f3ab114ba110eb1e61f413a93722112165 | Python | 3,227 | 109 | '''
H4O2
'''
import numpy as np
import sys
def intro():
print("""
SHORT List of potential energy surfaces for H4O2:
P: potential energy, G: Gradient, D: Nonadiabatic coupling vector
This is listed at the end of description to show the availability.
For example: P/G means both potential energy and... |
7d9121bb5fee4c1cec807434b9add87c9de6526f0cc98c2e02dd65aadc025fcc | Python | 3,227 | 97 | # Copyright (C) CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT
import textwrap
from typing import Any
from django.conf import settings
from rest_framework import serializers
from cvat.apps.engine.serializers import BasicUserSerializer
from . import models
class AccessTokenReadSerializer(serializers.ModelSer... |
98fedc6e6ba8f0f05f196c4fb5698f1114e4688563728aac7e4bed07c493febf | Python | 3,227 | 100 | import json
import logging
import os.path as op
from argparse import Namespace
import pytest
import AFQ.utils.bin as afb
from AFQ.definitions.image import ImageFile
def _make_args(arg_dict, **overrides):
"""Build a Namespace as argparse would, with all dynamic defaults."""
ns = {}
for section, args in a... |
b80adf052ffacca741872600f3d8e97980f9a909f5aa0820db92dc7b4080e31d | Python | 3,227 | 106 | import logging
import os.path as op
import numpy as np
from scipy.ndimage import gaussian_filter
from skimage.morphology import dilation
from skimage.segmentation import find_boundaries
from AFQ.data.fetch import afq_home, fetch_brainchop_models
from AFQ.nn.utils import prepare_t1_for_nn, resample_output
logger = lo... |
398fb58f3bfc8c9543b0563edf62ad2fbb6d50db39de69a7cb15aea52296630c | Python | 3,228 | 117 | # LMBTR descriptor functions
# Imports
import json
import glob
import numpy as np
import numpy.typing as npt
import ase
import ase.io
import dscribe.descriptors
from modules.build_data.fhi_aims.descriptors.default_settings import (
DEFAULT_LMBTR_SETTINGS,
)
from modules.tools.strings import xyz2formula
from mo... |
8d148b8dc104e3318dd858ba7fa8b9ead6bac6ae6e3c48036547624aabb8007a | Python | 3,228 | 88 | import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import torch
import pandas as pd
from model.Ouroboros import Ouroboros
from utils.chem import cal_SAScore
if __name__ == '__main__':
# check GPU
print('CUDA available:', torch.cuda.is_available()) # Should be True
print('C... |
bfcfcccdce057bf2730e25b739464c7d8c17befb68e381bc44e06a77ce1c7514 | Python | 3,228 | 92 | import os
import numpy as np
parallel_starts = 8
available_gpus = available_gpus = ['4,7', '7,4']
# args dict
args_dict = {'device': 1, # gpu
'log_steps': 1,
'embedding_dim':128,
'walk_length':40,
'context_size':20,
'walks_per_node':10,
'batch_size':12... |
7bed018a7213085d7c7b306833d31326947cbf50ce5e2603233a3040f55eaf63 | Python | 3,229 | 85 | # This file was automatically generated by SWIG (https://www.swig.org).
# Version 4.3.1
#
# Do not make changes to this file unless you know what you are doing - modify
# the SWIG interface file instead.
from sys import version_info as _swig_python_version_info
# Import the low-level C/C++ module
if __package__ or "."... |
01e8ec6daaf8202e191ae9fd64750e86ab7f96fd4d7eade55405d4f807cb2d95 | Python | 3,230 | 80 | import os
import nibabel as nib
import numpy as np
import scipy.io as sio
mag_4d_path = '/mnt/f/BIDS/demo_BIDS/derivatives/qsm_pipeline/sub-TAOHC0261/ses-baseline/sub-TAOHC0261_ses-baseline_part-mag_desc-smoothed_GRE.nii.gz'
r2star_path = '/mnt/f/BIDS/demo_BIDS/derivatives/qsm_pipeline/sub-TAOHC0261/ses-baseline/sepia... |
556b8187d22697b4012ca2fcfdffde08128a8fabf3cd8114f6d18fa8785556f3 | Python | 3,230 | 105 | from pathlib import Path
from typing import TYPE_CHECKING
import numpy as np
from tests.setup_tests.setup_modelling_test_data.setup_targets_test_data import (
get_current_test_label_values,
get_test_label_file_fieldnames,
set_up_label_file_writing,
set_up_label_line_dict,
)
from tests.setup_tests.setu... |
593959b628d39c89da9c875ec055e31d6cb22a1f2952bbd071c7a58b570fa29d | Python | 3,230 | 94 | """Tests for rule-based artifact detectors."""
import numpy as np
import pytest
from artifact_identification.detectors.rule_based import (
detect_eye_movement_tuh_adapted,
detect_muscle_artifacts_tuh_adapted,
detect_non_physiological_tuh_adapted,
run_rules,
)
def _make_random_eeg(n_windows=50, n_tim... |
93f9ffcf459a755d97c5cc6db12da89ee09852d3061cdee3f872f47475448853 | Python | 3,230 | 76 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
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=['processing.zip'])
tmp_dir = tempfile.T... |
4c084a83fa0e0afbe2e4bb63cb2d93b8504d65becfc6dcdd5dcc597a19b38ef0 | Python | 3,231 | 95 | import torch
import time
from UBSIM.loss_functions import cost_function_norm, cost_function
from UBSIM.blind_SIM_functions import reshape_psf
from torch.utils.data import Dataset, DataLoader
class CustomDataset(Dataset):
def __init__(self, torch_array):
assert torch_array is not None, "Input torch_array ... |
1e5cb7bdabdb7cceaffdb05f5864a526c683511a6526c64941f2148ac4eeef1c | Python | 3,232 | 105 | import os
import h5py
import glob
import warnings
import numpy as np
from tqdm import tqdm
from nicety.conf import get_conf
from scipy.interpolate import interpn
import imageio
from fiberpipeline.utils import preprocess_vol
def extract_signals(vol, skels, anisotropy, method: str, dtype):
assert vol.ndim == 3, "... |
302f25ee5aae86dcb03c7e609778a5fdfe66c2e687126d473c632fd4b687076e | Python | 3,232 | 82 | from pathlib import Path
import matplotlib.pyplot as plt
from argclz import AbstractParser, as_argument, argument
from neuralib.imglib.color import grey2rgb
from neuralib.imglib.transform import affine_transform
from neuralib.suite2p import Suite2PResult, get_soma_pixel
from neuralib.util.verbose import publish_annot... |
5d4000bf80e62007951513ad3651d02b7df5b36f7c4974ac0c0b8c05ec0ad806 | Python | 3,232 | 117 | # SOAP descriptor functions
# Imports
import json
import glob
import numpy as np
import numpy.typing as npt
import ase
import ase.io
import dscribe.descriptors
from modules.build_data.fhi_aims.descriptors.default_settings import (
DEFAULT_SOAP_SETTINGS,
)
from modules.tools.strings import xyz2formula
from modu... |
65d4a9db48f6187e370b3d985535a4c448e065b33f2b6b280b949613ec5b5d74 | Python | 3,232 | 100 | import numpy as np
from scipy import fftpack, signal
import matplotlib.pyplot as plt
import fft_utils as u
############################
# parameters
############################
#20 s of signal
tend=20
#sampling interval
ts=0.01
#sampling frequency (measurements per second)
f0 = 1 #starting frequency, Esprit... |
e83b1397ad6d461ac89b2ede761b11e7e1aed6d6c78e51355fd5060e570e918d | Python | 3,232 | 77 | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from pathlib import Path
from typing import Any
from ultralytics.solutions.solutions import BaseSolution, SolutionResults
from ultralytics.utils.plotting import save_one_box
class ObjectCropper(BaseSolution):
"""A class to manage the cropping o... |
b8841dcd2353835947149f010423899a0fc522521268743a5a3e54f76b4a6254 | Python | 3,233 | 63 | import os
import glob
from nipype.interfaces.base import CommandLineInputSpec, TraitedSpec, CommandLine, File, Directory, traits
from cvdproc.config.paths import get_package_path
recon_all_longitudinal_script = get_package_path(
"pipelines", "bash", "freesurfer", "freesurfer_reconall_longitudinal_single.sh"
)
cl... |
3985bf931ccb380155cceab09e0663d247842fecc4422d2b7b68b559ace533aa | Python | 3,234 | 113 | # Cut Coulomb matrix descriptor functions
# Imports
import json
import glob
import numpy as np
import numpy.typing as npt
import ase
import ase.io
import dscribe.descriptors
from modules.build_data.fhi_aims.descriptors.default_settings import (
DEFAULT_CUTCM_SETTINGS,
)
from modules.tools.strings import xyz2for... |
fb0d8606a060f3c567be760fd07f9ff803c0b6f724acea1115df28c5b1530088 | Python | 3,234 | 100 | from pathlib import Path
from typing import Literal, ClassVar, Final
import polars as pl
from typing_extensions import Self
from neuralib.tools.gspread import GoogleWorkSheet, GoogleSpreadSheet
from neuralib.typing import DataFrame
from neuralib.util.verbose import fprint
from rscvp.util.io import IOConfig
__all__ =... |
ff3e69179858e1892704e89fdccdef67c07f306cd4e2f04c9eae725b44e5071f | Python | 3,234 | 63 | # cli.py
import argparse
from .chemembed_single_file import run
from .reference_utils import DEFAULT_PRECURSOR_TOLERANCE_PPM
def main():
"""
A cli targeted invocation, where all the configuration settings come from command line arguments.
"""
parser = argparse.ArgumentParser(description='Process ... |
1f6cd7fe8d52af13c485d730a16add391b5f7af202e86d2f3f77bc62e375e2d3 | Python | 3,237 | 92 | """Download and prepare the Therapeutics Data Commons (TDC) ADMET Benchmark Group datasets."""
from pathlib import Path
import pandas as pd
from tdc import utils
from tdc.benchmark_group import admet_group
from tqdm import tqdm
from tdc_constants import (
ADMET_GROUP_SEEDS,
ADMET_GROUP_TARGET_COLUMN,
DAT... |
8225cbe7ccc50e33a49408a9dbb3d8691d08437dbfee75c8332ffa659aa83352 | Python | 3,237 | 86 | """Convert protein embeddings to gene embeddings by averaging the protein embeddings for each gene."""
import json
from pathlib import Path
from typing_extensions import Literal
import torch
from tap import Tap
from tqdm import tqdm
class Args(Tap):
embedding_dir: Path # Path to directory containing .pt files w... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.