sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
542f1948bf365772a4396cb0e928504f72a36c4e2f407c00eee46cc05aef2144
Python
2,414
86
from tqdm.notebook import tqdm import copy import cv2 import json import numpy as np import pickle import torch import torch.nn as nn from Function import std_2 import Imf_Extraction ImfExtrat from Trace_Detection import N_top_func from Trace_Detection import N_top_indices from Trace_Value_Extraction import train_top_v...
b689c8def3350cc04c43ead5e1ae3948f8ee9b14d17b529ed726bb808906219c
Python
2,414
66
import numpy as np from scipy import stats import matplotlib.pyplot as plt from scipy.stats import levy_stable from matplotlib.collections import LineCollection from mpl_toolkits.mplot3d import Axes3D import TwoD_fun import levy import brainpy as bp import brainpy.math as bm fit_color = ['#009FB9', '#F18D00'] legend =...
1a0bf6c7d3fb0f6995aa90d349322a668bf67d981836b81ee10b8e9490df82d5
Python
2,415
67
#!/usr/bin/env python import numpy as np import pandas as pd import click as ck import logging from toolkit.utils import Ontology from toolkit.metrics import compute_metrics logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.INFO) @ck.command() @ck.option( '--data-root', '-dr', default='data',...
201d278244dda6455f2a3093da335ab5d3faf6c69c7595766cb63af3e4f7ae71
Python
2,415
81
import nilearn import nilearn.regions import nilearn.reporting import itertools import plotly from scipy import ndimage import fire import sys sys.path.insert(0,'..') import pickle from nilearn import plotting from nilearn import surface from nilearn.glm.thresholding import threshold_stats_img import numpy as np ...
7125e6d99e6d8af9c2adf5991f46ea76665aaf1b8cbefcd14265796cb179ea99
Python
2,415
64
import user_features as uf import csv import time import pandas as pd import json def get_user_vector(user): user_vector = { "user_id": uf.get_user_id(user), "profile_description": uf.has_description(user), "profile_location": uf.has_location(user), "profile_url": uf.has_url(user),...
bcd685ba1ae6a1a770b128d7c0b6ed216f0e420aaf9c8f6e9f022069dfecf740
Python
2,415
92
# -*- coding: utf-8 -*- import numpy as np from scilpy.utils.spatial import get_axis_index def affine_from_offset(orientation, offset): """ Create an affine matrix from a scalar offset in given orientation, in RPS coordinates for imaging. Parameters ---------- orientation : str Name...
fb97668fc55a9849c4da087aec34c7cf26707d5ca8eb996811c3e4c438c6926a
Python
2,415
86
"""# Basic widgets demo Widget demonstration with magicgui. This code demonstrates a few of the widget types that magicgui can create based on the parameter types in your function. """ import datetime from enum import Enum from pathlib import Path from magicgui import magicgui class Medium(Enum): """Enum for ...
ffd0580a21d143f34680d12b161a35a49733c473dc342943d76e7b70d09360b1
Python
2,415
74
""" UnetFormer for uavid datasets with supervision training Libo Wang, 2022.02.22 """ from torch.utils.data import DataLoader from geoseg.losses import * from geoseg.datasets.uavid_dataset import * from geoseg.models.UNetFormer import UNetFormer from catalyst.contrib.nn import Lookahead from catalyst import utils # tr...
ae9a1e3a0a5e0832a37195dcacb36ae2f4e4ec196c7dc11d9c0c9a12ac9784dd
Python
2,416
62
"""Test the functions in the yasa/plotting.py file.""" import unittest import matplotlib.pyplot as plt import pandas as pd from yasa.hypno import simulate_hypnogram from yasa.plotting import topoplot class TestPlotting(unittest.TestCase): def test_topoplot(self): """Test topoplot""" data = pd.S...
62599140bca3e91b01b980e89be4e3fe209baa8a8a853e845c53537b01856e28
Python
2,417
75
import argparse from tqdm import tqdm import torch import torch.nn.functional as F from torch_sparse import SparseTensor from torch_geometric.utils import to_undirected, dropout_adj from ogb.nodeproppred import PygNodePropPredDataset def main(): parser = argparse.ArgumentParser(description='OGBN-papers100M (MLP...
7c40e1b8517f191610558916bf5ac34f09ae3660fac075a50aaba0350fdaf509
Python
2,417
71
""" GeneratePCALabeledVideo @2022Knowblesse After PCA dimensionality reduction on the wholesessionunitdata, draw clustered label on the video. """ import cv2 as cv from tqdm import tqdm import numpy as np from scipy.interpolate import interp1d from Switching.SwitchingHelper import parseAllData, getZoneLDA from pathlib...
96aa83f7bb29e308aba57855264864d45308c41dbc49ee68481ebab1c22cf311
Python
2,417
66
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...
96cfc8d0a88fa600765e6f9c2b7d971c29979d7db060d694b798606bfb7dbba1
Python
2,417
48
from brainscore_vision import data_registry, stimulus_set_registry, load_stimulus_set from brainscore_core.supported_data_standards.brainio.s3 import load_stimulus_set_from_s3, load_assembly_from_s3 from brainscore_core.supported_data_standards.brainio.assemblies import NeuroidAssembly BIBTEX = """@article{gifford_lar...
a013f3e8e8a1189de205af0901fb85514d605030db075317fbf7cc056415ba17
Python
2,417
70
import os import pickle import numpy as np import time # from glob import glob from pycurv import TriangleGraph, io from graph_tool import load_graph from intradistance_verticality import export_csv from morphometrics_stats import Experiment, Tomogram, weighted_median, weighted_histogram_peak, statistics, histogram,...
d99641b78c2dc32cfd3cef7b263fc73d7ecfcc7f887c83bdcfd53fa3edcbb7a8
Python
2,417
74
import torch import torch.nn as nn import torchvision.transforms.functional as TF class DoubleConv(nn.Module): def __init__(self, in_channels, out_channels): super(DoubleConv, self).__init__() self.conv = nn.Sequential( nn.Conv2d(in_channels, out_channels, 3, 1, 1, bias=False), ...
ddb609348e04a491c4afc93346a66a8b7fecb57d4601d44ee190f392dcb6cb5a
Python
2,417
69
from argclz import AbstractParser, as_argument, try_int_type from rscvp.statistic._var import VIS_HEADERS from rscvp.statistic.csv_agg.core import ParquetSheetSync, NeuronDataAggregator from rscvp.util.cli.cli_io import HEADER from rscvp.util.cli.cli_statistic import StatisticOptions __all__ = ['VisAggOptions'] clas...
e990882e7d4883936214393d9a829defb34249a3ac893d874ab24d53ffc6907c
Python
2,417
77
# -*- coding: utf-8 -*- """Test mvpa model.""" import numpy as np import pytest from fmri_decoder.model import MVPA @pytest.fixture def mvpa_model() -> MVPA: """Dummy model using the iris data set.""" return MVPA.from_iris() def test_shape(mvpa_model: MVPA): """Check input data shape.""" assert mv...
a3cdd2263835f90bc6785b2f3e0a8c97d88c5ecfbf63a565cf1be3a9208eff6b
Python
2,418
70
from brainvoice.configuration.configuration_instantiator import construct_from_kwargs from brainvoice.modules.weight_init import apply_weight_init import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable class VanillaAutoencoder(nn.Module): def __init__(self, encoder, ...
c6382f4d4b3ce18d234098a9f3688562e2a2f20c7d311b0e4535fb23189d7384
Python
2,418
78
from pathlib import Path from snakemake.logging import logger class Genome: def __init__(self, annotation, assembly, reference): self.annotation = annotation self.assembly = assembly # Allow for old drop config stylings, where the file was a string under MAE # -> force into dicti...
d7a8b683d43fce786958ff72dc0ec3a075442757ef1e44d34fc4b28787cfdf42
Python
2,418
63
# Copyright (c) OpenMMLab. All rights reserved. import os.path as osp from mmcv.utils import TORCH_VERSION, digit_version from mmcv.runner.dist_utils import master_only from mmcv.runner.hooks import HOOKS from mmcv.runner.hooks.logger.base import LoggerHook @HOOKS.register_module() class TensorboardImageLoggerHook(L...
30c079c9044930ea1f20402b83f4bfa4f829f8a360c7be0dd9fcf5aeb5079101
Python
2,419
81
#!/usr/bin/env python3 import os import sys import time import getopt import numpy as np import pandas as pd def apply_cells_usage(): print(""" Usage : GEM_toolkit.py apply_cells \\ -g <gem file> \\ -m <cell segment mask file> \\ -o <output prefix> \\ -x [xshift...
cb22f34b373bd1fadd90a35b28af2ec64f5f74e06a472e3c67e4456f842b377a
Python
2,419
71
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Script to obtain labels from a binary mask which contains multiple blobs. The script will assign a label to each blob in the mask. The background label is excluded from the labels list. By default, the background label is 0 and the labels are assigned in increasing or...
300a3cb2b18ba02a43f0835f552a8fa82905ce43621018d24cb0e77c3585cf86
Python
2,420
80
# -*- coding: utf-8 -*- # external inputs import numpy as np # local inputs from ..utils import get_fft def get_pca(arr, fft_threshold=0.25): """Get PCA. This function computes the principal axes from the thresholded fourier spectrum of an input array. They are found by estimating the eigenvector...
a550e939b7a82802bb67dea460bfb85b13708c6383f2ce6449edc36a765233cb
Python
2,421
61
import h5py import numpy as np from pathlib import Path from typing import Union def save_dict_to_hdf5(group: h5py.Group, data: Union[dict, list, int, float, str, np.ndarray]): """ Recursively saves data to an HDF5 file group. This method iterates through a dictionary and saves its contents to the provid...
c7fc734a3200ed335fa36fde05c9d798a1bc89d6ccb51022585decaab9f7fe88
Python
2,421
80
from __future__ import annotations from typing import Any, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple, Union import numpy as np from fairlearn.metrics import equalized_odds_difference as fl_equalized_odds_difference ArrayLike = Sequence[Any] def _validate_lengths(*arrays: Sequence[Any]) -> None: len...
2ccb5e02408bf41114af38f8e1dc73019ea7128b0d6a43c1a3ecbb683e2ae63c
Python
2,422
87
from test.unit.util import is_equal_tf import numpy as np import pytest import tensorflow as tf from deepreg.loss.kernel import ( cauchy_kernel1d, gaussian_kernel1d_sigma, gaussian_kernel1d_size, rectangular_kernel1d, triangular_kernel1d, ) @pytest.mark.parametrize("sigma", [1, 3, 2.2]) def test...
7d11f1dc821afce94ae269c0f396609d3711e9eec37ba3b26a2fbafd86e2ce4d
Python
2,422
90
import argparse import h5py import os import matplotlib.pyplot as plt import numpy as np # from skimage.metrics import structural_similarity as ssim # from skimage.metrics import normalized_root_mse as nrmse DIR = os.path.dirname(os.path.realpath(__file__)) # %% parser = argparse.ArgumentParser(description='plot br...
99b9fe55e544b9b7567915b86f47181d8b192bd6262e3408199767ccec066846
Python
2,422
69
from pathlib import Path from typing import Optional import pandas as pd from brainways.project.info_classes import SliceInfo from brainways.utils.cell_detection_importer.cell_detection_importer import ( CellDetectionImporter, ) class KerenCellDetectionsImporter(CellDetectionImporter): parameters = { ...
1d78fffeda0caafce182feb77cadee2d985e3489b2790a07851c8aa84f2a3eea
Python
2,423
75
import sys import getopt import json import scipy.ndimage as nd from skimage import io as skio import numpy as np # usage def affine_txt_usage(): print(""" Usage : affine_txt.py -i <input.txt> -o <output> -r <ref image> -f [f...
3329f56fd1c70a06dba7d1d0f968b34fd59e0d18ed2574479f3df3aab2a55c1e
Python
2,423
60
import numpy as np import pandas as pd import pytest from src.audit.schmidt_design import annotate_core, pool_counts, design_matrix def example_metadata(): return pd.DataFrame({ 'ODCF_name':['c1','c2','d1','d3'], 'Cell_line':['lineA']*4, 'Batch':[1]*4, 'Condition_simple':['Ctrl','Ctrl','Trt5','Tr...
718c766e7c0796d0c49b6cc3bb0aa222c762f9846bcb1aebe48c0a366322a861
Python
2,423
81
import scipy import torch.utils.data import numpy as np import random def CreateDatasetSynthesis(phase, input_path): # Load data for contrast1 target_file = input_path + phase + "/LF_T2.npy" data_fs_s1 = LoadDataSet(target_file) # Load data for contrast2 target_file = input_path + phase + "/HF...
e74a0223907322f57589ebbf5974aeaa7057d0725757c2dbcb8589123443afc8
Python
2,424
87
method_bounds = { "None": {}, "Average": {}, "2D Convexhull": { "degree": [0.5, 2], # degree of polynomial fit }, "Circularly-symmetric": { "smooth": [1, 50], # any positive number (larger numbers means more smoothing) "tension": [1, 5], "radial_bin": [2, 200], # i...
53542fd57e0a89d4f428fc1f0c47a9939713cb47a4e485c67ba10be061daed83
Python
2,425
96
import numpy as np from PIL import Image def dummy_loader(model_path): ''' Load a stored keras model and return its weights. Input ---------- The file path of the stored keras model. Output ---------- Weights of the model. ''' backbone = keras.models....
77841a8df60695d555299444896b45f6ac08773ae04bb77a6a217288450e1065
Python
2,425
67
"""Add AAL v4 ROI names to the 32k left/right GIFTI label tables.""" from __future__ import annotations import argparse import csv from pathlib import Path import nibabel as nib def cortical_names(roi_txt: Path, side: str) -> list[str]: suffix = f"_{side}" names = [] for line in roi_txt.read_text(encod...
a721567592c687ed7e00efacb03211e56fbf502b8239fb1924b6e816e93a2735
Python
2,426
51
#!/usr/bin/env python3 # Author: Francois Aguet import argparse import os import struct import subprocess from datetime import datetime import contextlib @contextlib.contextmanager def cd(cd_path): saved_path = os.getcwd() os.chdir(cd_path) yield os.chdir(saved_path) parser = argparse.ArgumentParser(...
7543c22a721ac2e97a782ce8ea4668ea12d21a1164b0855c93ab6ae21901937f
Python
2,427
84
import random def simulate_health_sample(sequence_length: int) -> tuple[str, str]: age = random.randint(18, 80) fitness_score = round(random.uniform(1.0, 10.0), 1) cortisol_morning = random.randint(10, 25) cortisol_evening = random.randint(3, 12) sleep_quality = random.randint(1, 10) start_h...
9bfff31984464d50bbf7a8a16bf95ba7846aa39e235bb4752a909a72648e90ce
Python
2,427
90
import torch import torch.nn as nn import torch.nn.functional as F class InterpolateProjection(nn.Module): def __init__( self, in_channels: int, out_channels: int, output_size: tuple[int, int], mode: str = "bilinear", align_corners: bool | None = None, ): ...
ab8e828a1955ae874a60555a7ab0d8ec959862dd4785ed380de3dd3de6c08cea
Python
2,427
64
from chimerax.core.commands import run from chimerax.atomic import selected_atoms from collections import Counter import os import glob # === Configuration === # Retrieve all CIF files generated by ModelAngelo structure_files = sorted(glob.glob("/home/sunch/Desktop/Cb-project-maps/S2C2-dataset/one-Fab-4-classes/*map/*...
c54d9ec37a21dc6452e7bb715e0ee26cf42e2cf8112e138661f8ae1df54b5844
Python
2,427
77
# This file is part of connectome-manipulator. # # SPDX-License-Identifier: Apache-2.0 # Copyright (c) 2024 Blue Brain Project/EPFL import re import json import pytest from pathlib import Path from cached_property import cached_property from connectome_manipulator import utils as test_module from bluepysnap.circuit im...
1d5f5a3c20758714d88c2801c265f3b5d836c451d4d64377f4d1b93537571c73
Python
2,428
99
# 2022-05-27 # handle files import pandas as pd import matplotlib.pyplot as plt import seaborn as sns def read_expr_(fn): expr = pd.read_csv(fn) expr = expr.dropna(how='all',axis=1) for c in expr.columns: if (expr[c]==0).all(): expr = expr.drop(c,axis=1) return expr def read_expr...
b794077382da2a244f12e719c0cd05dc1f8271602ecea8560e55f4b5ce315746
Python
2,429
67
import sys sys.path.insert(0, '../') sys.path.insert(0, '../../') sys.path.insert(0, '../../../') sys.path.insert(0, '../../../ogb') import argparse import torch from torch_geometric.nn import Node2Vec from ogb.linkproppred import PygLinkPropPredDataset def save_embedding(dataset_name, model): embedding_name =...
48eb23bb3cefce1be3053907a5c2eece3254073249a3c9c6111d3290cc84377a
Python
2,430
62
# Copyright (C) 2021-2022 Intel Corporation # Copyright (C) CVAT.ai Corporation # # SPDX-License-Identifier: MIT import os.path as osp import shutil from datumaro.components.dataset import Dataset from datumaro.plugins.data_formats.kitti.format import KittiPath, write_label_map from cvat.apps.dataset_manager.binding...
fa80197b11edb2bbd3ee35c639aee6e4362c380e75a83dae0c0d0a678d52fb65
Python
2,431
94
# Copyright (C) CVAT.ai Corporation # # SPDX-License-Identifier: MIT import io import unittest from pathlib import Path from typing import Any import pytest from cvat_sdk import make_client from shared.utils.config import BASE_URL, USER_PASS from shared.utils.helpers import generate_image_file def run_cli( te...
24fae60477b55679a23c07ff1628e7e3af72f31384e6a74f781bfb62beff7be6
Python
2,432
69
# model_utils.py import torch import pandas as pd # Assuming you have your model class defined somewhere, e.g., up_cnn_model.py from .cnn_train import up_cnn_model def load_model(model_path): """ Load the trained model. """ model_cnn = up_cnn_model.CNN_Class() model_cnn.load_state_dict(torch.load...
6260f05663972c3e0b5fc428419f9239105012cf29f6e54d01a0af40e3b32bc3
Python
2,432
69
import random import numpy as np from analogainas.search_spaces.resnet_macro_architecture import Network from analogainas.search_spaces.config_space import ConfigSpace from analogainas.search_algorithms.worker import Worker from analogainas.search_spaces.train import train from analogainas.utils import * import csv EP...
cbf51585060454c3c05c7dbee27908c871847e2e2c7359f90eff4f4c7c9489c7
Python
2,434
85
""" generate location of poles with x sampled from gaussian process """ from scipy import spatial import numpy as np def generate_path(y_min, y_max, sigma, amplitude=0.12, gp_mean=0, n_poll=15): """ Args: """ # Sample from the Gaussian process distribution # Independent variable samples ...
eb5fc9d58652817bb2342700631706ab364d4f031e4e8a254a4346d705128907
Python
2,434
89
# Copyright (C) 2018-2022 Intel Corporation # Copyright (C) CVAT.ai Corporation # # SPDX-License-Identifier: MIT import os from rq import Worker import cvat.utils.remote_debugger as debug DefaultWorker = Worker class BaseDeathPenalty: def __init__(self, timeout, exception, **kwargs): pass def __e...
a2a676f4360dd1be976d1f2ac9f1465b6ff5aa2b2c4f8327fcb1d3203ab42d86
Python
2,436
64
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Imports ----------------------------------------------------------------- # import...
e99f8946277ac8c31ce0d7634b5bd775781fb148051f50669d006685056451b2
Python
2,436
91
import os, sys import numpy as np import scipy.ndimage def gen_s2s(gen, batch_size=1): while True: X = next(gen) fixed = X[0] moving = X[1] # generate a zero tensor as pseudo labels Zero = np.zeros((1)) yield ([fixed, moving], [fixed, Zero, fixed,...
f493eb2a4148f501b74b290f0a1367559265745eb9cfd8b51be32f4829233f51
Python
2,436
88
import json import torch from pymatgen.core.structure import Structure from pymatgen.io.jarvis import JarvisAtomsAdaptor from tqdm import tqdm data = 'BOTH-SN-Em-test.json' # The data to re-train on (gvrh) model_path = 'checkpoint_500.pt' # The model checkpoint to load initially (std_phonons) freeze_before = 8 # T...
82b9ba36d1b57253824c034738f1540765655a787a897b47b0cea0badb499341
Python
2,437
66
#!/usr/bin/env python # Somewhat hacky way of importing from . import gauss from . import mfn from . import relu from . import siren from . import wire from . import wire2d model_dict = {'gauss': gauss, 'mfn': mfn, 'relu': relu, 'siren': siren, 'wire': wire, ...
c52b9455a48c83eb034396228ef8e5f6bc0ad7ce761e98e069dff5e6210f8c4e
Python
2,437
79
from argclz import try_int_type, AbstractParser, as_argument from rscvp.statistic._var import GENERIC_HEADERS from rscvp.statistic.csv_agg.core import ParquetSheetSync, NeuronDataAggregator from rscvp.util.cli.cli_statistic import StatisticOptions __all__ = ['GenericAggOptions'] class GenericAggOptions(AbstractParse...
ce1f2454e7a3c910b93b8bc00d7b03e57d91fa79880c4f08b3bb7c7c7fd665ad
Python
2,437
56
from nipype.interfaces.fsl import Reorient2Std from PUMI.engine import BidsPipeline, NestedNode as Node from PUMI.pipelines.anat.anat_proc import anat_proc from PUMI.pipelines.func.compcor import anat_noise_roi, compcor from PUMI.pipelines.anat.func_to_anat import func2anat import os ROOT_DIR = os.path.dirname(os.get...
dd18f566684f46ebaf1591bd7f474e3b8b3226ac05da40b26fcdfeba1897a02f
Python
2,437
75
# -*- coding: utf-8 -*- """ Map2ana In the following script, source data is transformed using a deformation field and the transformed data is mapped onto a surface mesh in the target space. The deformation of the input data is optional. The script needs an installation of freesurfer. """ # python standard library in...
f5b0bfe2dfbfbb6732cca2f7fa22a4edb0cd50d6275ced04bd051c0127e90943
Python
2,437
69
# This file is part of Eigen, a lightweight C++ template library # for linear algebra. # # Copyright (C) 2012 Keir Mierle <mierle@gmail.com> # # This Source Code Form is subject to the terms of the Mozilla # Public License v. 2.0. If a copy of the MPL was not distributed # with this file, You can obtain one at h...
f69650add2ba0c9c743a0c6ae48b8991563919caefd7d91437903349157578af
Python
2,437
65
import os import torch import pandas as pd import numpy as np import json from pathlib import Path import torch.multiprocessing as mp import sys sys.path.append("..") from preprocess import * from tqdm import tqdm def generate_transfer_data(): data_path = Path("/data2/whr/czl/TwiBot22-baselines/datasets/Twibot-22"...
215a3e27a7967812f8a011e7c9e584ebd072db721de48c1f648ed112f2acf2f6
Python
2,438
28
from testsetclass import TestsetClass class YBDE18(TestsetClass): def __init__(self): self.weak = 1.0 self.molecules = ['h2s', 'f2s', 'pf3', 'pf3-ch2', 'nme3-cbh22', 'pme3-cbh22', 'f2s-ch2', 'me2s-cbh22', 'ph3', 'nf3-ch2', 'pme3', 'h2s-cbh22', 'ch2', 'nh3-cbh22', 'nh3-ch2', 'nme3-ch2', 'nf3', 'nf3...
c8de8b8850319c8e47045e8707fdfb3d873ece476c4105620fe54964a7fcc0d7
Python
2,438
82
import numpy as np import pandas as pd import pingouin as pg import seaborn as sns from matplotlib.axes import Axes from rscvp.util.cli.cli_celltype import CellTypeSelectionOptions from rscvp.util.cli.cli_output import DataOutput from argclz import AbstractParser, as_argument from neuralib.plot import plot_figure from...
ee67a5bacd2e21090f9ea262b652053a57eaa68b6d570cb063db9230c0b7bb72
Python
2,438
61
#!/usr/bin/env python """Evaluation script to compare predicted and native PDB structures using TM-score.""" import os import argparse import shutil from utils_trX2dy.evaluate_utils import run_score def main(): parser = argparse.ArgumentParser( description="Evaluate predicted structures by comparing with n...
065709c712f54a4e48accb8f5f100e1471398a6dd12cb97724fc7a3904af354c
Python
2,439
92
import os import torch import yaml from external_models.dna_bert import DNABertTokenizer DEVICE = ("cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu") DEVICE = "cpu" DEVICE_TRAINING = ("cuda" if torch.cuda.is_available() else "mps" i...
1bc64ac5e8eb74cf2ffc26d12519f1422d31edc958232a8155069370bf31d14e
Python
2,439
76
import io import logging import pytest from chemgraph.utils.logging_config import configure_logging @pytest.fixture def isolated_chemgraph_logging(): """Isolate global logger mutations made by ``configure_logging``.""" root = logging.getLogger() package = logging.getLogger("chemgraph") child = loggi...
eba2f6294bb179529da1d3892774de0fcf672f24e3d5588bff07f023ea4782bb
Python
2,439
80
#!/usr/bin/python # ## @file # # Convert .stv files to .mat files for those who persist in using Matlab # and want to be able to manipulate image mosaics. # # Hazen 07/13 # import os import pickle import numpy import scipy.io import sys if (len(sys.argv) != 2): print("Usage <mosaic_file>") exit() directory =...
a36809ececd2da21689ed95fb77a2bb79b9b962675f2cfd9b91d06d6d21053cf
Python
2,440
73
from collections.abc import Sequence class Vocab: def __init__( self, tokens: list[str] | None = None, stoi: dict[str, int] | None = None, ): self.itos: list[str] = [] # index to string self.stoi: dict[str, int] = {} # string to index self.default_index: int =...
9df882d6103f307b89e2460d2f6862d32adcc28f1244ba107263878a6adae9da
Python
2,441
77
""" Module for IO of files in relation to data loading. """ import glob import itertools as it import os import random from typing import List, Tuple, Union import h5py def get_h5_sorted_keys(filename: str) -> List[str]: """ Function to get sorted keys from filename :param filename: h5 file. :return:...
eff0eee0bee8ff23a32f065bac326b9a5cf5a1dea0fef82ab16666996a5f4d24
Python
2,441
87
import os import os.path as op import nibabel as nib from dipy.reconst import fwdti import AFQ.utils.models as ut __all__ = ["fit_fwdti"] def _fit(data, gtab, mask): fwmodel = fwdti.FreeWaterTensorModel(gtab) fwfit = fwmodel.fit(data, mask=mask) return fwfit def fit_fwdti( data_files, bval_files,...
399446694da4d91eb69f40c00470321c4e56b1b4a28e85c15997bbe76b5f6927
Python
2,442
73
# Copyright (C) 2021-2022 Intel Corporation # Copyright (C) CVAT.ai Corporation # # SPDX-License-Identifier: MIT from allauth.account import app_settings as allauth_settings from dj_rest_auth.views import ( LogoutView, PasswordChangeView, PasswordResetConfirmView, PasswordResetView, ) from django.conf ...
5a9aea8ab0bc647b9ac8dbe823b69a4bc80a9dd65cf2cc412b88b07f4d37ef92
Python
2,442
88
import json import torch from pymatgen.core.structure import Structure from pymatgen.io.jarvis import JarvisAtomsAdaptor from tqdm import tqdm data = 'BOTH-SN-Em-test.json' # The data to re-train on (gvrh) model_path = 'checkpoint_500.pt' # The model checkpoint to load initially (std_phonons) freeze_before = 8 # T...
23edd99a66ac7caf5c763413e25ee3a785ea9936a09ec6aa29ccf502190f793f
Python
2,443
73
import numpy as np import pytest from eir.interpretation import interpret_omics def test_rescale_gradients(): input_array = np.array([[0, 0, 1], [0, 0, 2], [0, 0, 4]]) rescaled_array = interpret_omics.rescale_gradients(gradients=input_array) assert ( rescaled_array == np.array([[0, 0, 0.25], [0...
d7e4d4ba77121c66e3e824e2706d09007241bc9b3278541fa558312f8d751131
Python
2,444
72
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Select b-values on specific b-value shells. With the --tolerance argument, this is useful for sampling schemes where b-values of a shell are not all identical. Adjust the tolerance to vary the accepted interval around the targetted b-value. For example, a b-value of ...
8bd2c17dddcd104d79ea12c8325f5fd4a35117c835c50e18ecb317e6e9ebc122
Python
2,445
73
from __future__ import absolute_import from typing import TextIO import os import logging def init_logger(log_name=None, log_file=None): """ Adopted from OpenNMT-py: https://github.com/OpenNMT/OpenNMT-py/blob/master/onmt/utils/logging.py """ log_format = logging.Formatter("[%(asctime)s %(leve...
ab1e8c9d2e228ef61a8caf229462ec65e939ef8fc88ac4c641995b19ffa57f70
Python
2,445
87
from torch import nn import torch from model.non_local_embedded_gaussian import NONLocalBlock1D # 冻结网络层 def freeze(model): for param in model.parameters(): param.requires_grad = False class Network(nn.Module): def __init__(self): super(Network, self).__init__() self.conv_1 = nn.Seque...
44f5a2cb1fb70e5a50470270ad4d7f09450157ff9f5709786e691a4b7156065c
Python
2,446
66
#!/usr/bin/env python3 import nibabel as nib import numpy as np import SimpleITK as sitk import os import tempfile import argparse def nifti_warp_to_h5(input_nifti: str, output_h5: str): """ Convert a 4D NIfTI warp field (x,y,z,3) to an ANTs-compatible .h5 transform file. The function creates a temporary N...
9d8b26700e41fb36f7970af6db1007b09dec0501eeb795633898db1e2d8ce603
Python
2,446
65
#!/usr/bin/env python3 """Read a Thalamus capture (``.tha``) file and plot its analog channels. This demonstrates reading raw records directly with ``thalamus.record_reader2`` (no hydration step required) and reconstructing per-channel time series. It works on the file produced by ``synthetic_recording.py`` or on any...
a489646c31efbde0e8bf1be198b98d28718bf62185a9d7868ce195657a47b8fe
Python
2,446
62
#!/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=['bst.zip']) tmp_dir = tempfile.Temporar...
d8e611a54aef73f2fc7d5541d94cf0adf48bfe0b4c8b4d7eff60762d038227e5
Python
2,447
77
import numpy as np import os import pandas as pd import SimpleITK as sitk from radiomics import featureextractor, getFeatureClasses DICOM_dir = r'' SEG_dir = r'' label_path = r'' feature_outputFilepath = r'' feature_with_class_outputFilepath = r'' label_outputFilepath = r'' discard = [] table = [] ta...
11e50c5e5519736a6a0138a32a4ab56fd4da0977c0ffe054a043fbbf985cac21
Python
2,449
74
from torch.utils.data import DataLoader from geoseg.losses import * from geoseg.datasets.vaihingen_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 = 8...
f0b27a5a6626cdfc8d269988360e354af24b86fd7d3bdba47835ef5b0a79068b
Python
2,449
88
import json import torch from pymatgen.core.structure import Structure from pymatgen.io.jarvis import JarvisAtomsAdaptor from tqdm import tqdm data = 'SINGLE-BOTH-SN-Em-test.json' # The data to re-train on (gvrh) model_path = 'checkpoint_500.pt' # The model checkpoint to load initially (std_phonons) freeze_before ...
77b669cfadf78b4df5634fd67bc80a2cf2d37f7d0d6257a812b34e8db0b1f053
Python
2,450
145
from nipype.pipeline import engine as pe # Registration and transformation # Registration workflows def init_surftransform_wf(): """ Worflow that transforms gifti or freesurfer surfaces using ants transform Parameters ---------- Inputs ------ - gifti or freesurfer surface - ants tran...
f7ee00984a169937a2dc95ccb8eeb94f3535c51535b13c205313a6eddeda35b1
Python
2,450
69
import subprocess from lyroi.utils import check_version_local, check_version_online, check_model, get_download_size, format_file_size from lyroi.modes import get_mode_list, get_pretty_name, get_folds, get_suffix_dict, get_archive_names class ModelManager: def get_available_models(self): return get_mode_...
4e280b826845b5bed653132d27998b7b5e641ba1f8a284809ded00936e811695
Python
2,451
70
# This file is part of connectome-manipulator. # # SPDX-License-Identifier: Apache-2.0 # Copyright (c) 2024 Blue Brain Project/EPFL import os import numpy as np from numpy.testing import assert_array_equal, assert_array_almost_equal from bluepysnap import Circuit from utils import TEST_DATA_DIR import connectome_mani...
096f4cb227615d092d58cb11b323575e7cc7328207316ae6b32494b076b9c5ed
Python
2,452
64
import os import yaml import torch import models import argparse import numpy as np from utils.utils import * import matplotlib.pyplot as plt from scipy.io import loadmat, savemat def main(args): # construct fitting model model = getattr(getattr(models, args.model), args.model) with open(os.pa...
942dabda8d469f438da86a8991afc135c9558e94d8e2502f30bee86ab2d7b617
Python
2,452
52
from train_gtex import * def main(): model_type = 'MultiGene' current_dir = os.path.dirname(__file__) DATA_DIR = os.path.join(current_dir,'../data') config_path = os.path.join(current_dir,"configs/multi_gene_196kb_blood.yaml") remaining_tests = [(0,'0ubse6xy','epoch=19-step=24080.ckpt'),(2,'ega4xl1...
ab1ae90336c05ae6c8448b3c584722b13a47d53a0ea4a1e4e057a01c1faf5e07
Python
2,452
74
# -*- coding: utf-8 -*- import numpy as np supported_tensor_formats = ['fsl', 'nifti', 'mrtrix', 'dipy'] tensor_format_description = \ """ Dipy's order is [Dxx, Dxy, Dyy, Dxz, Dyz, Dzz] Shape: [i, j , k, 6]. Ref: https://github.com/dipy/dipy/blob/master/dipy/reconst/dti.py#L1639 MRTRIX'...
e41f913c6a9c94a8d1876986d2e83af50537a35eca902c7bd105561c2f756be1
Python
2,452
63
import pytest from qtpy import PYQT5, PYQT_VERSION, PYSIDE2, QtQuick def test_qtquick(): """Test the qtpy.QtQuick namespace""" if PYQT5: assert QtQuick.QQuickCloseEvent is not None assert QtQuick.QSGFlatColorMaterial is not None assert QtQuick.QSGImageNode is not None assert Q...
3a4a5447e7cc91418b96d96982fceea70bbbdd3ad7af7b98ab147a807a8c95a7
Python
2,453
69
from pathlib import Path import random from typing import Final, Optional import cv2 import torch from torch.utils import data from torchvision.transforms import v2 IMG_SIZE: Final[int] = 224 class TextureDataset(data.Dataset): def __init__(self, root_path: Path, patients: li...
8defca0eaf390aaa3e999d6266c5f9ad5ad00fafb3f9a1bf80b221cb8293012c
Python
2,454
84
import os from collections import OrderedDict import numpy as np import pandas as pd import pytest from openturns import Distribution, TestResult from impedancefitter import Fitter, PostProcess, get_equivalent_circuit_model @pytest.fixture def postprocessRC(): """Initialise postprocessing on RC circuit data."""...
94dce280ff5d90b7973e5242f79a35ff6da88d1f4320fafc454e09ee08b6a263
Python
2,455
89
from PIL import Image, ImageChops path = '' # specify your path here # Utility to crop transparent border def crop_alpha(image): bg = Image.new("RGBA", image.size, (0, 0, 0, 0)) diff = ImageChops.difference(image, bg) bbox = diff.getbbox() return image.crop(bbox) if bbox else image for name in ['_L+R_...
d8c3cae3f530b56d282f5b6e15bbb2dda12789768b37963c7dc2fd8377158341
Python
2,455
70
""" src/prepare_data.py =================== 功能: 1. 调用 utils.data_utils.load_data() 读取并预处理数据。 2. 使用 MultilabelStratifiedKFold 将样本按多标签分层方式 划分为 10 折,保存每折的 train / val 索引。 3. 额外生成 1000 份 bootstrap 采样索引,可供稳健评估使用。 运行 ---- $ python -m src.prepare_data """ from __future__ import annotations import os import pickle from ...
cf94c40fa85beacff900b7f8f7453bb821165924b6b643d8f2ca001479168470
Python
2,456
91
import urllib.request as ur import zipfile import os import os.path as osp from six.moves import urllib import errno from tqdm import tqdm GBFACTOR = float(1 << 30) def decide_download(url): d = ur.urlopen(url) size = int(d.info()["Content-Length"])/GBFACTOR ### confirm if larger than 1GB if size > 1...
571bb1c6c7825f7403cbf7b78f80c376cd1241bb4b016f082e170a3210f92830
Python
2,457
137
''' Code for C. Nazaret et. al. / Journal of theoretical biology 2009 Original code in scilab (author Nazaret) Ported to python3 (author chaitanya) This code generates figure 7 and figure 8 from the paper. ''' from math import exp from scipy.integrate import odeint import numpy as np import matplotlib.pyplot as plt ...
67244ab72405b5001dc60b7f5072996909897e586ed8dea8331d93eb76bd17a6
Python
2,457
76
import os, sys import pandas as pd import re # Directory containing variant folders DIR = sys.argv[1] output_file = sys.argv[2] # Columns to include COLUMNS = [ "total_score","dslf_fa13","fa_atr","fa_dun","fa_elec","fa_intra_rep", "fa_rep","fa_sol","hbond_bb_sc","hbond_lr_bb","hbond_sc","hbond_sr_bb", "om...
7516d690f8f47b22c6649a2e037aa79246897f87ea5165891dc47438a82f09aa
Python
2,457
81
import inspect from typing import Any, Callable, Optional, Sequence, Union from napari.qt.threading import FunctionWorker, GeneratorWorker, create_worker def do_work_async( function: Callable, return_callback: Optional[Union[Callable, Sequence[Callable]]] = None, yield_callback: Optional[Union[Callable, ...
fcaa8b0606a619bc911df5b85479029eaf3ce582d5fea168b1a15bb187ddf264
Python
2,457
66
import numpy as np def compute_tp_fp_fn_tn(mask_ref, mask_pred, ignore_mask=None): if ignore_mask is None: use_mask = np.ones_like(mask_ref, dtype=bool) else: use_mask = ~ignore_mask tp = np.sum((mask_ref & mask_pred) & use_mask) fp = np.sum(((~mask_ref) & mask_pred) & use_mask) fn...
40d6a2612d47d044ad6648ff5310a1d5cb0b726e2b860285a4c5d92c9032930d
Python
2,458
74
# Copyright (c) 2015 Tobias Neumann, Philipp Rescheneder. # # This file is part of Slamdunk. # # Slamdunk is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your ...
fd83686f78d9ff8415c1f5699624fd7f8df96aa3232cd2d815c296e298321f67
Python
2,458
69
""" Pseudo-dyad validation template. This script provides a simplified permutation-style template. If the repository contains only dyad-level processed data, true pseudo-dyad reconstruction from raw participant-level time series cannot be performed. Therefore, this script demonstrates a conservative label-permutation ...
65753ac0f3c8c798a31d092e49f17bd17246408146251d316268e146a342931b
Python
2,459
88
import lmfit import numpy as np import impedancefitter as ifit from impedancefitter.time_domain import ( calculate_impedance_spectrum_using_cwt, calculate_impedance_spectrum_using_fft, fit_impedance_from_time_domain, predict_time_domain_signal, rectangle, ) fs = 10000 # 10 kHz sampling dt = 1.0 /...
daedc6e5df05ca8a6a7ead47114018b17a1e9ca7292638a06b6679d05ea0025e
Python
2,460
65
from .unet2 import unet import torch import torch.nn as nn import torch.nn.functional as F from clustercontrast.utils.serialization import load_checkpoint class MoECrossAttention(nn.Module): def __init__(self, output_dim=4608, dropout=0.1, num_features=0,new_in_channels=0,**args): super(MoECrossAttention,...
a82616ddf2e4dda5f9c49e432ef528b1d68a2c23f01628c30a110df2c6f94a61
Python
2,461
57
import numpy as np import pytest from pytest import approx from brainscore_core.supported_data_standards.brainio.assemblies import BehavioralAssembly from brainscore_vision.benchmarks.imagenet_c import Imagenet_C_Noise, Imagenet_C_Blur, \ Imagenet_C_Weather, Imagenet_C_Digital from brainscore_vision.model_interfac...
e094f7e4e8d819bf747e85784ba76e88d8f43777a7dfcf86025fd96e6eeb29ff
Python
2,461
66
# Sourced from https://github.com/fwillett/speechBCI/blob/main/NeuralDecoder/neuralDecoder/models.py import tensorflow as tf class GRU(tf.keras.Model): def __init__(self, units, weightReg, nClasses, dropout=0.0, nL...
11f774f9bf02bbd28211cfbc363b508b8652cc0fd27381ba39afbecf3b908eb2
Python
2,462
76
import pandas as pd import time import ijson import content_feature as cf import csv import spacy nlp = spacy.load('en_core_web_lg') def get_content_vector(tweets): links = cf.count_urls(tweets) mentions = cf.count_mentions(tweets) content_vector = { "links_ratio":links[0], "unique_links_ra...