sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
895b4a58bfca1e427e07f35239f06f3241ce5421177c37cd88f390a04322c38a | Python | 2,287 | 61 | import nilearn.reporting
import nilearn.glm.thresholding
from nilearn.image import new_img_like
import fire
import pickle
import numpy as np
base = "../bids_dataset/derivatives/"
def main(pop, task):
models = ["symbolic", "IT"]
paths = {k: f'{base}rsa/sub-average/pop-{pop}_task-{task}_theory-{k}_bootstrap... |
7779fba10b443d9b465a551cdfd4be939ef4707c4db72805cfa03317244ba9b9 | Python | 2,288 | 55 | import sys
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from .internals import *
from .components import __get_figax
from .model import lm
from typing import Union, Callable, Dict
# grab module
__pub = sys.modules['pubplot']
def from_data(x: Union[list, np.ndarray], lb: Union[list, np.ndarra... |
da5f8ea0a4ec2008989e43e43cbc9ac43e77a0dc617c498d38b8f748e25c964e | Python | 2,288 | 64 | from fileinput import filename
from matplotlib.hatch import Shapes
import numpy as np
import os
import pandas as pd
from pathlib import Path
from brainscore_core.supported_data_standards.brainio.stimuli import StimulusSet
from brainscore_core.supported_data_standards.brainio.packaging import package_stimulus_set
#
# C... |
4faa6a85d65bcd016b4ce0094e9507277182f65f43febc898c8d4608cee93f2b | Python | 2,289 | 77 | # -*- coding: utf-8 -*-
# python standard library inputs
import os
# external inputs
import nibabel as nb
from scipy.ndimage import gaussian_filter
# local inputs
from ..io.get_filename import get_filename
def deweight_mask(file_in, mask_in, mask_max=0.25, sigma_gaussian=10.0,
write_output=False,... |
72e15c8b1e3abd7c6d575b33d9e1c38ef95f4df6fff619155cb35d9aebf584f5 | Python | 2,289 | 57 | BUNDLE_RECO_2_AFQ = {
"AF_L": "Left Arcuate",
"AF_R": "Right Arcuate",
"UF_L": "Left Uncinate",
"UF_R": "Right Uncinate",
"IFOF_L": "Left Inferior Fronto-occipital",
"IFOF_R": "Right Inferior Fronto-occipital",
"CST_L": "Left Corticospinal",
"CST_R": "Right Corticospinal",
"ILF_L": "... |
7b2c40a65cd496ce9058e6166366cfc2aee2477974d9dcdab575635f82352709 | Python | 2,289 | 69 | #!/usr/bin/env python
# Install script for labdata tools
# wfield - tools to transfer and copy data in the lab
# Copyright (C) 2021 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... |
e48470baf145aed40544a04587b3fab459227453b45422b5e35001069bea2f38 | Python | 2,290 | 72 | from brainscore_core.supported_data_standards.brainio.stimuli import StimulusSet
from brainscore_core.supported_data_standards.brainio.packaging import package_stimulus_set
import pandas as pd
import numpy as np
'''
Dataset Information:
- From Hebart 2023: https://elifesciences.org/articles/82580v1
- For metadata see... |
4cee0d9abd22faab94d3c457d857eb0ed63d91434434cc719b930e20ff95bcb7 | Python | 2,291 | 64 | from brainscore_vision.model_helpers.check_submission import check_models
import functools
import os
from urllib.request import urlretrieve
import torchvision.models
from brainscore_vision.model_helpers.activations.pytorch import PytorchWrapper
from brainscore_vision.model_helpers.activations.pytorch import load_prepro... |
38f46713568c6abbead2636121782bc6d122a3a0acb3f74b1f9edb9b5e430351 | Python | 2,292 | 95 | import arbor as A
from arbor import units as U
import matplotlib.pyplot as plt
from pathlib import Path
import numpy as np
here = Path(__file__).parent
E = np.zeros(shape=(3,), dtype=np.float64)
ctr = "(location 0 0.5)"
mrf = A.load_swc_neuron(here / "Acker2008.swc")
dec = (
A.decor()
.set_property(Vm=-55... |
3c4280729c4757c355236de90883dd06ba7d56d9dea330f71c90b659e3e62c9f | Python | 2,293 | 72 | """
Non maxima suppression on WSI results
Uses a kdTree to improve speed. This will only work reasonably for same-sized objects.
Marc Aubreville, Pattern Recognition Lab, FAU Erlangen-Nürnberg, 2019
"""
import numpy as np
import torch
from sklearn.neighbors import KDTree
from utils.detection_... |
db674e3de98ad5352db6bd57f2157857072c4e14c4cc68d8d7135a1854b2e8b2 | Python | 2,293 | 104 | # Kai Sandbrink
# 2023-02-01
# This script computes the learning curves for specified test models
# %% LIBRARY IMPORTS
import torch
import pandas as pd
import numpy as np
from utils import Config, get_timestamp
from utils_project import load_config_files
from test_case import test
import os, copy, pickle
import multi... |
1ae8e060f7ecfdb8987fba00c1801db36d6772de2c7af36b9ceee22538027e8d | Python | 2,294 | 73 | # -*- coding: utf-8 -*-
# @Author : LG
import numpy as np
import pydicom
from PIL import Image
from pydicom.multival import MultiValue
def load_dcm_as_image(ds_file):
r"""
Load dcm file as a PIL Image.
Arguments:
ds_file (str): path to dicom file
Returns:
Image (PIL.Image)
"""
... |
7b028616c3a078fb87ec199ef571e6b904786b705f0ccc2f432a52d47845e4eb | Python | 2,295 | 64 | from brainscore_vision.model_helpers.check_submission import check_models
import functools
import os
from urllib.request import urlretrieve
import torchvision.models
from brainscore_vision.model_helpers.activations.pytorch import PytorchWrapper
from brainscore_vision.model_helpers.activations.pytorch import load_prepro... |
c9fede7f6775527850e161434695b1289eae51f6320dd0b3c104d460854bfb19 | Python | 2,295 | 100 | from __future__ import annotations
from typing import Literal, NamedTuple
import numpy as np
import obspy
Key = tuple[float, str]
class GroupedTraceData(NamedTuple):
data: np.ndarray
stations: list[str]
component_order: list[str]
start_time: obspy.UTCDateTime
sampling_rate: float
grouping: ... |
e0a9a08831a9b015562789112bfc30aab4c1d7b7522224a72ffc985df00f645b | Python | 2,295 | 72 | """ChemGraph evaluation and benchmarking module.
Provides a structured framework for evaluating LLM tool-calling
accuracy across multiple models and workflows against ground-truth
datasets. Two judge strategies are available:
1. **LLM-as-judge** -- a separate judge LLM compares the agent's
tool-call sequence and ... |
f37669420ecde6deea5c830389e72d7ea603c25f35ffcb024d0f2e4590c74fc5 | Python | 2,295 | 66 | #!/usr/bin/env python
import numpy as np
import pandas as pd
import click as ck
from sklearn.metrics import classification_report
from sklearn.metrics.pairwise import cosine_similarity
import sys
from collections import deque
import time
import logging
from sklearn.metrics import roc_curve, auc, matthews_corrcoef
from... |
7f1339edb963ad3301abef02c3a9352b9220f2509f312087792b24989098a10b | Python | 2,297 | 81 | import unittest
import torch
import torch.nn as nn
import torch.testing as ptt
from deepdwi import fourier, util
from deepdwi.dims import *
from deepdwi.models import resnet
from deepdwi.recons import zsssl
if __name__ == "__main__":
unittest.main()
devices = [torch.device('cpu')]
if torch.cuda.is_available()... |
b970b461950eff82921dbd5ea67d1473ece2218dd926cbf07c2976842e38824f | Python | 2,297 | 38 | """Pinned reference objects, archive evidence, and gene sets for plan freeze."""
import json
from src.acquisition.download import ROOT, COMMIT, acquire
def main():
tree=json.loads((ROOT/'data/raw/schmidt/github_tree.json').read_text())
for item in tree['tree']:
name=item['path']
if item['type'... |
16182056a3024ff6ccca3fe1b4290fcfec5111cc72efea1a91284bbc6ca2e6d4 | Python | 2,298 | 63 | from __future__ import annotations
import copy
import numpy as np
import numpy.typing as npt
from ._model import Shape
def can_merge_shapes(shapes: list[Shape], /) -> bool:
return (
len(shapes) > 1
and all(s.shape_type == "mask" and s.mask is not None for s in shapes)
and len({s.label f... |
c7ef89c08d26a91cb1ed803203a7e5a6b2e364750a7e6e4a58843a5ab42d9cfe | Python | 2,298 | 89 | # src/utils/logger.py
"""
统一日志模块 —— 基于 Python 标准 logging
功能:
- 在控制台和文件中输出日志
- 支持按模块或全局设置日志级别
- 便于训练、评估等脚本统一记录运行信息
使用示例
--------
from src.utils.logger import setup_logger, logger
# 初始化日志(可在主脚本开头调用)
setup_logger(
name="strabismus",
log_file="logs/strabismus.log",
level="INFO"
)
# 之后即可在任何文件中导入并使用
logger.i... |
ff950d392efc2694ebaabb59ffaede9f8a1df2bef7adebe9d52db89afca7d23d | Python | 2,298 | 76 | # The ImpedanceFitter is a package to fit impedance spectra to
# equivalent-circuit models using open-source software.
#
# Copyright (C) 2018, 2019 Leonard Thiele, leonard.thiele[AT]uni-rostock.de
# Copyright (C) 2018, 2019, 2020 Julius Zimmermann,
# julius.zimmermann[AT]un... |
4ff3d9f7ede7aafa4a12d9fb9a7d94a40a47acb67d0df811168ee56a84c5ad0f | Python | 2,299 | 81 | # -*- coding: utf-8 -*-
"""
Great library of phenotypes
"""
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib import cm
from mpl_toolkits.mplot3d.axes3d import Axes3D, get_test_data
from sklearn.preprocessing import StandardScaler
from sklea... |
5b738f67c77e4f874fd7cae0d2288fde9d585d76fd80bde7166a4d115683ee88 | Python | 2,299 | 87 | '''
A class for serial interface to an arduino to control TitanEZ chain.
George Emanuel
2/16/2018
'''
import serial
import string
import time
from storm_control.fluidics.valves.valve import AbstractValve
class TitanValve(AbstractValve):
def __init__(self, com_port=2, verbose= False):
self.com_port ... |
633cb22ba01aa804898dc542dd6780e91828f97c85cbbccea3000dfc647b2c5c | Python | 2,299 | 61 | from PUMI.engine import BidsPipeline
from PUMI.pipelines.anat.segmentation import bet_fsl
import argparse
import os
"""
Using command line arguments, one can set the paths to the input/output/working directory of the workflow.
Remember to enter a full path.
If nothing was given, default paths will be... |
eadd8a1b5196a69cb8b4d4fd16e8762c11707cb9d7c16bfa7d9ca643848139a3 | Python | 2,299 | 78 | import json
import numpy as np
import glob
import os
from pymatgen.core.structure import Structure
from pymatgen.io.jarvis import JarvisAtomsAdaptor
from tqdm import tqdm
data = 'BOTH-SN-Em-train.json'
with open(data, "rb") as f:
dataset = json.loads(f.read())
# ### Now set up alignn model
from alignn.data_du... |
d3986713ed533e08a42f4739c8896e14d5a25246d026f9232d3615282c99156d | Python | 2,300 | 74 | import json
import numpy as np
import matplotlib.pyplot as plt
with open('results/tables/drl_vrfb_results.json', 'r') as f:
results = json.load(f)
print("DRL Results Loaded:")
print(f" SOC RMSE: {results['final_soc_rmse']:.4f}")
print(f" WLSS: {results['final_wlss_%']:.2f}%")
print(f" Training time: {results['... |
1bbc8faf6a7f5d1291fa8ce7b29fb93c7d4b8b4f307098bc09e95cf295f70c6f | Python | 2,301 | 64 | from brainscore_vision.model_helpers.check_submission import check_models
import functools
import os
from urllib.request import urlretrieve
import torchvision.models
from brainscore_vision.model_helpers.activations.pytorch import PytorchWrapper
from brainscore_vision.model_helpers.activations.pytorch import load_prepro... |
8bf6e262ac5af4a59f8e56755cab68ac6cce33d5ef6ef58905fbc05a6539fbc1 | Python | 2,301 | 62 |
import os
import pickle
import matplotlib.pyplot as plt
import numpy as np
DIR = os.path.dirname(os.path.realpath(__file__))
plt.rcParams['font.family'] = 'monospace'
# %% define helper functions
def get_indices_of_noise(noiseParam):
indices_sorted_noise = []
for noiseValue in range(int(max(noiseParam))+1... |
e874ef892b0a8bf17a517c551795f7098f9d4972a175e46fd24910311878256b | Python | 2,301 | 70 | from PIL import Image
from image_similarity_measures.evaluate import evaluation
class ImageComparison2D:
"""
Comparison of image similarity
Compares image-related similarity metrics of defaced and original 2D-image
- RMSE
- PSNR
- SSIM
- FSIM
- Percentage of different pixels
"""
... |
fa471681ec63bcb45fc25e98443ac1df3b14492cab1d1ab50d40c8f402107845 | Python | 2,301 | 60 | # 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, ... |
4bc6efe09030dfe8309dc6c23f0584223d20db7c361eff86709c0d5383e8d98b | Python | 2,302 | 78 | import json
import numpy as np
import glob
import os
from pymatgen.core.structure import Structure
from pymatgen.io.jarvis import JarvisAtomsAdaptor
from tqdm import tqdm
data = 'BOTH-SN-Em-train.json'
with open(data, "rb") as f:
dataset = json.loads(f.read())
# ### Now set up alignn model
from alignn.data_du... |
801d46ad613f833afdc990623518a5046f984afc9f1a4f1e2904ac5ce2c8ca13 | Python | 2,302 | 73 | # Copyright (C) CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT
from typing import Any
from django.apps.registry import Apps
from django.db import migrations
from django.db.backends.base.schema import BaseDatabaseSchemaEditor
from django.db.models import Q
_FORWARD_REPLACEMENTS = {
"create:export": (
... |
471839f1c902d1395037003bd33ceb669b4e652929ef40bb5712781d2519a7dc | Python | 2,303 | 65 | import torch
import torch.nn as nn
# 定义 Transformer 块
class ParallelTransformerBlock(nn.Module):
def __init__(self, dim=512, heads=8, ff_mult=4):
super().__init__()
self.norm = nn.LayerNorm(dim)
self.attn = nn.MultiheadAttention(embed_dim=dim, num_heads=heads, batch_first=True)
self... |
64b080ccc859832c59798f2f72e6b7a3a0dac0f20d083700572f09f219fe9457 | Python | 2,305 | 69 | from __future__ import annotations
import shutil
import subprocess
import sys
from collections.abc import Iterator
from pathlib import Path
from typing import Final
from xml.etree import ElementTree
import PIL.Image
import pytest
from PySide6 import QtWidgets
from PySide6.QtCore import QCoreApplication
from PySide6.Q... |
7c11bb5b09ce1f67205ed2ee720c20376f9b4e66a3c1f69d9e98f15c201238e3 | Python | 2,305 | 106 | #!/usr/bin/env python
#
# FJN, Sainsbury Laboratory, Cambridge University
# 4.6.2019
"""
Read data from file and save plot
Syntax:
plot.py [filename]
"""
import sys, math, os
from random import random
try:
import matplotlib
import matplotlib.pyplot as plt
except ImportError:
prin... |
58e689a1fbda9c7b2d0b74a7d69994bd81c2be6ec03c0b5178681f067d8e8112 | Python | 2,306 | 83 | """
Script that performs grid search over lambda parameter
"""
import pandas as pd
import json
import numpy as np
from stg_PopPK.main_utils import run_cv, run_train
import argparse
import os
from pathlib import Path
ROOT_PATH = Path(__file__).resolve().parent.parent
DATA_PATH = ROOT_PATH / "data"
def read_data(scen... |
99918d30903aaaa35e5a6c36f8312acd79a4fd7484535ed4baed625e309a8d2c | Python | 2,308 | 46 | """Guard scientific reporting against missing checks and false robust labels."""
import hashlib
import json
import numpy as np
import pandas as pd
import pytest
from src.transcriptomics.report_results import classify, verify, ROOT
def test_significance_does_not_override_block_reversal():
assert classify(1e-15, 2.... |
5d3e4f28f544d4a30b3867e516a04571bf3bfd31df2bb6cb28c55986e9d55e58 | Python | 2,309 | 74 | import re
import subprocess
import tempfile
from pathlib import Path
from typing import Optional
import click
from dti.utils import mri_number_of_frames
# TODO: Incorporate to allow multiple files resliced simultaneously
def moving_pair(args):
assert len(args) == 2, f"Got {len(args)} arguments, should only have... |
b594497f7032da3162ded77205490c147605b5434373cfe613ae00f3ddffb51a | Python | 2,309 | 78 | import json
import numpy as np
import glob
import os
from pymatgen.core.structure import Structure
from pymatgen.io.jarvis import JarvisAtomsAdaptor
from tqdm import tqdm
data = 'SINGLE-BOTH-SN-Em-train.json'
with open(data, "rb") as f:
dataset = json.loads(f.read())
# ### Now set up alignn model
from alignn.... |
157535bd9f7f2a99bebec5cbb171d4c8837d5d75e2b25c1bf75dc56e3f05031d | Python | 2,310 | 64 | from brainscore_vision.model_helpers.check_submission import check_models
import functools
import os
from urllib.request import urlretrieve
import torchvision.models
from brainscore_vision.model_helpers.activations.pytorch import PytorchWrapper
from brainscore_vision.model_helpers.activations.pytorch import load_prepro... |
43e4145d704ebab4ad1f6f801b3e062aed5a5aabf0de77fdc32c8cd375b54ac6 | Python | 2,310 | 64 | from brainscore_vision.model_helpers.check_submission import check_models
import functools
import os
from urllib.request import urlretrieve
import torchvision.models
from brainscore_vision.model_helpers.activations.pytorch import PytorchWrapper
from brainscore_vision.model_helpers.activations.pytorch import load_prepro... |
442a1e71fb9ae478e489f6627cbb41933d082787ab57ba24b54ba1a8b42af787 | Python | 2,310 | 54 | from neuron_morphology.feature_extractor.marked_feature import (
specialize, nested_specialize
)
from neuron_morphology.feature_extractor.feature_specialization import (
NEURITE_SPECIALIZATIONS,
AxonSpec,
BasalDendriteSpec,
ApicalDendriteSpec
)
from neuron_morphology.features.statistics.moments_alon... |
873b7aec2965dc3b8999a67c5ed548f5d17cd3c3b52fef312495bd1d17a91a67 | Python | 2,310 | 64 | #!/usr/bin/env python3
import os
import unittest
class TestHometools(unittest.TestCase):
def test_cli(self):
from subprocess import Popen, PIPE
p = Popen('syri -h'.split(), stdout=PIPE, stderr=PIPE)
out = p.communicate()
assert 'error' not in out[1].decode()
# END
def test_... |
96b43eb0ffe83a75711e8372d44bed71f181ca42097e393ca8339e3cdd8f3d76 | Python | 2,310 | 53 | import os
from argparse import ArgumentParser
import numpy as np
import torch
from Functions import generate_grid_unit, save_img, save_flow, transform_unit_flow_to_flow, load_4D
from miccai2020_model_stage import Miccai2020_LDR_laplacian_unit_disp_add_lvl1, \
Miccai2020_LDR_laplacian_unit_disp_add_lvl2, Miccai202... |
02a0ecf0b17805f1eafc041410d89a90f3474f00473ddd21a51c33d4881b2835 | Python | 2,311 | 55 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Script for preprocessing data with FSL prior to training. This step is done within
the script brain_age.py but is too time consuming to do on-the-fly during training.
This script uses FSL to do a rigid registration (6 DOF) to the MNI brain, so FSL FLIRT needs to be i... |
4a69d73763318fc01c163cbba414182906151ca69ee6effc0333d42d42c2424d | Python | 2,311 | 92 | import itertools
import os
import os.path as op
import numpy as np
from pydesigner.fitting.dwipy import DWI
from pydesigner.system.utils import writeNii
basePath = os.path.join('/Volumes','Flashy','HIE_FBI_003','FBWM_b4000')
dwi_path = os.path.join(basePath, "dwi_preprocessed.nii")
bvec_path = os.path.join(basePath,... |
d81a959e2e783ed132af1ce34522d338ee683b8834481de305b607c0bdcb00b0 | Python | 2,311 | 81 | import matplotlib.pyplot as plt
import pandas as pd
import os
cases = 'Abel'
mmHg_to_Pa = 133.3616
t01 = 750
t02 = 1650
cm = 1/2.54
# plot for the heart
models = 'heart_kim_lit'
nodes = ['left-atrium','left-ventricular','aorta']
edges = ['D-mitral','D-aorta']
c_nodes = ['r','k','b']
c_edges = ['r','b']
fig = plt.fi... |
dfa91617b01b1b454cbd22774dcea91ded9306fba4ad189cea38f1ef7947fd4c | Python | 2,312 | 79 | import numpy as np
from torch import nn, Tensor
import torch
class Attention(nn.Module):
def __init__(self, ed, ev, n_ed=None, n_ev=None):
super().__init__()
if n_ed is None:
n_ed = ed
if n_ev is None:
n_ev = ev
self.query_weight = nn.Parameter(torch.eye(... |
23c880b5059de7feca8f1d4d0953c522ab5fe91d40ebed62aaf5df7cecdb3b55 | Python | 2,313 | 70 | from torch.utils.data import DataLoader
from geoseg.losses import *
from geoseg.datasets.vaihingen_dataset import *
from geoseg.models.UNetFormer import UNetFormer
from catalyst.contrib.nn import Lookahead
from catalyst import utils
# training hparam
max_epoch = 105
ignore_index = len(CLASSES)
train_batch_size = 16
va... |
55304e8f05f1cc86de7c5bda99e706243890ad43af8fe5c39957610066c465e8 | Python | 2,313 | 79 | from pathlib import Path
import click
import dolfin as df
import numpy as np
import simple_mri as sm
from panta_rhei import read_domain
from simple_mri import load_mri
from gmri2fem.segmentation_groups import (
CEREBRAL_CGM_RANGES,
CEREBRAL_WM_RANGES,
SUBCORTICAL_GM_RANGES,
)
from i2m.mri2fenics import fi... |
75f7abd7c7c0430ea316045e53e709fefa2736dada6fa652885688d401335506 | Python | 2,313 | 84 | """Cost functions for SciPyBackend."""
import numpy as np
from nems.tools.lookup import FindCallable
# TODO: Need to have normalization in-place for multi-neuron data
# (or multi-batch?), otherwise some components will get weighted
# more heavily. Should be a pre-processing step.
# TODO: I don't love h... |
110ae562469df96a676415c7fed34c095b87a1ccc820ffeee6f0d7665037bb24 | Python | 2,314 | 67 | # Copyright (C) CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from cvat.apps.engine.models import CloudStorage, Task
from ..utils import move_multiple_tasks, parse_task_ids
class Command(BaseCommand):
help... |
1f10b80190392623d481d1547bfc01e73c5880ff5bd2c5c5e2de3a2100c3f479 | Python | 2,314 | 67 | #############################################################################
# Copyright (C) 2020-2026 MEmilio
#
# Authors: Henrik Zunker, Maximilian Betz
#
# Contact: Martin J. Kuehn <Martin.Kuehn@DLR.de>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in complia... |
4b598def090ad883e414d07ef9eb7fc9515280bd0596abef9ac60adcd0b80a24 | Python | 2,314 | 74 | from collections.abc import Callable
from typing import TYPE_CHECKING
import torch
from torch import nn
from eir.models.layers.mlp_layers import MLPResidualBlock, ResidualMLPConfig
from eir.models.models_utils import (
calculate_module_dict_outputs,
create_multi_task_blocks_with_first_adaptor_block,
)
from ei... |
5c29cb1c63456d02fdc3ade9c84d0623c06677631014e2a553b8b5644470faae | Python | 2,314 | 61 | # This file is part of connectome-manipulator.
#
# SPDX-License-Identifier: Apache-2.0
# Copyright (c) 2024 Blue Brain Project/EPFL
import os
import types
import numpy as np
from numpy.testing import assert_array_equal
from utils import setup_tempdir, TEST_DATA_DIR
import connectome_manipulator.model_building.model_... |
ad7d865ef16c6004202a606ab3ca0dea3f333520b06dec9ca889186258aabc40 | Python | 2,314 | 93 | import pandas as pd
import numpy as np
trendsdf = snakemake.input.trend
bg_subtract = snakemake.output.subtract
bg_log2 = snakemake.output.log2
auxo = snakemake.output.aux
ctrlo = snakemake.output.ctrl
_sdic = {
'aux': [],
'ctrl': []
}
with open(trendsdf) as f:
for line in f:
if line.startswith('R... |
cfbe6699e1771f6a02abb8c356af647f08fc5e0c75f3dd035c885c4971fee873 | Python | 2,314 | 71 | import torch.nn as nn
from basics.utils_u_b import unetConv3d, unetUp3d
class unet3d(nn.Module):
def __init__(self,
feature_scale = 2,
n_classes = 5,
is_deconv = True,
in_channels = 9,
is_batchnorm = False,
is_hpool = True,
):
super(unet3d, self)._... |
19e371f132833ea7a8e3e100808d7ffc2d9b7dd051a35427db58e4ae685e26f5 | Python | 2,315 | 66 | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
from pathlib import Path
import numpy as np
import torch
from ultralytics.utils import LOGGER
from .base import BaseBackend
class AscendBackend(BaseBackend):
"""Huawei Ascend NPU inference backend for CANN ... |
26977cc2326a34c8671ceda51afcaa41fd2431fce7355d6d13fa7724ea6b7fbc | Python | 2,315 | 53 | import os
from nipype.interfaces.base import TraitedSpec, File, Directory, CommandLineInputSpec, File, TraitedSpec, CommandLine, Directory
class Synb0InputSpec(CommandLineInputSpec):
# T1W_IMG=$1
# DWI_IMG=$2
# OUTPUT_DIR=$3
# DWI_JSON=$4
# FMAP_DIR=$5
# if [[ $# -ne 5 ]]; then
# echo "Usa... |
71e8deef02ce5d7e47d26f72132f223e59fb57f6e6ac21fadb679104ad2fe951 | Python | 2,316 | 63 | import onnxruntime as ort
import os
import numpy as np
class OnnxClassifier(object):
def __init__(self, model_name=None):
self.model = None
self.ensemble = False
if model_name is not None:
if "ensemble" in model_name.lower():
self.load_model_ensemble(model_name)
... |
aea2de07d1d6e18a7d7fd858d8e9d0b2b0b7cedee8ebee756ff8035e133d7daf | Python | 2,316 | 85 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2023/6/3 15:20
# @Author : SONG-LE
# @知乎 : https://www.zhihu.com/people/xiao-xue-sheng-ye-xiang-xie-shu
import numpy as np
from numpy import poly1d
from numpy import polyfit
def BoxCounting(MT, EPSILON):
# 以EPSILON 行为一组,合并三维矩阵的行
MT_BOX_0 = np.add.reducea... |
d354a5004c096e9d8eab99ad353585dcfb07c3d95d1fcc9555393f84de7dda03 | Python | 2,316 | 82 | #!/usr/bin/env python
import sys
import argparse
import pysam
import os
from Bio import SeqIO, Seq, SeqRecord
from math import ceil
def split_reads(input_bam_filename, outdir, n_chunks):
"""
Splits unmapped reads into chunks.
Parameters
----------
input_bam_filename : str
Name of the BAM... |
93dd2d6352ade58c8fbc262974fef9d06e622839d1c7dea732e65367733070f4 | Python | 2,317 | 66 | import torch
from utils import loss_and_miner_utils as lmu
from miners.base_miner import BaseTupleMiner
class UniformHistogramMiner(BaseTupleMiner):
def __init__(self, num_bins=100, pos_per_bin=10, neg_per_bin=10, **kwargs):
super().__init__(**kwargs)
self.num_bins = num_bins
self.pos_per... |
6533d207f7cb2ff432e6b71a9f634df19c3b007e67e8e2bfd701fc36afd469d1 | Python | 2,318 | 88 | # Predictor module
# Imports
from pathlib import Path
import joblib
import torch
import numpy as np
import pandas as pd
from modules.tools.types_abbrv import MLP_REG_TYPE
def run_all(
trained_model_file: str,
features_file: str,
scaler_path: str,
output_file: str,
):
"""Run every step to predi... |
727478d03939c0b08d59dd83417993d4ad22b85e02ec1ccf03b843f2aef68690 | Python | 2,318 | 58 | """
file: Brain_Comparment_Analysis_Demo.py
author: Tiago Ferreira
version: 20200126
info: A Python demo on how to assess the brain areas a neuron projects to
(in this case a MouseLight neuron retrived from the MouseLight
database). Internet connection required.
"""
from sc.f... |
b11148e9e2cddb43aa33ea15b6fc7639296ae2fdf57ef3ebdcbe5c377eb2cdda | Python | 2,318 | 64 | import os
import numpy as np
from torchvision import transforms
class DatasetSOFIA:
def __init__(self, folder_path, subject_meta, is_ct_image=False, is_shape=False, mci_sigma=2,transform=None):
self.folder_path = folder_path
self.images = []
self.labels = []
self.cores = []
... |
d2b401b5768dbb899670074f4b0862baf0c1a2e716edd435557a2c3eeafe85ce | Python | 2,318 | 75 | # -*- coding: utf-8 -*-
"""
@author: cdonnat
"""
### Random tools useful for saveing stuff and manipulating pickle/numpy objects
import numpy as np
import pickle
import gzip
import re
import networkx as nx
def save_obj(obj, name, path, compress=False):
# print path+name+ ".pkl"
if compress is False:
w... |
f0f5c1dbf588579be44ec2ebb4692e576a83aa281d2d13845f818c85830b8397 | Python | 2,318 | 55 | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
"""Depth estimation predictor for YOLO models."""
from __future__ import annotations
from typing import Any
import numpy as np
import torch
import torch.nn.functional as F
from ultralytics.engine.predictor import BasePredictor
from ultralytics.engi... |
990f17800afc6175f9073dd2660104828875f16601c5157d28faa373c1c64717 | Python | 2,319 | 71 | #############################################################################
# Copyright (C) 2020-2026 MEmilio
#
# Authors: Maximilian Betz
#
# Contact: Martin J. Kuehn <Martin.Kuehn@DLR.de>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Li... |
0ffc7b6310b605c2b8c6ad684a601f7e2b186a821a8cc1ae0bfd784fe14d2789 | Python | 2,320 | 54 | import nighres
import os
import nibabel
import numpy
import glob
inpath = '/home/pilou/Projects/Cerebellum/Cerebellar-segmentation-ABC/'
out_sfx = 'nighres/denoise/'
inv1m_sfx = '_anat_inv1.nii.gz'
inv1p_sfx = '_anat_inv1_ph.nii.gz'
inv2m_sfx = '_anat_inv2.nii.gz'
inv2p_sfx = '_anat_inv2_ph.nii.gz'
mni = '/home/pilo... |
799632de54aa813431c494f6398d4cdd0cbcc5e9dff4b058506f2c8bb3fc0a5f | Python | 2,320 | 64 | from brainscore_vision.model_helpers.check_submission import check_models
import functools
import os
from urllib.request import urlretrieve
import torchvision.models
from brainscore_vision.model_helpers.activations.pytorch import PytorchWrapper
from brainscore_vision.model_helpers.activations.pytorch import load_prepro... |
febe5e9f84be4b4f38353f249b00767a87a8e0754207567219b93c12697efaeb | Python | 2,320 | 71 | from typing import Type
import numpy as np
from neuron import h
from ..cells.neuron_cell import NeuronCell
from .simulation import Simulation, WaveformType
from neuron.units import ms, mV
class VoltageCurveSimulation(Simulation):
def __init__(
self,
neuron_cell: Type[NeuronCell],
wavefor... |
406326f2cdd6162c849329a6b9f5b9b5e90b7317df6e18fa17fbdb9cb768ac64 | Python | 2,321 | 74 | import os
import numpy as np
import pandas as pd
import pytest
from mcmlnet.data_gen.camera_adaptation import adapt_simulations_to_tivita
@pytest.fixture # type: ignore[misc]
def dummy_filters() -> pd.DataFrame:
"""Create a dummy filter response CSV file."""
return pd.DataFrame(
np.concatenate([np.... |
c2b91a5e4a868973e6d4227a660303b441340984d9664b4edce7b32829f9de82 | Python | 2,321 | 65 | import numpy as np
from fancyimpute import (
BiScaler,
KNN,
NuclearNormMinimization,
SoftImpute,
SimpleFill
)
n = 200
m = 20
inner_rank = 4
X = np.dot(np.random.randn(n, inner_rank), np.random.randn(inner_rank, m))
print("Mean squared element: %0.4f" % (X ** 2).mean())
# X is a data matrix which w... |
4b091aa8b7f8c4796603a77ef4ba61c6fd9ba7597ac995b13138d338ea28ec9d | Python | 2,322 | 69 | import sys
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from .internals import *
from .components import __get_figax
from typing import Union, Callable, Dict
# grab module
__pub = sys.modules['pubplot']
def legend(fig: Union[matplotlib.figure.Figure, None] = None, ax: U... |
e137116905b7ffe3d7ae18163c115283f6a41d88eb32f85a41b6d617a6d3eafa | Python | 2,322 | 33 | import matplotlib.pyplot as plt
from src.ionisation import *
if __name__ == "__main__":
"""
Equation for systematic error removal
E_actual (in eV) = 0.397 + 0.731 * E_vert (in eV) for wB97X-D4
Emodin | Calculated | After systematic error removal
S111 ... |
331418f8a4dfcc49377edef501769bc395262760227c34ea4199bb846bdebd01 | Python | 2,323 | 61 | from brainscore_vision.model_helpers.activations.pytorch import PytorchWrapper
from brainscore_vision.model_helpers.activations.pytorch import load_preprocess_images
import ssl
import functools
import timm
from brainscore_vision.model_helpers.check_submission import check_models
ssl._create_default_https_context = ssl... |
dcf1175c140c57a8ad72ddb3856ef76476276b5841fe2b7d9fc33f08ccd244a0 | Python | 2,323 | 69 | import torch.nn as nn
import torch
from torch.autograd import Variable
class VariationalBottleneck(nn.Module):
def __init__(self, z_dim):
super(VariationalBottleneck, self).__init__()
self._z_dim = z_dim
@property
def z_dim(self):
return self._z_dim
def forward(self, dis... |
5fe658593a06b83cd65715bc2f71d02c1471e2e493d63a301da299925a1d0cf4 | Python | 2,324 | 84 | import os
import json
import torch
def save_model(
model,
out_path,
filename):
os.makedirs(out_path, exist_ok=True)
if not filename.endswith(".pth"):
filename += ".pth"
filepath = os.path.join(out_path, filename)
torch.save(model.state_dict(), filepath)
print(... |
5ff7f4244a3aec317d84ea4896add03d65c0f5117cba85458b5f79523b2dcc37 | Python | 2,324 | 77 | import bz2
import gzip
import os.path as osp
import sys
import tarfile
import zipfile
def maybe_log(path: str, log: bool = True) -> None:
if log and 'pytest' not in sys.modules:
print(f'Extracting {path}', file=sys.stderr)
def extract_tar(
path: str,
folder: str,
mode: str = 'r:gz',
log:... |
76174cfec5259fc64596111d5d1ae49a8613a606a139507351331d98e6d3c193 | Python | 2,325 | 68 | from __future__ import annotations
from typing import Final
from PySide6 import QtGui
from PySide6 import QtWidgets
from PySide6.QtCore import Qt
class ToolBar(QtWidgets.QToolBar):
def __init__(
self,
*,
title: str,
actions: list[QtGui.QAction],
orientation: Qt.Orientatio... |
a6b3d1aa3475074c7cf4e1996a9123f99f18077bf0facec7ea44a19f9b870d1d | Python | 2,325 | 66 | import torch
from distances import CosineSimilarity
from utils import common_functions as c_f
from utils import loss_and_miner_utils as lmu
from miners.base_miner import BaseTupleMiner
class MultiSimilarityMiner(BaseTupleMiner):
def __init__(self, epsilon=0.1, **kwargs):
super().__init__(**kwargs)
... |
ab041ff240820b9c45531ca92c72e626d5a9870ecd44ca6619bacc59b2cbb92e | Python | 2,325 | 67 | # @Context context
# @LUTService lut
# @SNTService snt
# @UIService ui
"""
file: Reconstruction_Viewer_Demo.py
author: Tiago Ferreira
version: 20190318
info: Exemplifies how to render reconstructions and neuropil annotations
in a stand-alone Reconstruction Viewer. Requires internet conne... |
def250b032d1f59f5ebed5dd9ce64fc744a2a299c75e1bd556285e7edab3fe13 | Python | 2,325 | 92 | """
utils/delong.py
基于 DeLong 方法对比两组预测概率的 AUC 差异显著性检验。
用法示例:
from utils.delong import delong_roc_test
p_value, auc1, auc2 = delong_roc_test(y_true, prob_set1, prob_set2)
"""
import numpy as np
from scipy import stats
def _compute_midrank(x: np.ndarray) -> np.ndarray:
"""
计算中位秩(midrank)——DeLong 算法内部使用
... |
e854b43e29716ed6edf75e7fca06d0461fc1b96a2b2d8fdd467462b31fb3d650 | Python | 2,325 | 70 | import argparse
import numpy as np
import shap
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from xgboost import XGBClassifier
from pathlib import Path
import pickle
from sklearn.metrics import accuracy_score
from pstimutils import PertStimDataSimple... |
4fe14573e846326d7b478e09a262d5e25d89fff54eaa9236a16839de99929153 | Python | 2,326 | 59 | #!/usr/bin/env python
"""
HAL module for controlling a Thorlabs laser diode. The
actual control is done by a DAQ card.
Hazen 05/17
"""
import storm_control.hal4000.halLib.halMessage as halMessage
import storm_control.sc_hardware.baseClasses.amplitudeModule as amplitudeModule
import storm_control.sc_hardware.baseClas... |
f741778e7c64d44e855b366c9ac90c94301f52fc0d79ff4944be0c48fda060cf | Python | 2,326 | 72 | # Copyright (C) CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT
import sys
import traceback
from argparse import ArgumentParser
from django.conf import settings
from django.core.management import call_command
from django.core.management.base import BaseCommand, CommandError
from redis import Redis
from cvat.app... |
00b172625395c24d291bc9f878b0fc7dfe2267c7061ce55e9e1f3acd44555e42 | Python | 2,328 | 73 | import os
from parsl.config import Config
from parsl.providers import LocalProvider
from parsl.executors import HighThroughputExecutor
from parsl.launchers import MpiExecLauncher
from chemgraph.hpc_configs.loader import resolve_worker_init
def get_polaris_config(
run_dir=None,
worker_init: str | None = None,... |
693804b71744ba56dc6019003c045cba5d74a4396b4192e6a88a1ff03fd35def | Python | 2,328 | 59 | from train_gtex_all_genes import *
class AttrDict(dict):
"""A dictionary class that supports attribute-style access."""
def __getattr__(self, item):
try:
return self[item]
except KeyError:
raise AttributeError(f"'AttrDict' object has no attribute '{item}'")
def _... |
bf8adfd5e771bdc365c35ae9ff8760dcea7aa88481dc7e24f28c1e3e2d67ff00 | Python | 2,328 | 69 | """Make the generated test BAMs from the test CRAM.
Two BAMs, each skipped when already present:
- generated/test-chr20.bam: the header lists only chr20. This sample
tests a bam with fewer contigs than its fasta.
- generated/test-rev.bam: the header lists chr21 before chr20. This
sample tests header-order preserv... |
c4687b9a8c2b8164e6f4fcb8e5aa8ed3e077940097942ea93bb180a4620d7daf | Python | 2,329 | 69 | import torch
import pandas as pd
from torch.utils.data import DataLoader
from IEFFEUM import dataset, model
def get_target_F_onehot(positions):
lower_breaks = torch.linspace(2, 42, 21, device=positions.device)
upper_breaks = torch.cat([lower_breaks[1:], torch.tensor([1e4], dtype=torch.float32, device=positions... |
c95e4dbc210e5665cf7633fa7820e444f02cc61bdb50043e15ff07bab718d441 | Python | 2,329 | 45 | import numpy as np
from pfcmap.python.utils import stimfuncs as sfn
stimplotfns = {
'AudStim_10kHz': lambda timestamps,ax: [ax.axvspan(timestamp, timestamp + 0.2, **{'color': 'k', 'alpha': 1, 'lw': 0}) \
for timestamp in timestamps],\
'Optogenetics': lambda timesta... |
4240e337de6cec4f6c33175852bc15b3d84d38344f703f814651ca5c39b78def | Python | 2,331 | 55 | #!/usr/bin/env python
# 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
#... |
02c3585811e78dda8f63b0e5a4946b095b04e52db7e288cdbec77d21f87c7572 | Python | 2,332 | 69 | from __future__ import annotations
from dataclasses import dataclass
from typing import Optional
from aihwkit.nn import AnalogConv2d, AnalogLinear
from aihwkit.simulator.configs import InferenceRPUConfig
from aihwkit.simulator.parameters import IOParameters, UpdateParameters
from aihwkit.simulator.rpu_base import cud... |
2db15165c7d3ad207aa840de03a625aa1c0f2395ac3535b34f3cff430cead493 | Python | 2,333 | 65 | import os
import glob
import re
PACKAGE_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
def get_package_path(*subpaths):
"""Return absolute path inside the cvdproc package."""
return os.path.join(PACKAGE_ROOT, *subpaths)
# Global path constants
FSAVERAGE_DIR = os.path.join(os.path.dirna... |
4074f3827a3b7c1bf25f2f46a03f564c33caa143e1baef7e5e092db6791cab01 | Python | 2,333 | 64 | from brainscore_vision import model_registry
from brainscore_vision.model_helpers.brain_transformation import ModelCommitment
from .model import get_model, LAYERS
model_registry['ReAlnet01']= lambda: ModelCommitment(
identifier='ReAlnet01',
activations_model=get_model('ReAlnet01'),
layers=LAYERS,
regi... |
ad409e66c8710ae00bcf4375fb4282ae592b593e9b1c491ac7286c06a1a14990 | Python | 2,334 | 72 | _base_ = [
'../_base_/models/depthformer_swin.py', '../_base_/datasets/sun_rgbd.py',
'../_base_/default_runtime.py'
]
model = dict(
pretrained='https://github.com/SwinTransformer/storage/releases/download/v1.0.0/swin_large_patch4_window7_224_22k.pth', # noqa
backbone=dict(
embed_dims=192,
... |
09f84263be7ffd3afb6c1873d9dab63c1d56706a416e14cdab925fb21b4ce059 | Python | 2,335 | 57 | #!/usr/bin/env python3
# StrabismusClassification/scripts/plot_calibration.py
import sys
from pathlib import Path
import numpy as np
import matplotlib.pyplot as plt
from sklearn.calibration import calibration_curve
# ─── 将项目根目录加入搜索路径 ────────────────────────────────────────────────
PROJECT_ROOT = Path(__file__).pare... |
1be55038b63bdaabf89221ab9291c67454c8cda27f7ebb356e289590bdb1612d | Python | 2,335 | 63 | _base_ = [
'RepLKNet_upernet.py',
'../_base_/datasets/ade20k.py',
'../_base_/default_runtime.py',
'../_base_/schedules/schedule_160k.py',
]
crop_size = (640, 640)
model = dict(
backbone=dict(
drop_path_rate=0.3,
),
test_cfg = dict(mode='slide', crop_size=crop_size, stride=(426, 426... |
8319955124aece69a79a3c87397d5eae15fe8f2443679fc38a684b031f3e7359 | Python | 2,335 | 72 | import torch
import torch.nn as nn
import torch.optim as opt
import numpy as np
class IT_NN(nn.Module):
def __init__(self, input_s, ln_rate=1e-4, h_size=50, bottleneck_s=15):
""" Implement a convolutional autoencoder to mimic cortex, trained to reconstruct images """
super().__init__()
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.