sha256
stringlengths
64
64
language
stringclasses
27 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
b3b376c10f4cf4029a1a58386d7432a276fe6919020f4114ae46a1410da2e761
Python
6,230
177
from pathlib import Path from typing import List, Tuple, Union from natsort import natsorted import pandas as pd from napari.utils.notifications import show_info def construct_path(input_path: Path, *sub_paths: str) -> Path: """ Construct a path by joining the base path with sub-paths. Parameters: ...
2cc86d503261bf11ab4058b784b20750676240ce09287a6df1cbd930692e0515
Python
6,231
158
import requests import pathlib import numpy as np from nems.tools.arrays import apply_to_dict #remote_uri = 'https://s3-us-west-2.amazonaws.com/nemspublic/' remote_uri = 'https://nemspublic.s3.us-west-2.amazonaws.com' # E.g. "/path/to/NEMS/nems/tools/demo_data/saved_data/" datapath = pathlib.Path(__file__).parent /...
60b91efe5ac2253103ac10b734a9d019f1f142a5b95f9de00b8e3b9179984c82
Python
6,231
183
import numpy as np import obspy import pytest import torch import seisbench.models as sbm import seisbench.util as sbu @pytest.mark.parametrize("variant", ["s", "m", "l"]) def test_seist_forward_shape(variant): model = sbm.SeisT(variant=variant, in_samples=1200) x = torch.randn(2, 3, model.in_samples) mo...
8b68515ffe294503e5116892fe151a793b152d1b38f4bf643cfa8a9c06585102
Python
6,231
178
import numpy as np from matplotlib import pyplot as plt from matplotlib.colors import Normalize from typing import Literal from argclz import AbstractParser, argument from argclz.dispatch import Dispatch, dispatch from neuralib.facemap import FaceMapResult from neuralib.facemap.plot import plot_cmap_time_series from n...
a6afe53ad07a0e2859c9f6e3a487283636c3f67a068d45b6ec2ba18672c459cd
Python
6,231
83
"""A module that contains :py:class:`~corelay.pipeline.base.Pipeline` implementations for spectral embeddings, :py:class:`~corelay.pipeline.spectral.SpectralEmbedding`, and spectral clustering, :py:class:`~corelay.pipeline.spectral.SpectralClustering`. These are specific to `Spectral Relevance Analysis (SprAy) <https:/...
ba4dde449275afae5c46b8267bc4fccc0612e7e12b8f522338572156f0b9399b
Python
6,232
129
import numpy as np from scipy.spatial import KDTree from impyute.ops import matrix from impyute.ops import wrapper from impyute.ops import inverse_distance_weighting as idw from . import mean # pylint: disable=too-many-arguments @wrapper.wrappers @wrapper.checks def fast_knn(data, k=3, eps=0, p=2, distance_upper_boun...
e8030733c8fa08b611b9f3799766764b0375e4acb7d0eb6770c600077b28c5ca
Python
6,233
155
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn from torch.nn import functional as F from typing import Tuple from ..modeling import ...
765777eca76d1716823eadc60db24bee5f3f9c9621c3d1c9d692508227af3ac5
Python
6,234
167
import os import pytest import torch import numpy as np from fireants.registration.distributed import parallel_state from fireants.registration.distributed.parallel_state import ( initialize_parallel_state, cleanup_parallel_state, all_reduce_across_dp_ranks, all_reduce_across_gp_ranks, get_parallel_...
785f5bfb6c1ba44710124f9d77e3c9a8040950fbd045a528781216fab15add29
Python
6,235
186
"""Analyze the univariate and multivariate NSD-synthetic fMRI responses. Parameters ---------- subjects : list List of the used NSD subjects. rois : list List with all used NSD ROIs. zscore : int Whether to z-score [1] or not [0] the fMRI responses of each vertex across the trials of each session. ncsnr_threshold ...
56746c7cd49800af74bf63148e8a2d0c5ae28f1c39283428ce795a5a2143e401
Python
6,238
121
import pytest import teneto import numpy as np from comet import connectivity, utils import pydfc from pydfc.data_loader import TIME_SERIES from pydfc.dfc_methods import WINDOWLESS np.random.seed(0) # Fixture to load data once for all tests @pytest.fixture(scope="module") def ts(): ts = utils.load_example() ...
8f7f243a78a30beaa45521d111a2146b33aad710fd20ef53a6d2548813b5a6cf
Python
6,238
196
# -*- coding: utf-8 -*- import logging import numpy as np from tempfile import mkstemp from dipy.data import get_sphere from fury import actor, window from scilpy.viz.color import generate_n_colors from scilpy.viz.backends.fury import snapshot_scenes from scilpy.viz.screenshot import compose_image def plot_each_sh...
b0b9bd34fafc47137d29d8942700df0e7792a2073970bec3b0c06aca6a83ec51
Python
6,238
146
"""YOLOv5 PyTorch Hub models https://pytorch.org/hub/ultralytics_yolov5/ Usage: import torch model = torch.hub.load('ultralytics/yolov5', 'yolov5s') """ from pathlib import Path import torch from models.yolo import Model, attempt_load from utils.general import check_requirements, set_logging from utils.goog...
665eabe6e46d690905d7240b7b91c858b151175f251841c9c6fcd045ee85c342
Python
6,239
164
import torch import math import argparse import os import torch.nn.functional as F from glob import glob from torch.utils.data import Dataset, DataLoader from torch.optim import AdamW from tqdm import tqdm from IEFFEUM import model class SimpleBatchDataset(Dataset): def __init__(self, data_dir): self.file...
b8d951032258580fba6f1f8a7c1112728c06fe1d44f60e649788da4e30e3f460
Python
6,240
175
from qtpy.QtWidgets import ( QApplication, QGroupBox, QHBoxLayout, QVBoxLayout, QLabel, QPushButton, QSpinBox, QWidget, ) from qtpy.QtCore import QThread, Signal, Qt import napari from typing import TYPE_CHECKING if TYPE_CHECKING: import napari from ._input_data_widget import InputDataGro...
be39b95770769b7cb08007d1cb8ed539ab808bb32b725ed5e7a589b06b55b199
Python
6,241
204
# -*- coding: utf-8 -*- from copy import deepcopy from glob import glob import os import nibabel as nib import numpy as np from numpy.testing import assert_equal import pytest from scilpy.image.labels import (combine_labels, dilate_labels, get_data_as_labels, get_labels_from_mask, ...
c87d2050c007bb36c919e43554d36d6bcd7762e2ac288632843cd03d4b693dc1
Python
6,242
159
import torch import os import argparse import datetime import numpy as np from brainCT.networks.gen_model import GUNet from monai.transforms import ( Compose, ToTensord, RandAffined, ScaleIntensityd, RandGaussianSmoothd ) from brainCT.train_utils.data_loader import MultiModalDataset from brainCT....
0a53ed602814a9181cf8fe5b707a6a18451f0369fe4249389ed15e2400423865
Python
6,244
169
#!/usr/bin/env python """ The HAL testing modules. The TestingRandomPause module Hazen 04/17 """ import random import time import storm_control.sc_library.tcpClient as tcpClient import storm_control.hal4000.halLib.halMessage as halMessage import storm_control.hal4000.halLib.halModule as halModule import storm_con...
26bf4dd5fd5986d12928997270a44a201f802f6dea1bb2d4c2fcdba06fc7814a
Python
6,244
163
""" plot mouse brains using brainglobe """ import numpy as np import pandas as pd import brainglobe_heatmap as bgh from ast import literal_eval from palettable.colorbrewer.sequential import PuBuGn_9 from matplotlib.colors import LinearSegmentedColormap path = "/home/jhansen/projects/proj_synaptome/" # min and max of...
9b3bd48398a17c1d08028a764ccf9fb0e8c8853c03a4062e7531b303e22530ab
Python
6,244
190
#!/usr/bin/env python3 # baseline_tables.py # 需要的第三方包:pandas, numpy, matplotlib, openpyxl (写 Excel 用) import pandas as pd import numpy as np import matplotlib.pyplot as plt from pathlib import Path ############################ # 1. 读取数据 ############################ DATA_FILE = "Data_M1D5.csv" # ← 这里改成你的完整数据文件名...
56dc731f1219a2cba2ff5af9daef3a3f244d3d0a45288b1504895142247b5b68
Python
6,245
114
from pathlib import Path import pytest from pytest import approx from brainscore_core.supported_data_standards.brainio.assemblies import BehavioralAssembly from brainscore_vision import load_benchmark from brainscore_vision.benchmark_helpers import PrecomputedFeatures from brainscore_core.supported_data_standards.brain...
5de31fa90f0521754cae33b9f167427cd34c127f9bc1f4e0017816d2c16419a6
Python
6,246
159
import os import os.path as osp import numpy as np import torch from torch.utils.data import Dataset import cv2 import matplotlib.pyplot as plt import albumentations as albu from .transform import * import matplotlib.patches as mpatches from PIL import Image import random CLASSES = ('ImSurf', 'Building', 'LowVeg', 'T...
010e4cab5f44c0d437f31148f88fd6c63afc5be63470c4bc6cd6fa14bd8cbdc1
Python
6,247
176
''' Peak detection ------------------- Functions for finding characterising cells within ground truth retinae. These functions are designed to detect high contrast peaks that all have a similar amplitude, such as output by the reaction-diffusion model. It has not been tested for use on synthetic or real AOSLO images...
925ca3b21229e43839241cf28c2ba8a0d767012737de0342c2d08da8d3f765a9
Python
6,248
127
from distances.distances_between_graphs import * import pygsp import matplotlib.pyplot as plt import networkx as nx import numpy as np import pandas as pd from utils.graph_tools import * def compute_evolution_heat_diff(node1, mode, list_heat_df1, list_heat_df2, type_distance="auc", no...
2a6ae8a8068eaf29b5299b1421defbc4a306b0619739b5d9db1afa62b61b7575
Python
6,251
120
import os from nipype import Node, Workflow from nipype.interfaces.utility import IdentityInterface from cvdproc.pipelines.common.register import SynthmorphNonlinear from ...bids_data.rename_bids_file import rename_bids_file # Template definitions: space -> {resolution: (filename, register_between_stripped)} # For M...
3a3d913fb9523f9f026b5b063260ac292befb9464f6a138e5e0b8d108492d2a3
Python
6,252
193
# Copyright 2017 Calico 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, ...
f3cc82318ea33798650fe3a9219140c98484fd239a5f0175667a2b17eb1a205b
Python
6,254
163
import mayavi import abagen import neuromaps import fcn_megfmri import numpy as np import pandas as pd import seaborn as sns import sklearn.metrics import scipy.stats as stats import matplotlib.pyplot as plt from statsmodels.stats import multitest from neuromaps.parcellate import Parcellater from sklearn.preprocessing ...
b84d0e5ea89ae113c41304005401f13bfd007b3da51d410e86b865d5072471ab
Python
6,255
152
import math import torch from torch import nn from torch.nn import functional as F from transformers import BeitModel, BeitConfig from torch.nn import init class eca_layer(nn.Module): def __init__(self, channel, k_size=3): super(eca_layer, self).__init__() self.avg_pool = nn.AdaptiveAvgPool2d(1) ...
3e214d6ac8a6d5dfdf9fb08b744660311c9517ab63f7d17e98ef5a573e68f22f
Python
6,258
185
""" A set of helper functions for downloading and preprocessing hippocampal data. @author: Gautam Agarwal @author: Ben Toker """ from scipy.signal import decimate import numpy as np import math import os from scipy import io from scipy.stats import mode import h5py def get_behav(mat_file, fs=25): """ Organiz...
5b0943f0f068320f2902e3ba103289737389e6103de4bc24afe3baa6e486268f
Python
6,258
174
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by ...
9d5e1727a705c1f27d08d2c6a434084bd59a256d8bac9650783d1875df6326fd
Python
6,258
235
#!/usr/bin/env python3 import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy as np from optparse import OptionParser import sys ############################################################################### def windowToKey(a): k = a[0] + ':' + str(a[1]) + '-' + str(a[2]) retu...
a5a224ecb34adfa529b198ec34ec84dd7635b9d2fadea2faab3215897ccd24e9
Python
6,258
157
# -*- coding: utf-8 -*- """ Created on Sat Apr 6 03:27:25 2024 @author: aka2333 """ #%% import numpy as np # turn off warning messages import warnings warnings.simplefilter(action='ignore', category=FutureWarning) # system paths import torch import torch.nn as nn import f_simulation import f_eval...
b713df0069fa33c55c9136d90eaf8537720fceadc3dc38860b7f8c0efa87ede9
Python
6,260
191
from typing import Generator, Tuple, Any from zigzag.classes.stages.Stage import Stage from zigzag.classes.cost_model.cost_model import CostModelEvaluation import logging import os logger = logging.getLogger(__name__) class RemoveExtraInfoStage(Stage): """ Strips extra info for subcallables to save memory ...
190c910e86f93a8002c394ddc7b5d9135f17995fd6dec2d9870b45b4a0607d47
Python
6,264
139
"""This script shows how to call the training function. It re-uses the last example (6-SR_synthesis_synthetic), where we use T1 and T2 synthetic as input channels (at HR but simulating data acquired at LR) and synthetic HR T1 scans as regression target. If you use this code, please the SynthSR paper in: https://githu...
943fd277f8296367c438d4a3e8313a82af488f536d9eb2abffbdba74c8237e72
Python
6,265
167
from __future__ import annotations from collections.abc import Callable from PySide6 import QtCore from PySide6 import QtGui from PySide6 import QtWidgets from .._ai_models import AI_TEXT_MODEL_OPTIONS from ._info_button import InfoButton from ._model_picker import ModelPicker class AiTextToAnnotationWidget(QtWidg...
e8cd781961bac04e6c2419c3ff9d70291c24785b1a3f0348c1032bee08e7d30e
Python
6,265
165
#!/usr/bin/env python3 """Gene / CpG feature-selection (public repo version). This script keeps a runnable example for GitHub using the bundled toy dataset, while preserving the key paper-style step of selecting features by effect size: selected_* = log2fc[abs(log2fc) >= 0.25] Behavior - Loads a CSV with a binar...
640b50441ce08f74de75b9f0474e046aa67d03f2e09031b632b477a4f8a7d9ac
Python
6,266
196
from unittest.mock import patch import ants import numpy as np from pyment.preprocessing import rescale_intensity, skullstrip_with_antspynet SHAPE = (10, 12, 14) RAMP_SHAPE = (7, 11, 13) def make_ants_image( shape: tuple = SHAPE, spacing: tuple = (1.0, 1.0, 1.0), value: float = 1.0, ) -> ants.ANTsImage...
eed98a6643eeaad01728e7cd6ef6108f29b3967bb1a47614d7009228b05a6349
Python
6,266
175
#!/usr/bin/env python """ HAL module for controlling a Zaber XY stage. Based on the Marzhauser class. Hazen 04/17 Jeff 04/21 """ from PyQt5 import QtCore import storm_control.hal4000.halLib.halMessage as halMessage import storm_control.sc_hardware.baseClasses.stageModule as stageModule import storm_control.sc_hard...
c0b377d84a9002605de47c643383a608cedcaa5fdcf8ea540a8d3cc427783448
Python
6,268
141
import numpy as np import OptimalBattery.util as ut import os import pandas as pd import OptimalBattery.evaluate as ev import Functional_Fusion.atlas_map as am from Functional_Fusion.dataset import DataSetMDTB import nibabel as nb import OptimalBattery.estimate as es import OptimalBattery.construct as ct import Optimal...
170dc269383ae65dbd537ba639ff915dbc9d2bddbcc7909dce166ade05508cb1
Python
6,272
163
import multiprocessing_on_dill as multiprocessing # from mpi4py import MPI import mpi4py # mpiexec -n 3 -f machinefile_mp python3 main_mpi.py import pickle from sympy.ntheory import factorint from copy import deepcopy import logging from zigzag.classes.hardware.architecture.accelerator import Accelerator from zigzag...
9f9abe424f05a15a3da94d038854f4f66b01333a820f7997d0b7e3d53b3e3e26
Python
6,273
229
import numpy as np import datetime import pandas as pd try: from visdom import Visdom except: print("could not find visdom package. try 'pip install visdom'. continue without...") Visdom=None pass class Printer(): def __init__(self, batchsize = None, N = None): self.batchsize = batchsize ...
f95d195b339b8df10453814089d682d4a9690ac7e0df9086ddab5d8296ec2114
Python
6,273
146
""" This module contains functions to get task variables from behavior data. """ from sklearn.preprocessing import LabelEncoder, MinMaxScaler import numpy as np from pyTdr.tdrUpdateBehavior import add_block_length, add_switch_block_length from utils.get_session_info import get_unit_spike_dirs, get_behavior_df def ad...
8889e0dc1a92bb4eb38cbefae8206f76b7f358321f40123b3e25dd8c3e9b83cf
Python
6,274
152
# wfield - tools to analyse widefield data - NCAAS related # Copyright (C) 2020 Joao Couto - jpcouto@gmail.com # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the Licens...
dafb8fe45901c408bf63dd7e90182a7c2bdc3cba223fe3d5d504caa0778fc9ec
Python
6,274
142
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license """Functions for estimating the best YOLO batch size to use a fraction of the available GPU memory in PyTorch.""" from __future__ import annotations from copy import deepcopy import numpy as np import torch from ultralytics.utils import DEFAULT_CFG...
c2e9ed58a9c76ccf3815af575f7c177a01ccb1f0d9d563fb2815486533b66620
Python
6,275
165
#! /usr/bin/env python3 # -*- coding: utf-8 -*- """ Estimates the per-voxel volumetric density of a set of fibertubes. In other words, how much space is occupied by fibertubes and how much is emptiness. 1. Segments voxels that contain at least a single fibertube. 2. Valid voxels are finely sampled and we count the num...
24e58679f8619ebab38de5a19e131937154ef289077ea9244a29eee6e440eba2
Python
6,276
186
import argparse import mmcv import numpy as np import warnings import torch import os from mmcv import Config, DictAction, mkdir_or_exist from mmcv.runner import (get_dist_info, init_dist, load_checkpoint, wrap_fp16_model) from os import path as osp from pathlib import Path from depth.dataset...
1b08cc125845cdee808eb9eff4989d71e6209669a1b8f9a59a3a2e9693fdb8d5
Python
6,278
211
"""Shared configuration helpers for CLI and UI.""" from __future__ import annotations from typing import Any, Dict, Optional from chemgraph.models.endpoints import ( normalize_openai_base_url as _normalize_openai_base_url, ) from chemgraph.models.endpoints.configuration import ( has_config_section, resol...
8f3a069bbec7bcd48e8e010698b311a974861d77083e8eec5129a43006214535
Python
6,278
261
# Copyright (C) 2018-2024 Intel Corporation # # SPDX-License-Identifier: MIT from django.contrib import admin from .models import ( AnnotationGuide, Asset, AttributeSpec, CloudStorage, Data, Job, Label, Project, Segment, Storage, Task, ) class JobInline(admin.TabularInlin...
d6cdf4d43f107731e97f2ef812a4c17104168a0a2311b5508be7c93fd5544c31
Python
6,278
206
#!/usr/bin/env python # coding: utf-8 import sys import os import argparse import pandas as pd import numpy as np import yaml import logging import scipy.io import scipy.stats from sklearn.cluster import KMeans from dna3bit import DNA3Bit import warnings logger = logging.getLogger("demux_kmeans") logging.basicConfi...
0c60cb0710effe32423a5f997cdf2b8269b2198918a3a41bfb8dd013a52c6f19
Python
6,279
201
import os import anndata import pandas as pd import scanpy as sc import squidpy as sq import numpy as np from nest.utility import spatial_smoothing SQUIDPY_DATASETS = ["seqfish", "slideseq", "merfish"] VISIUM_DATASETS = [ "V1_Breast_Cancer_Block_A_Section_1", "V1_Mouse_Brain_Sagittal_Anterior", "V1_Mous...
a6545efddf955a6f83c048adc7ce8c9026233ccdf09a05c88ba9188dfa80bc02
Python
6,281
179
""" PyTorch FX Based Feature Extraction Helpers Using https://pytorch.org/vision/stable/feature_extraction.html """ from typing import Callable, Dict, List, Optional, Union, Tuple, Type import torch from torch import nn from ._features import _get_feature_info, _get_return_layers try: # NOTE we wrap torchvision ...
d79fba32f28b05e297310e4a540eecabe68076bef58611e9a4d7abde60689469
Python
6,281
164
""" Access to YASA tutorial data The YASA sample dataset is stored on Zenodo and can be accessed using the Pooch library. """ import time from pathlib import Path import pooch __all__ = [ "fetch_sample", ] REGISTRY = { "sample": { "v1": { "base_url": "https://zenodo.org/records/1456428...
6700849d75f95dafe168a306902783139f9a613d2762edba7357e16b800c80ef
Python
6,283
117
from brainvoice.configuration.configuration import Configuration from brainvoice.configuration.utils import extract_modify_dict from brainvoice.configuration.configuration_linker import ConfigurationLinker from brainvoice.configuration.static_configuration_parser import StaticConfigurationParser import argparse ...
9dc338dbef0221615b6931732fe3b657af7e4ad32a6284fc1541261b01eca489
Python
6,283
163
""" Metrics to assess performance of propensity score models. Function named as ``*_error`` return a scalar value to minimize: the lower, the better. Metrics' interface doesn't strictly follow skleran's metrics interface. Names are kept as `y_true` and `y_pred` even though these regard the treatment assignment `a` (`a...
884034eb563e9587fa37c4ed0755478ab95c7390bc58832e5728415e2fa691ed
Python
6,285
179
from __future__ import division import numpy.ma as ma import numpy as np import scipy as s import scipy.special as special # Import manually defined functions from .variational_nodes import Gamma_Unobserved_Variational_Node class AlphaW_Node(Gamma_Unobserved_Variational_Node): def __init__(self, dim, pa, pb, qa,...
9a7017df8a3b463d28e3a87ac27f2f3ca4c6f3cde5a3c7700ef46132f8106bac
Python
6,287
192
import importlib import subprocess import sys import os from tkinter import Tk, Label, Button, StringVar, ttk, Scale, HORIZONTAL, messagebox # Auto-install required packages required = ["tifffile", "matplotlib"] for package in required: try: importlib.import_module(package) except Import...
a2171cb3149ee58bfba9f0c84b0437c9d675cb7651cc31ea3fc1bc81e1c4986a
Python
6,289
159
""" Classes and functions for fitting ivim model """ import numpy as np from scipy.optimize import curve_fit from dipy.reconst.base import ReconstModel from dipy.reconst.multi_voxel import multi_voxel_fit from dipy.utils.optpkg import optional_package class IvimModelSegmented2Step(ReconstModel): def ...
32e20a60035540626dc55cf832eb09b8a1b5ddab2e27906707b2b2640c983aa5
Python
6,292
156
import glob, os, struct import numpy as np import json from pathlib import Path #calculates the error based on distance of the triangles. The triangle distance is the sum of distances between #each point of the triangle and its nearest point of the other triangle. #deltaY and deltaZ is the value for how far the triang...
3000512010d34fa69448566685ff22718f5fd64a0496959d088a15a231d74d95
Python
6,293
189
import math import os import numpy as np import pandas as pd import statsmodels.stats.multitest as multi from scipy.stats import gamma from tqdm.auto import tqdm from output_paths import artifact_dir, artifact_path def _resolve_distribution_file(path): if path is None: return artifact_path("distributions...
fbb6a3b794240e457d12e337672873b3b2a61a4833e7ce21deb74227081316a4
Python
6,294
146
import os import os.path as op import sys import numpy as np import pandas as pd import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.patches as patches from matplotlib.gridspec import GridSpec import seaborn as sns sys.path.append('/imaging/hauk/rl05/fake_diamond/scripts/preprocessing') sys.path...
50b1c15833eec74f318285ffc858e8334c84194e5c6738e905380a75f2c261f4
Python
6,296
185
"""Spiking linear layers, including E-I variants.""" import numpy as np import torch from torch import nn __all__ = [ 'SpikingLinear', 'SpikingEiLinear' ] class SpikingLinear(nn.Module): """Linear layer wrapper.""" def __init__(self, in_features: int, out_features: int, bias: bool = True): """I...
7e9f9fd9e716ad9406c852ddcafdb81a050620d6cefc1c17c770abe194e5304d
Python
6,296
207
#Lucas Sancéré - import os import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import yaml from attrdictionary import AttrDict as attributedict ############################################################# ## Load configs parameter ############################################...
dd9cd4cbd1dc4833b5f58de3706cdf347127863540ec6d65e1ffd507b886f00e
Python
6,296
205
import os import sys import unittest try: sys.path.insert(0, os.path.dirname(os.path.dirname(__file__))) except Exception: sys.path.insert(0, os.path.dirname(os.path.abspath("."))) from bx.intervals.intersection import ( Interval, IntervalNode, IntervalTree, ) class NeighborTestCase(unittest.Tes...
d941a82d3f8dfd9edb6672a40e33ea1eb4a4901a4798f2cf74c994f31de7534d
Python
6,298
205
"""Pure-Python cheminformatics helpers (no LangChain / MCP decorators). Provides a single implementation for PubChem lookups and RDKit SMILES-to-3D conversion, used by both the LangChain ``@tool`` wrappers in :mod:`cheminformatics_tools` and the MCP wrappers in :mod:`chemgraph.mcp.mcp_tools`. """ from __future__ impo...
2107cc75e96650ec7e38d476473fd2733b131aeb0ce73dbd61f728d9467879ae
Python
6,299
128
import importlib import logging from collections import defaultdict import functools import re import torch from torch.nn import Module from brainscore_core.supported_data_standards.brainio.assemblies import merge_data_arrays, NeuroidAssembly, walk_coords from brainscore_core.supported_data_standards.brainio.s3 import ...
0619c880327b1cc8473e768193cd96aaf1ebf1143ec7b3c3b5d3157d75b8693a
Python
6,304
153
from PIL import Image import numpy as np import os from skimage.filters import threshold_otsu, threshold_local from myfunctions import augStack def import_fun(joinpath,sigma_chosen): ## this creates one aray of 3 columns and fills it will all the images ## all_image_array=np.zeros((256,256))[None, :, :...
063adac4717c99f9c69de61a147e0e968c6414cb4c0a9aec65352bb3e5065d2c
Python
6,306
148
import argparse import joblib from collections import defaultdict import numpy as np import pandas as pd from sklearn.ensemble import RandomForestClassifier from xgboost_ensemble_classifier import XGBoostEnsembleClassifier from xgboost import XGBClassifier from sklearn.neural_network import MLPClassifier from sklearn...
98c9b6f8633bfc318b776889f98e08a3aaac99c8e6e9d9fbfe1aa4df20bb57db
Python
6,306
205
import math import numpy as np from numba import cuda, njit, prange from scipy.sparse import csr_matrix from .util import fp_type import subprocess import warnings from numba.core.errors import NumbaPerformanceWarning warnings.filterwarnings("ignore", category=NumbaPerformanceWarning) def is_cuda_available(): """...
5e37fee8422bafffbfe67f8c11958bcd30ada48bbfd64f7821a46c3a13cf6ce7
Python
6,307
135
import os import torch from torch.utils.data import Dataset import numpy as np import pandas as pd from datetime import datetime from pathlib import Path # import random # from matplotlib import pyplot as plt class RotorBladeDatasetClean(Dataset): """ This class creates a dataset instance from a csv-file or DataF...
93ddfdb302f4611af38413ba58c5e4075daf860ba9e7d6e8a91a4e0fa440b04a
Python
6,308
166
from benchmark import CentroidDistScore, calculate_ncc from deepreg.predict import unwrapped_predict from tqdm import tqdm from network_utils import write_to_json import deepreg.model.layer as layer import h5py import numpy as np import tensorflow as tf import yaml def set_GPU(device): gpus = tf.config.list_physi...
9e21cf286f2d3f47018f3c7a1c333483d99c607fc43c3ffbedb5fb3aaddaf259
Python
6,308
151
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from typing import Any from ultralytics.solutions.solutions import BaseSolution, SolutionAnnotator, SolutionResults from ultralytics.utils import LOGGER from ultralytics.utils.plotting import colors class SecurityAlarm(BaseSolution): """A class...
a6d0abd4ef732650afaa39f73d298738e35182fc8a7f830ca5cbb146e12b6c19
Python
6,308
157
import qt class ComboDelegate(qt.QItemDelegate): def __init__(self, parent): qt.QItemDelegate.__init__(self, parent) def createEditor(self, parent, option, index): pass def setEditorData(self, editor, index): editor.blockSignals(True) editor.setCurrentText(index.model().data(index)) editor....
9ad49cd7d8977ed5cf7819753ab008dd7d35737f2e9226965f09bd6b163ebd8e
Python
6,309
167
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 as pd import json import torch_geometric.transforms as T from tqdm import tqdm import random import spacy from torch_geometric.data import Data i...
13daf33b366332f85d171389543f719d2104b1e1af242956dda0dc0cd848a983
Python
6,310
154
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Compute the statistics (mean, std) of scalar maps, which can represent diffusion metrics, in ROIs. Prints the results. The ROIs can either be binary masks, or weighting masks. If the ROIs are weighting masks, they should either contain floats between 0 and 1 or shoul...
facb718031cc5fd92c2fa9a6feeb03363321f72fd4fc1a4dc3291e3b659762bd
Python
6,310
205
# Copyright 2024 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...
1010a24cbc27c7c80fdc6e593ab10d74a19a98f34f540f618d41318b4ec5efcf
Python
6,314
195
# This file is part of connectome-manipulator. # # SPDX-License-Identifier: Apache-2.0 # Copyright (c) 2024 Blue Brain Project/EPFL """Customized profling""" import resource import time import os import logging from contextlib import ContextDecorator import pandas as pd logger_profiling = logging.getLogger(__name__...
722580d16cbdfac329547b31acbf7a6d137665a17e0fa38ca6dc889db565be65
Python
6,314
210
# Author: Lucas Berg # # Program that calculates the APD of every cell in the grid by passing a certain percentage. # e.g: APD_90 --> percentage = 90 # APD_80 --> percentage = 80 # APD_70 --> percentage = 70 # # This program also works with multiples AP's ! import sys import subprocess import time imp...
fffe81718bd87137aaaaa5b7f67f8a53b8ceb708ed40476e07bf4fadf74c4ce5
Python
6,314
187
import time import serial import numpy as np import logging import yaml import pyvisa as visa import pyvisascope from grid import get_grid import os if not os.path.exists("data"): os.makedirs("data") if os.path.exists('experiment.log'): os.remove('experiment.log') visa.log_to_screen('INFO')...
149e46fad79a322f165dde6236760d238043214e7ce590943a1e327a6ea0f6ba
Python
6,315
126
import functools import torch from brainscore_vision.model_helpers.activations.pytorch import PytorchWrapper from brainscore_vision.model_helpers.activations.pytorch import load_preprocess_images from PIL import Image import numpy as np import timm from timm.data import resolve_data_config from timm.data.transforms_fa...
43d429bb6990255212e02b7c98e34c843d3cbaa58dbf0ed8351ea7f3aa79bd3f
Python
6,315
186
import torch import torch.nn as nn from typing import Any from ._builder import build_model_with_cfg from .registry import register_model __all__ = ["AlexNet", "alexnet"] class AlexNet(nn.Module): def __init__(self, num_classes=1000, dropout=0.5, **kwargs) -> None: super().__init__() self.num_cl...
31a0a630c736a8fd2578b18810c81ecadd606023bbb3ee83de76655d2ea63f19
Python
6,316
194
""" This script is used to make plot for the cross-validation results of the actor and observer trial's projectin on the switch evidence direction. """ import sys import os sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import os import numpy as np import json import matplotlib as mp...
e373a27d307fd98f191505c4cc751f20b5b37c56c8914201b7ec13ff50734725
Python
6,317
269
CompScalerMeans = [ 21.194441759304013, 58.20212663122281, 37.0076848719188, 36.52738520455582, 13.350626389725019, 29.468922184630255, 28.71735137747704, 78.8868535524408, 50.16950217496375, 59.56764743604155, 19.020429484306277, 61.335572740454325, 47.14515893344343...
404b9098354ff3a7969a1942ee968393c48caae6cdb1a0c19908af962aa591fc
Python
6,319
170
""" Tests for the logging functionality. """ import logging import tempfile from pathlib import Path from io import StringIO import pytest from stack_corr.logger import setup_logger, get_logger, set_log_level, ColoredFormatter class TestLogger: """Test the logging functionality.""" def test_get_logger(sel...
ebf42db5af7d6cd51c1b1066d71e5206632f156bef6b7a17a8dc0a32b1803d24
Python
6,319
137
import numpy as np from GEASO.utils.utils import voxel_data from GEASO.utils.utils import normalize_coords from GEASO.utils.utils import cal_distance def _to_numpy_matrix(x): if hasattr(x, "A"): return x.A if hasattr(x, "toarray"): return x.toarray() return np.asarray(x) def inlier_from_...
473c472a50408ad0912016e3d82a3b307e87085c21973543dad8cd802744f437
Python
6,320
167
import warnings from typing import List, Tuple, Union import torch from torch import Tensor, nn from torch.nn import Parameter import torch_geometric.typing from torch_geometric.nn.conv import MessagePassing from torch_geometric.nn.dense.linear import Linear from torch_geometric.nn.inits import uniform, zeros from to...
79b6dfbe2c0779ead1e90b833edc5fd0baef91858cd544ba5b417d622cd8cf40
Python
6,321
218
# Generate a specific input image for SHAP explanations from "Test dataset" import glob from PIL import Image import torch import numpy as np import sys import pickle import torch.nn as nn import torch.optim as optim import torchvision import torchvision.models as models import torch.nn.functional as F import torchvis...
83947e3dd0bdc777b246a9e39282e7ec33ce034a816490414ce27d70eb482e4d
Python
6,321
222
import os import pytest from deepreg.vis import main, string_to_list def test_string_to_list(): string = "abc, 123, def, 456" got = string_to_list(string) expected = ["abc", "123", "def", "456"] assert got == expected class TestMain: img_paths = "./data/test/nifti/unit_test/moving_image.nii.gz...
b5506a34166dcdad0a7e80802f9d72b1d26435711be52f8bdf3ed909c054a047
Python
6,322
179
# 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, ...
f54620f6f8d6f69ae940de92849df5e50d9dd6b0e824966173ad7ebe2de2ea19
Python
6,322
149
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Performs a statistical comparison between connectivity matrices for populations g1 and g2, using a t-test. The inputs are any connectivity matrix, that can be obtained with scil_connectivity_compute_matrices, used separately on the two populations. All input matrices ...
03206c024baea8f4b565fb9528d6f83acd1bada7ca33fc9c5c56a8789460cfc0
Python
6,323
187
import matplotlib.pyplot as plt import matplotlib.transforms as transforms import matplotlib.patches as patches import fig_constants def label_panels_mosaic(fig, axes, xloc=0, yloc=1.0, size=fig_constants.BIGGER_SIZE): """ Labels the panels in a mosaic plot. Parameters: - fig: The figure object. ...
6cfcb9234432f27412f960444d208fee93f9ea9b24495e9cb4f73e4ce61fc39f
Python
6,323
142
import numpy as np from sklearn.metrics.pairwise import euclidean_distances import matplotlib.pyplot as plt import matplotlib.patches as patches from tqdm import tqdm from .nbfr import generate_grid, Model def get_single_target_responses(neuron_locations, stim_design, spks, stim_times, um=1/1.17, valid_radius=30, resp...
e4f0386a9efd1cac67af4f770b0e599ad6a87bfbeb59c6ab3b80997f7c1c943b
Python
6,324
160
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...
438474e0d5bc3ed7803f25049febfe02eed8105d39e6638a1a020961f791af3b
Python
6,326
155
"""Functions for simulations related to IVIM.""" import numpy as np import numpy.typing as npt from ivim.models import sIVIM, diffusive, ballistic, intermediate, check_regime, DIFFUSIVE_REGIME, BALLISTIC_REGIME, INTERMEDIATE_REGIME from ivim.io.base import write_im, read_im, read_bval, read_cval, write_bval, write_cva...
53ff0e13a5b4b9c087066d7574f4dc5fd2ff309572603d0ff42f77c1c3087104
Python
6,326
233
import os import numpy as np import torch import matplotlib.pyplot as plt from sklearn.manifold import TSNE from sklearn.preprocessing import StandardScaler from umap.umap_ import UMAP from params import load_embeddings def filter_nan(labels, embeddings): labels_np = np.array(labels).ravel() val...
c38ea2c6c287a2b50d5b1ccae29afa3551eff4eeb1ff4dc9a824f33908339aa9
Python
6,328
180
import numpy as np import matplotlib.pyplot as plt import sys import os sys.path.append(os.path.dirname(os.path.dirname(__file__))) from src.solvers.vrfb_optimizer import VRFBOptimizer print("Generating enhanced VRFB Pareto front...") optimizer = VRFBOptimizer() electrode_thicknesses = [3, 5, 7, 10] flow_rate...
aee39cc7eaa241a0299a0b97f4b3d82a060a9e57336661c885632b54ce032fc0
Python
6,329
184
from collections.abc import Generator, Sequence from dataclasses import dataclass from typing import ( TYPE_CHECKING, Any, overload, ) import torch from torch.utils.data import DistributedSampler, WeightedRandomSampler from eir.data_load.data_loading_funcs import get_weighted_random_sampler from eir.setup...
3bd6ba38d040cccae7241a08a232512b62b63453d426ef86fe6d9940a8e72172
Python
6,330
175
# -*- coding: utf-8 -*- # python standard library inputs import os # external inputs import numpy as np from numpy.linalg import norm from scipy.stats import sem from nibabel.freesurfer.io import read_geometry, write_morph_data # local inputs from ..io.surf import read_patch def calculate_distortion(file_patch, fi...
a21719ae5aaca29543bbf6fc7b6ff984e403b10770fa6e50b7b52bc8abdf37a0
Python
6,332
207
dict_to_average = { "sub-01": { "AF_L": {'length': [1.00, 2.00]}, "AF_R": {'length': [8.00, 2.00]}, }, "sub-02": { "AF_L": {'length': [9.00, 2.00]}, "AF_R": {'length': [13.00, 2.00]}, } } expected_dict_averaged = { "sub-01": { "AF_L": {'length': {'mean': 1.5...
49b0a8c730dc145cdf147da2c957c5460253ba7b481490a85f16aae307866eac
Python
6,334
185
import inspect import logging from importlib import import_module import immlib from dipy.io.stateful_tractogram import set_sft_logger_level from pcollections._lazy import LazyError from AFQ.utils.docstring_parser import parse_numpy_docstring __all__ = ["methods_descriptors", "kwargs_descriptors", "AFQclass_doc"] ...
f993cd1ad86c5a3b34151330abd40150cff45a31cb41e4cd516fae2b34cf0f5f
Python
6,334
52
from brainscore_vision import benchmark_registry from . import benchmark # behavioral benchmarks benchmark_registry['Scialom2024_rgbBehavioralAccuracyDistance'] = lambda: benchmark._Scialom2024BehavioralAccuracyDistance('rgb') benchmark_registry['Scialom2024_contoursBehavioralAccuracyDistance'] = lambda: benchmark._Sc...
dc6cda4b84437faa38546a693ea8e8bc8cafe6b6d097a01b8999b1cdf900b0c2
Python
6,337
167
#!/usr/bin/env python """ The galvo control UI. Actual control of the hardware is provided by a waveform functionality from the DAQ. Jeff Moffitt 11/15 Hazen Babcock 05/17 """ import fractions import numpy from PyQt5 import QtCore, QtGui, QtWidgets import storm_control.hal4000.halLib.halDialog as halDialog import st...