sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
121b63923241eaa0c334a63092546c4940382a234b45efc1bcbf2b7d796ba2a7
Python
4,068
97
"""Tests for the OBJ/MTL/colormap writer (numpy + matplotlib; no vtk needed).""" import os import tempfile import numpy as np from surface_morphometrics import export_obj as eo def _mesh(): pts = np.array([[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0], [2, 0, 0]], float) faces = np.array([[0, 1, 2], [0, 2, 3],...
f5243c92f543868332ba0fde98b5c84daeb2df3b6e37517ed3575dc8fd524562
Python
4,068
105
import subprocess import os import glob import pandas as pd import multiprocessing as mp import subprocess import argparse def read_result(xinput): index, path = xinput print(f" * {index}: {path}") df_ind = pd.read_csv(path, sep="\t") df_ind.rename(columns={'bam': 'sample_id'}, inplace=True) df_i...
55ce148525db03648f0837ab5cda9be634922e47a5fcaaaf7d3b9ca65d9bdf94
Python
4,070
123
# -*- coding: utf-8 -*- """ Outlier detection This script looks for outliers in a functional time series using the Afni function 3dToutcount. The fraction of outliers found within a volume defined by a mask are written out for each time point. Additionally, a graphical visualization, a regressor of no interest and a s...
f8c2a72a011af7679edb68e84b6bf2506285e1559d405914506225c9c594df0c
Python
4,070
124
# -*- coding: utf-8 -*- """ Simulation study regarding the hemodynamic response function Joram Soch, MPI Leipzig <soch@cbs.mpg.de> 2023-08-24, 19:20: first version 2023-08-28, 10:15: minor changes 2023-08-28, 15:38: corrected derivatives """ ### Step 0: specify settings ##############################################...
48dfae5d71adf44e910c1f20c5f5eca55ca0a3232fa826db619b40e6a349c7df
Python
4,071
113
"""Contains the command-line interface for the ViRelAy application.""" import argparse import atexit import os import flask from virelay import __version__ from virelay.model import Workspace from virelay.server import Server def run_cli_app() -> None: """Runs the application with a command-line interface (CLI...
6142808fcc1e967801a173b056874a5c07eda40b5dfca24139f91f6b1ba8c060
Python
4,072
105
import os from argparse import ArgumentParser from dataset import SATARDataset import numpy as np import time import torch import torch.nn as nn from torch.utils.data import DataLoader from model import SATAR, BotClassifier from utils import calc_metrics device = torch.device('cuda' if torch.cuda.is_available() else '...
b1f8b8d4caade843f076d90c6e8b59788e3749f433551ac5a1e4971833bce13c
Python
4,073
129
import logging from collections import defaultdict from torch.utils.data.sampler import Sampler import random, torch from flair.data import FlairDataset log = logging.getLogger("flair") class ImbalancedClassificationDatasetSampler(Sampler): """Use this to upsample rare classes and downsample common classes in ...
3bdefe6b2d455c2cd57b318c6e371d77ba18f694f508b50540de77502ab3fc35
Python
4,074
113
#!/usr/bin/env python import numpy as np import pandas as pd import click as ck import sys from collections import deque import time import logging import math from deepgo.utils import FUNC_DICT, Ontology, NAMESPACES from deepgo.metrics import compute_metrics logging.basicConfig(format='%(levelname)s:%(message)s', le...
8372fed77678b77ef29cf3e67f255cfe5b25a245fc106a7807abf487006a21a1
Python
4,074
101
"""Why a bundle shows no peak-detection traces. uv run python python/diagnose_bundle_traces.py <run>.meanap Reads the bundle's own manifest and params, so it answers the question without the output folder, the raw data or the run's log. """ from __future__ import annotations import sys from pathlib import Path ...
f8d0119c4f61516c3008deeee782593e148224f9eb941bbdf3fd62011105d06e
Python
4,074
123
from obspy.clients.fdsn.mass_downloader.domain import ( CircularDomain, Domain, RectangularDomain, ) from obspy.geodetics.base import locations2degrees class RectangleDomain(RectangularDomain): """ A rectangular domain defined by latitude and longitude bounds. Edges are included in the domain. ...
be208f660a0db77af8c532f711b6cb1cb4cc606a8e541d819df051bc637857e7
Python
4,075
124
# -*- coding: utf-8 -*- """ Simulation of imaging MTF The purpose of the following script is to simulate the imaging modulation transfer function from a GE-EPI from imaging of a thin slid. The slid is parallel to the x-direction (read direction). The following steps are done: 1. generate input image 2. simulat...
bfb3bb04c0600c0199373a8c2ba87d7ba33f9b0f357903155eb5f4bef9a6860f
Python
4,075
97
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations from copy import copy import torch from ultralytics.data.utils import get_split_fraction from ultralytics.models.yolo.detect import DetectionTrainer from ultralytics.nn.tasks import RTDETRDetectionModel from ultra...
1e24a8774390f530dadef9ada79035edbf1954ed4cae1703bb53d0f2f06dd9a7
Python
4,076
114
from typing import Any, Optional, Sequence, Tuple, Union import torch.nn as nn from monai.utils import ensure_tuple_rep from monai.networks.nets import UNet from monai.networks.blocks import Convolution, ResidualUnit, SubpixelUpsample from monai.networks.layers import Act, Conv, Norm from monai.networks.layers.simplela...
9f7900e5a63cc8651d73db630bc83a0c3eb81f60d6c61672e085a89c64889c06
Python
4,076
118
import numpy as np from scipy.spatial.transform import Rotation from scipy.interpolate import RBFInterpolator from sklearn.kernel_approximation import Nystroem # Nyström 近似 from sklearn.neighbors import NearestNeighbors def kernel_interpolate( Y, # (N, D) target points y, # (M, D) source points ...
0972c8b15594e518c15876c3993e78e481e44ac3cf1386504ab1c79cbb4fe670
Python
4,077
113
from pathlib import Path from typing import TYPE_CHECKING import pandas as pd if TYPE_CHECKING: from eir.setup.output_setup import al_output_objects_as_dict def check_performance_result_wrapper( outputs: "al_output_objects_as_dict", run_path: Path, max_thresholds: tuple[float, float], min_thresh...
7f57e31777c0256808dfea7ea5e826cbbb833633cac8ccdec9be9c0eb38bfb8f
Python
4,077
87
import numpy as np from brainscore_core.supported_data_standards.brainio.assemblies import BehavioralAssembly from brainscore_core.supported_data_standards.brainio.packaging import package_data_assembly import pandas as pd ''' Experiment Information: https://arxiv.org/pdf/1706.06969.pdf - 5 subjects - 800 trials ...
88d136afc3b510539a57573449241c171267b18e63a1e3f6acc826dd87033ea9
Python
4,077
128
import os import numpy as np import torch from scipy.sparse import csr_matrix import numba import logging import random import spotd.simulation_st from spotd.utils import * import scvi def get_scvi_latent( st_ad, sm_ad, n_layers, n_latent, gene_likelihood='zinb...
3cb4ae02d7c419dc3b9adccc47617e0310805c3cfa07dfee1b73816a5ff2a04a
Python
4,078
118
'''Pre-activation ResNet in PyTorch. Reference: [1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun Identity Mappings in Deep Residual Networks. arXiv:1603.05027 ''' import torch import torch.nn as nn import torch.nn.functional as F class PreActBlock(nn.Module): '''Pre-activation version of the BasicBlock....
5e7735c8edac62ee2bd5f18f9dad9106da68a4bfbcde540f19053cca3c19f095
Python
4,078
77
import numpy as np from collections import OrderedDict from tqdm import tqdm from .base import TemporalContextInferencerBase from brainscore_vision.model_helpers.activations.temporal.utils import stack_with_nan_padding class BlockInferencer(TemporalContextInferencerBase): """Inferencer that divides the original ...
6bc1723a3e56758f49c2fffedc2e1becde6588196d01d9744783ab86d426a52d
Python
4,078
125
from .qt import * from .observable_item_models import TreeObservableCollectionModel from .config import ObservableDict import os import oslex import shutil import typing import asyncio import logging import platform import subprocess from .task_controller.util import create_task_with_exc_handling LOGGER = logging.get...
3074c297605f854a1a415fe5c4d7cde239ec8a00cc53030282fa48ee67377f59
Python
4,079
88
import numpy as np from brainscore_core.supported_data_standards.brainio.assemblies import BehavioralAssembly from brainscore_core.supported_data_standards.brainio.packaging import package_data_assembly import pandas as pd ''' Experiment Information: https://arxiv.org/pdf/1706.06969.pdf - 4 subjects - 1120 images...
6ef20c505606305c96f3ffa215fdd4f691f83473f1e8db901e4ba2c8897ee973
Python
4,080
161
# am i optimizing prematurely? do we need this heavy machinary? from sqlalchemy import Column, Integer, String, Float, ForeignKey, create_engine from sqlalchemy.ext.declarative import declarative_base, declared_attr from sqlalchemy.orm import relationship, sessionmaker Base = declarative_base() session = None de...
083f0bfcf19b7fdb4e13a7078ed03b384b76478acd17c0bcd589153f6307d35b
Python
4,081
111
from dataclasses import dataclass from typing import Optional import torch from torch import Tensor import torch_geometric.typing from torch_geometric.nn.pool.select import SelectOutput @dataclass(init=False) class ConnectOutput: r"""The output of the :class:`Connect` method, which holds the coarsened graph...
7a309d1b635e0e37868f10c0de8807e08bf78c14f2dc5a68665b536042029d69
Python
4,081
107
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ This script harmonizes labels across a set of lesion files represented in NIfTI format. It ensures that labels are consistent across multiple input images by matching labels between images based on spatial proximity and overlap criteria. The script works iteratively, ...
3723abfad5c4cf3066615aa2249b5b3073bda69de20163bb924d39bdeb56fdeb
Python
4,084
120
import os from typing import List, Optional import hydra from omegaconf import DictConfig from pytorch_lightning import ( Callback, LightningDataModule, LightningModule, Trainer, seed_everything, ) from pytorch_lightning.loggers import LightningLoggerBase from {{cookiecutter.project_slug}} import u...
e56c4211cd0fffe3ad928ac9ad5c4921d894e731cd2cc04a57307da9cbc195de
Python
4,084
118
from zigzag.classes.cacti.cacti_parser import CactiParser import logging logger = logging.getLogger(__name__) class MemoryInstance: def __init__( self, name: str, size: int, r_bw: int, technology: int = 45, datawidth: int = 1, w_bw: int = 0, r_cost: f...
d05a8196491e511b43c252507b7f02876caa659b385ba0ec0e69ea71c05eca58
Python
4,085
107
import csv import os import pickle from typing import List import numpy as np import pandas as pd from rdkit.Chem import PandasTools def save_features(path: str, features: List[np.ndarray]) -> None: """ Saves features to a compressed :code:`.npz` file with array name "features". :param path: Path to a :...
ff1dc5e0b5cedd4c78ae19b53fb20f5901f13dbdea5e96b5f41bd6929cf4b031
Python
4,085
88
import numpy as np import torch import faiss import torch.nn as nn from typing import List, Mapping, Optional, Union, Tuple, Any from numpy import ndarray from sklearn.metrics.pairwise import euclidean_distances from anndata import AnnData def spatial_match(embes: List[torch.Tensor], reorder: Optio...
7482313c4a53525a2a726884e191cf9f2da150d41c4929accbaf0bbd93fd06af
Python
4,086
106
import torch import torchvision from torch import Tensor import torch.nn as nn import math import numpy as np import torch.nn.functional as F from torch.hub import load_state_dict_from_url from torchvision.models.efficientnet import _efficientnet_conf from .functions import ReverseLayerF # torchvision.__version__ == '...
81a418b2949b48e6f7ea1091f953cc5d2f544ae8e4bc9e6bb77c85471069c504
Python
4,086
104
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Splits the DWI image at certain indices along the last dimension (b-values). Many indices can be given at once by specifying multiple values. The splited volumes are in the same order as in the original file. Also outputs the corresponding .bval and .bvec files. This ...
8e6c5da676acd1ee23520d09c2661e721a8c57b849438b57931054dd220fb0be
Python
4,086
86
from .create_visualization import visualization from .create_visualization import visualization_continue from .create_visualization import visualization_continue_fastq from .qiita_visualization import qiita_visualization from .fastq_visualization import fastq_visualization import os # This function downloads the acc...
e9d92ee5b71e2ac6e2f2ed62982ea87c7c5707a69818f8b81647e71281446a1a
Python
4,087
140
#!/usr/bin/env python """ Given a list of intervals in BED format (`interval_file`) and a set of scores (`score_file`) print each interval plus the average, minimum, and maximum of the scores that fall in that interval. Scores can either be wiggle format data or a directory containing binned array files (named accordi...
eeea51c88ebeee70a06b4e1184bce00196cd1e5842d24992bf11a5829fd89af5
Python
4,087
112
# -*- coding: utf-8 -*- import os join = os.path.join import random import numpy as np from skimage import io import SimpleITK as sitk def dcm2nii(dcm_path, nii_path): """ Convert dicom files to nii files """ reader = sitk.ImageSeriesReader() dicom_names = reader.GetGDCMSeriesFileNames(dcm_path) ...
0694e1819e9e05e30db39ef6af4bf70f6448df60cc922d68be9e7ebc196c9d71
Python
4,088
78
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 from PUMI.pipelines.func.func_proc ...
109d04511aa4c7befbf6717261434e275ec55d98d999c06ccfa48074cf296184
Python
4,088
94
# This file is part of connectome-manipulator. # # SPDX-License-Identifier: Apache-2.0 # Copyright (c) 2024 Blue Brain Project/EPFL """Connectome extraction module.""" import os import json import numpy as np from connectome_manipulator import log, profiler from connectome_manipulator.connectome_manipulation.manipu...
f5caf2e91aa983d636bfe4ead657adb3b2977d8cff5ff6376ea3011cd2bd8b10
Python
4,088
108
import collections import numpy as np from abc import ABC import torch import torch.nn.functional as F from torch import nn, autograd class CM(autograd.Function): @staticmethod def forward(ctx, inputs, targets, features, momentum): ctx.features = features ctx.momentum = momentum ctx.s...
e8d0ee4e5833aba5b60e474f7f79ed90d96245bb3c8a4f4bd568113d6df1db00
Python
4,089
128
############################################################################# # Copyright (C) 2020-2026 MEmilio # # Authors: Patrick Lenz # # 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 Licen...
ff24120f55df74b36df41c680d6702ebdca1e4899daeedc10622888efee171ad
Python
4,089
101
import anndata import pandas as pd import numpy as np import logging from typing import Optional, Dict logging.basicConfig(level=logging.INFO) class STMetricEvaluator: def __init__(self, real_h5ad: str, pred_csv: str, index_col: int = 0): sel...
235c2b9b545ef56acd99fb83bf3945aea67697b994ad6ab8d0900a02fdb2e7b8
Python
4,090
137
# # SPDX-FileCopyrightText: Copyright © 2022 Idiap Research Institute <contact@idiap.ch> # # SPDX-FileContributor: Alexandre Bittar <abittar@idiap.ch> # # SPDX-License-Identifier: BSD-3-Clause # # This file is part of the sparch package # """ This is where the dataloader is defined for the SHD and SSC datasets. """ im...
06b7cb4f9fb245826d34c7d75c5e0d80cefeb4d6eadf6c1244b89c09b6e71a34
Python
4,091
187
import re def get_user_id(user): return user['id'] def get_username(user): return user['username'] def get_screen_name(user): return user['name'] def has_description(user): des = user['description'] if des is None or des == ' ': return False else: return True def has_lo...
7dea3f77732cbe498fa353bc4faf95c1b6d7396aa36b4aad566530f08b2b5f9a
Python
4,091
78
#!/usr/bin/env python import common import chromatics import os import pandas as pd import sys from glob import glob config_fn = sys.argv[1] cell_line = config_fn.split('/')[0] config = common.parse_config(config_fn) os.chdir(os.path.expanduser(config['working_dir'])) expression_cutoff = 0.3 idr_cutoff = 0.1 segme...
1d98455aa0a45df6fbdf7a6b8af156da47294f754763b343e432b451088e55f8
Python
4,092
143
#!/usr/bin/python """ This function accepts a csv file produced by aratools.utils.exportMaSIVPoints2Lasagna.m Each row of the csv file produced by that function is in this format: nodeId,parentID,z position,x position,y position This module imports this file and turns it into a format suitable for plotting in lasagna....
4f454f44e89fee6ca0e84caa40b2e7a38371706d0057eb073305fb888be0143b
Python
4,093
90
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from typing import Any import cv2 from ultralytics.solutions.solutions import BaseSolution, SolutionAnnotator, SolutionResults from ultralytics.utils import LOGGER from ultralytics.utils.plotting import colors class ObjectBlurrer(BaseSolution): ...
cbecad7743048a34e5b652c89ddf7523a44d877a479669f49ea2065f1453ddee
Python
4,093
144
from types import SimpleNamespace import pytest from langchain_core.tools import BaseTool, tool from chemgraph.registry import ( DuplicateRegistryEntryError, RegistryUnavailableError, RuntimeRequirement, ToolRegistry, ToolSpec, UnknownRegistryEntryError, ) EXPECTED_TOOLS = ( "extract_out...
2c7a29a40fd7954a96e4cbcaa31180df2dcf4f549316ec00977ced9b2d19c39e
Python
4,094
120
"""Group recordings into chains: the same field of view across DIVs. A chain is one field of view followed over days. Working out which recordings belong together is pure string handling, but there is one trap in it: **both naming conventions in this dataset put the imaging date in the name alongside the DIV**, and th...
e08b22af107bfabc4d4086c1114d1a9da424f9642637dcbf47c9e050cc9e3ec3
Python
4,095
100
# -*- coding: utf-8 -*- """ Created on Mon Jun 13 15:33:01 2022 @author: Yoshi """ import os import numpy as np from PIL import Image,ImageDraw,ImageFont os.chdir("../map_generators") from cell_drawer import * def modulation_index_mapper(map_output_path,canvas,width,height,cell_locations,scale,radius,color_key,ce...
05db802cf41e40269a61942b7ba31fad838d6fa516c057ced1c20432fe0ce2e3
Python
4,097
112
import numpy as np import copy import joblib import os from sklearn.base import BaseEstimator, ClassifierMixin from sklearn.utils.validation import check_X_y, check_array, check_is_fitted from sklearn.utils.multiclass import unique_labels from xgboost import XGBClassifier class XGBoostEnsembleClassifier(BaseEstimat...
c7a6257800a8ee124d4d9862a3039d3e928ee7d702464b26b07f566b86543cd2
Python
4,097
109
import os import unittest import SVMTK tests_dir = os.path.dirname(__file__) class Slice_Test(unittest.TestCase): def test_unpack_mesh(self): slc = SVMTK.Slice(); slc.add_constraint([SVMTK.Point_2(0,0),SVMTK.Point_2(0,1),SVMTK.Point_2(1,1), SVMTK.Point_2(1,0),SVMTK.Point_2(0,0) ] ) slc...
061b8a2cc028be15d44e717a152e7bb6fa6cb455bb5ebba6e3fb5d75bd934711
Python
4,099
120
# %% ### import modules from pathlib import Path import seaborn as sns import pandas as pd import numpy as np import bap1b.figures as figures # %% ### set paths data_dir = Path(__file__).resolve().parents[1] / "data" results_dir = Path(__file__).resolve().parents[1] / "results" # %% ### load data df_results = pd.rea...
2b6790a7c59a6af7d02aa4676ee1e8750de1f6a070d5cc415c2d709f88e98d61
Python
4,099
148
""" :mod:`metrics` --- metrics and measures ============================================================= """ import numpy as np __all__ = [ "gini", # Gini coefficient of inequality ] def gini(arr, mode="all"): """Calculate the Gini coefficient(s) of a matrix or vector. Parameters ---------- a...
49aa20ec87951fbad29bf9928ed256228a00c768225c4b652366770976de9d94
Python
4,099
123
import nibabel as nib import numpy as np import scipy.io from dipy.io.stateful_tractogram import Space, StatefulTractogram from tqdm.auto import tqdm from AFQ.data.utils import BUNDLE_MAT_2_PYTHON # This dictionary is used to convert the names of the bundles # from old pyAFQ bundle names to the new pyAFQ bundle names...
5e5acc12034fce7b0c6cd72a80bc8836ee4ac9e1ac8cb1011d8b478327c0ae77
Python
4,100
106
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Removal of streamlines that are out of the volume bounding box. In voxel space, no negative coordinate and no above volume dimension coordinate are possible. Any streamline that do not respect these two conditions is removed. The --cut_invalid option will cut streamli...
f3f69ba8a321923cd4db99447b595361f255551e959e45643656cf7d7c0b75ea
Python
4,100
99
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt import sys sys.path.insert(1, r'../function_scripts') import plotting_related_functions import os import pandas as pd from statsmodels.stats.multicomp import pairwise_tukeyhsd from statsmodels.formula.api import ols import...
6223880a2c993afc079e5ed609b3d1b72ffad73e9d17000b5d6ffb05d9c0470a
Python
4,101
95
import numpy as np import xarray from brainscore_core.supported_data_standards.brainio.packaging import package_data_assembly import scipy.io as sio from brainscore_core.supported_data_standards.brainio.assemblies import DataAssembly DATA_DIR = '/braintree/data2/active/users/tmarques/bs_datasets/Ringach2002.mat' ASSE...
40e6c2c752983f4fbd39ab627a9ce6b446c36c9e58a45aff46d05d658cd568ae
Python
4,103
114
import os import sys import time import matplotlib.pyplot as plt import numpy as np # by Shaoxuan Yuan at 2024/04/22 import torch from PIL import Image from scipy.ndimage import distance_transform_edt try: from mol_segment.unet import U_Net except: from unet import U_Net # 从unet模块导入U_Net类 #...
d5d2184547d90274b85881aea18c749bebd8942fabe1d7edc82222b51a3c65d7
Python
4,103
102
from .base import MLPBlock from torch import nn import torch as th from dgl.nn.pytorch import GINConv, GraphConv import torch.nn.functional as F class GMSA(nn.Module): def __init__(self, input_dim, hidden_dim, num_heads, feat_drop, att_drop): super(GMSA, self).__init__() self.gcn1 = GraphConv(inpu...
fa26295719756807efc6b9580a81a4c0e87ab4a006284587b10c6ae051f71e66
Python
4,103
117
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Extract symbol_set from trail21-50 model files and save them to concept_vectors folder. This script reads PyTorch model files from /workspace/Results/param/ directory, extracts the 'symbol_set' tensor from each file, and saves them individually to /workspace/Results/c...
10e70a305e96411db3f3a4833bee57d215f003f7d4a57fbfa12c4033f3aff1ca
Python
4,105
163
#!/usr/bin/env python """ Application to convert AXT file to MAF file. Reads an AXT file from standard input and writes a MAF file to standard out; some statistics are written to standard error. axt_to_maf primary:lengths_file secondary:lengths_file < axt_file > maf_file --silent: prevents stats report Lengths ...
e3d7e4654d7b3e5623e61b2db6c87ea488ff7de69f7c7e064e49277ff0cbe6c7
Python
4,107
112
# Copyright (C) CVAT.ai Corporation # # SPDX-License-Identifier: MIT from http import HTTPStatus import pytest from shared.utils.config import get_method, patch_method class TestGrowthData: INITIAL_PROMPT_STATE = { "github_prompt_shown": False, "github_prompt_support_clicked": False, "g...
20ed804b4a2ea769e56a01c9ecdd13cf520c56bc6f1037843d5e1f94e52251cc
Python
4,108
107
""" Manual assignment dialog for background configurations. """ from .pyqt_utils import * class ManualBackgroundAssignmentDialog(QDialog): """Dialog for assigning saved background configurations to images.""" def __init__( self, image_names, configuration_names, current_assignments=None, parent=None...
3d3ef06a9a7d7501ca468085e1ff4cb508370fe5ebae940ba650de68879ca3fb
Python
4,108
132
import pytest import numpy as np from impyute.imputation.cs import mean from impyute.ops import error from impyute.ops import wrapper # pylint:disable=redefined-builtin try: raise ModuleNotFoundError except NameError: class ModuleNotFoundError(Exception): "placeholder required for python2.7" pa...
3aa91e9d9ae0b5545501d73e80bb93e8beaf5d0d8652a0b3ca90e80b170905b1
Python
4,109
117
# Generated by Django 3.2.8 on 2021-10-26 14:52 import django.db.models.deletion from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] ope...
b77f233c64855941e3647a47e2558cbf2dbd12379216ea7dbc6361cbc8b81cf2
Python
4,109
98
import os import random import numpy as np from PIL import Image from tqdm import tqdm #-------------------------------------------------------# # 想要增加测试集修改trainval_percent # 修改train_percent用于改变验证集的比例 9:1 # # 当前该库将测试集当作验证集使用,不单独划分测试集 #-------------------------------------------------------# trainval_percent...
bf08fbdc2ed79d2792a8a75d9e0c80f4bc5adc77c04fdc3dcafd0dc0c785347a
Python
4,111
121
#!/usr/bin/env python import os import sys import tqdm import pdb import numpy as np import torch from torch import nn import torch.nn.functional as F class ComplexGaborLayer2D(nn.Module): ''' Implicit representation with complex Gabor nonlinearity with 2D activation function Inputs; ...
12a1b19ae245b724b6fc076f9536b0693dc3d6cb668293a1565333e3591c0a04
Python
4,113
117
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Aug 18 18:03:53 2023 @author: rl05 """ import os import os.path as op from mne import read_epochs, compute_source_morph, read_source_spaces from mne.minimum_norm import read_inverse_operator, apply_inverse import config subjects = [f'sub-{subject}'...
5e9eb28b9566eb6cd6a15f2aa0900b5b8e1dc6915c44a910f9b2d7a5214f1acb
Python
4,113
119
import sys import cebra import os import tempfile import torch import pandas as pd import numpy as np import pickle as pkl import matplotlib import cebra.models import cebra.models import cebra.data from cebra.models.model import _OffsetModel, ConvolutionalModelMixin from torch import nn from scipy import stats from ce...
514740daa886e5e46ac3d32f52422bcb6699d73333426302a45a868b0865fe5d
Python
4,114
81
import os from nipype.interfaces.base import TraitedSpec, File, Directory, CommandLineInputSpec, File, TraitedSpec, CommandLine, Directory class DenoiseDegibbsInputSpec(CommandLineInputSpec): dwi_img = File(desc="Path to the DWI image", mandatory=True, argstr="%s", position=0) dwi_bvec = File(desc="Path to the...
6bb07bc47ffa07898fe4e62f46c8a09d51620fadcdc3b7f5c0be6458d0d16612
Python
4,115
139
import logging from pathlib import Path from typing import ClassVar, Iterable from argclz import argument, str_tuple_type from neuralib.atlas.typing import Channel, Source, HEMISPHERE_TYPE, Area, PLANE_TYPE from rscvp.atlas.dir import AbstractCCFDir from rscvp.util.io import get_io_config __all__ = ['HistOptions'] ...
679965f79651862bb01895963ef8cd7f71c4ae42e6e83a68c7c08c3c9d5ff763
Python
4,117
115
"""XGBoost evaluator.""" from tabnanny import verbose import xgboost as xgb import numpy as np #from base_evaluator import Evaluator """ XGboost Evalutor Wrapper class. """ class XGBoostEvaluator(): def __init__( self, model_type = "XGBRanker", load_weight = True, hpo_wrapper=Fal...
bb7a59b5b6b3cdcfa0836eb87903fa04da55ba82cd63b898bd6efb562ab051bb
Python
4,117
105
#!/usr/bin/env python3 """Generate the Python MEA-Stim figures into a MATLAB-mirroring output tree. Runs the ported stim pipeline (detect -> patterns -> clean -> analysis) for each test recording and writes every ported figure under <out-root>/2_NeuronalActivity/2A_IndividualNeuronalAnalysis/<Grp>/<recording>/ u...
5c33e132f3640c8d28cdd82060f257aa271b585e0985b649e6f6faba42714c48
Python
4,118
112
import matplotlib.pyplot as plt import numpy as np import nems from nems import Model from nems.layers import WeightChannels, FiniteImpulseResponse, RectifiedLinear, STRF from nems import visualization from nems.metrics import correlation from nems.models.LN import LN_plot_strf import tensorflow as tf # Check if eage...
9d126812b6a91705920d82e5edd151231746fd0ad8e57b4a219a13b4f0b897ed
Python
4,118
127
# Copyright (C) 2022 Intel Corporation # Copyright (C) CVAT.ai Corporation # # SPDX-License-Identifier: MIT from enum import StrEnum from django.conf import settings from cvat.apps.engine.permissions import JobPermission, TaskPermission from cvat.apps.iam.permissions import OpenPolicyAgentPermission class LambdaPe...
f3879ce11c527ffe221ef2628eb5bd48787f4e595403eceec403b463bce32c2c
Python
4,118
126
""" Example usage of CollapsibleGroupBox. This file demonstrates how to use the CollapsibleGroupBox widget to replace standard QGroupBox with collapsible sections. """ from PySide6.QtWidgets import ( QApplication, QMainWindow, QWidget, QVBoxLayout, QLabel, QCheckBox, QPushButton, QSpin...
0e30da066e2283bb0d66014f92d804b5da5a9492727c857431ba60f3e10d3c27
Python
4,119
111
import argparse import os import os.path as osp import time import numpy as np import torch import torch.nn.functional as F from sklearn.metrics import f1_score import pandas import json import ijson import torch_geometric.transforms as T from torch_geometric.nn import ChebConv, GCNConv # noqa from tqdm import tqdm p...
83ef000e85a651b603c737a6444b86f4e23478e8a8d6d2b32c551e0afa08432c
Python
4,119
95
import random import subprocess from typing import Dict, Any, Optional class TestsetClass: """ A class for handling test sets and calculating dispersion energies. """ def assign_random_values(self, N: int = 50, seed: int = 42) -> None: """ Creates a new dictionary with the same keys as...
b6088c5adefa3fc6a07c3b26dff0971a557d7f30f5a77be5506eda5f014ecd60
Python
4,120
122
# -*- coding: utf-8 -*- from loguru import logger def load_data(file_path): data = [] labels = set() count = 0 with open(file_path, 'r', encoding='utf-8') as f: for line in f: line = line.strip('\n') if '-DOCSTART-' in line: continue terms ...
c4a373ff99afedc8eb604f6ab4bc9f474bc22056abc28a1af9a646436a2d7691
Python
4,122
95
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import tempfile import numpy as np 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...
aefe5bcd50a92746cd491984e4ddbee860b4d0cf9f90c29a20fd921ea4bffe8e
Python
4,123
120
from collections import OrderedDict from torch import nn from torch.nn.init import xavier_normal import torch import torch.nn.init as init from attorch.regularizers import LaplaceL2 from torch.autograd import Variable from attorch.module import ModuleDict from staticnet import logger as log class Shifter: def _...
c40a57bc54f209124c2b5a6fc8206ff0fb184349b139bb74516e3f24aca85bd5
Python
4,126
115
from __future__ import absolute_import from collections import defaultdict import numpy as np from sklearn.metrics import average_precision_score from ..utils import to_numpy def _unique_sample(ids_dict, num): mask = np.zeros(num, dtype=np.bool) for _, indices in ids_dict.items(): i = np.random.choi...
f0bc839509a63a9f1e79e5148c1a856a0bfb0c3a6ee7d79c0b1d4a14715f1d96
Python
4,126
107
import torch from typing import Optional from transformers.models.dinov2.modeling_dinov2 import Dinov2Embeddings, Dinov2Model, Dinov2ForImageClassification, BaseModelOutputWithPooling, ImageClassifierOutput class ConditionedDinov2Embeddings(Dinov2Embeddings): def forward(self, pixel_values: torch.Tensor, conditi...
fb4f404aa86377689838d056e0a7f91ced4586c86c6892d8b0f30a50b50883d2
Python
4,126
120
import copy import time import torch import numpy as np import torch.nn as nn from layer import CLGNN_GCN from layer import CLGNN_GIN from sklearn.metrics import precision_recall_curve, roc_auc_score, roc_curve, average_precision_score, f1_score, auc def train_model(data_o, data_a, train_loader, test_loader, args): ...
36332d3b644deaf25ae4d3d9c1663f2536797aa25a135a9f58984120401020f0
Python
4,127
108
""" Common functions for creating enrich2 datasets (for GB1 and Bgl3) """ import os from os.path import join from subprocess import call import pandas as pd def create_e2_config_file(inp_fn, sel_fn, e2_output_dir, config_file_save_dir): """ creates an enrich2 config file for a 2 timepoint selection experiment ...
8c58488c4383ceb47f9abad4d9a677bdcde39e7380025d5fd84fab0e16ec7b9f
Python
4,127
50
import argparse def parser(): parser = argparse.ArgumentParser(description = 'CATS-Net on ImageNet1k concept abstraction task') parser.add_argument('--dataset', type = str, default = 'imagenet1k', choices = ['cifar10', 'cifar100', 'imagenet1k', 'imagenet100'], help = 'Which dataset to be used') parser.add_...
e2949892488114218db0e08e0645721580da2392199c7bcb737b93df3d5fae90
Python
4,128
90
import torch # define the celcomen class class celcomen(torch.nn.Module): # define initialization function def __init__(self, input_dim, output_dim, n_neighbors, seed=0): super(celcomen, self).__init__() # define the seed torch.manual_seed(seed) # set up the graph convolution ...
f5ed8393d387598c9cbc049d2bedd7f8efd461a51cabb47cdf88948e1df3e358
Python
4,128
135
try: import torch import torch.nn as nn import torch.nn.functional as F except ModuleNotFoundError: print('pytorch is not installed. Using without it.') import sys import numpy as np from pathlib import Path from scipy.interpolate import interp1d from scipy.io import loadmat import platform import warni...
2372703cf656263aead77cc4818bc4b7047e47007bd3e0d6c8544bd4b346f3c1
Python
4,129
130
import argparse import torch import torch.nn.functional as F from ogb.nodeproppred import PygNodePropPredDataset, Evaluator from logger import Logger class MLP(torch.nn.Module): def __init__(self, in_channels, hidden_channels, out_channels, num_layers, dropout): super(MLP, self).__init...
18b8143d60d9df4461953c1e2b854b273fb190a14a9270c12e877f0960485023
Python
4,130
109
from __future__ import annotations import re from typing import Final from loguru import logger from ._shape_color import migrate_shape_color def migrate_config(*, config_from_yaml: dict) -> None: migrate_shape_color(config=config_from_yaml) if "instance_label_auto_increment" in config_from_yaml: l...
ad6f4e324e074b7980f67c95b99b9b9ac13d2f9a0eb8c1007941baa6605b4ba2
Python
4,130
76
#!/usr/bin/env python # export_architecture.py import sys from pathlib import Path # ────────────────────────────────────────────────────────────────────────────── # 1. 将项目根目录加入 Python 模块搜索路径 # ────────────────────────────────────────────────────────────────────────────── ROOT = Path(__file__).parent.resolve() sys.pa...
af73ed3b363d3f88e6897494ac2ba4ce29f042fe968460216b437f6b0f0544dc
Python
4,131
94
#!/usr/bin/env python from __future__ import print_function import os import json import argparse import sys # Prints to stderr def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) ## Main parser = argparse.ArgumentParser(description="Get all samples below minimum reads (UMIs) or minimum detected...
bb59d1ff8164c7e496e3d563bc2b77cd46f280fdb67a71ae499d731be6d8b2e0
Python
4,131
125
import os import re from typing import List, Tuple, Any from glob import glob import numpy as np from tqdm import tqdm import torch.nn.functional as F from torchvision.transforms import functional as T from torch.utils.data import DataLoader import torch from plio import Section from pli_transforms.geometric import ...
13422b2448a9a08e43b9a485754e0a3234d469c529d3f32fedbfe63f08c18937
Python
4,132
128
# Copyright (C) 2021-2022 Intel Corporation # Copyright (C) CVAT.ai Corporation # # SPDX-License-Identifier: MIT from datetime import timedelta from allauth.account.adapter import get_adapter from django.conf import settings from django.contrib.sites.shortcuts import get_current_site from django.core.exceptions impor...
48a787997ace4db891a0d8495822cd4059dd1e78f739ac26a32fc5defde0a2ba
Python
4,132
81
from dtiplayground.dmri.common.tools.base import ExternalToolWrapper class DTIReg(ExternalToolWrapper): def __init__(self,binary_path= None, **kwargs): super().__init__(binary_path, **kwargs) def execute_with_args(self,args,**kwargs): self.setArguments(args) return self.execute(args) ...
bda26fb7bc8e9e1675a83aed9f3356e267e60f3bd9dd8f4bd3488fe1f6c891f5
Python
4,132
145
from typing import Callable, List, Any import torch import torch.nn as nn from torch import Tensor from torch.nn import functional as F import pli_cyto.utils.functions as f def adversarial_ce_loss(disc: nn.Module, image: Tensor, target: bool = True): valid = torch.full((len(image), 1), target, dtype=image.dtype...
2471d690e6805686121cb76c43500223631c8a1dc731b283fd4e0961790b5709
Python
4,133
130
# -*- coding: utf-8 -*- import logging import numpy as np from dipy.direction.peaks import peak_directions def find_order_from_nb_coeff(data): if isinstance(data, np.ndarray): shape = data.shape else: shape = data return int((-3 + np.sqrt(1 + 8 * shape[-1])) / 2) def get_sh_order_and_f...
fe6898f753a4dd38d662e9b8f87940098a82cc1fffbe4300823141378870e2f2
Python
4,133
128
import torch import numpy as np from skimage.measure import shannon_entropy def ssim_f(img1, img2, fused, measure): return .5 * (measure(img1, fused) + measure(img2, fused)) def mi_f(img1, img2, fused): return MI(img1, fused) + MI(img2, fused) def _to_uint8(img): if not img.dtype == np.uint8: ...
349ba03faed84c4092b2c641e10aeed8c8e0d2cf5bf74620e46bcd30e4899448
Python
4,135
117
"""XGBoost evaluator.""" from tabnanny import verbose import xgboost as xgb import numpy as np #from base_evaluator import Evaluator """ XGboost Evalutor Wrapper class. """ class XGBoostEvaluator(): def __init__( self, model_type = "XGBRanker", load_weight = True, hpo_wrapper=Fal...
8a5d57741be400338ef3a350b79b754158b4d0bb19501c31f9d4775ec3244243
Python
4,135
110
import os import numpy as np import pandas as pd import time as tm from sklearn.discriminant_analysis import LinearDiscriminantAnalysis import rpy2.robjects as robjects def run_LDA_rejection(DataPath, LabelsPath, CV_RDataPath, OutputDir, GeneOrderPath = "", NumGenes = 0, Threshold = 0.7): ''' run b...
bba8fee7e887040483099efbe9dc9f088d4df30baf20c8de7dff24b61897dd0e
Python
4,137
116
import copy from typing import Callable, Tuple import torch from torch import Tensor from torch.nn import Module, Parameter from torch_geometric.nn.inits import reset, uniform EPS = 1e-15 class DeepGraphInfomax(torch.nn.Module): r"""The Deep Graph Infomax model from the `"Deep Graph Infomax" <https://arxiv...
28411ef254f6d6072504aa084d564dd9555cbd529e33016b4d0ec189fc2b1a5d
Python
4,138
104
# Copyright 2024 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
71ca2852c39aab9ac3a90d2120009b105f43adee0cbab1486fd2b3cf543b1b6b
Python
4,138
90
import gzip import re import argparse import subprocess import pandas as pd def read_gzip_file(file_path, header="infer"): with gzip.open(file_path, 'rt') as f: return pd.read_csv(f, sep='\t', header=header) def write_gzip_file(df, file_path): with gzip.open(file_path, 'wt') as f: df.to_csv(f,...