sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
df7405bd016e9a247b1250951eac9ef9b95439be2e4c636f78bffe542252fe66 | Python | 3,816 | 128 | import json
import argparse
import yaml
import copy
from flair.utils import logging
from flair.algorithms import dict_merge
logger = logging.init_logger()
class Params(object):
"""
Parameters
"""
def __init__(self, params):
self.params = params
def __eq__(self, other):
if not i... |
3d7ca0121a0d35b6501cdca06990ac72b7ed1bb71f8ef7ac43ee2b9767c0028b | Python | 3,817 | 116 | '''
C2H6F
'''
import numpy as np
import sys
def intro():
print("""
SHORT List of potential energy surfaces for C2H6F:
P: potential energy, G: Gradient, D: Nonadiabatic coupling vector
This is listed at the end of description to show the availability.
For example: P/G means both potential energy a... |
ca5d0662b5b0067ce250ec747c84ae9bfda665d6f0d8a054c016305d6128d9d0 | Python | 3,817 | 125 | from os.path import join
from os import makedirs
from imageio import imread
from skimage import measure
import numpy as np
from ..cpn import labels2contour_list as labels2contours
from ...visualization.images import show_detection
import torchvision
__all__ = ['download_bbbc039', 'BBBC039Train', 'BBBC039Test', 'BBBC03... |
f3c545682e58b529f55d4be15414edb41f3e41169b8aba6667c8c1e826e67416 | Python | 3,817 | 101 | """Split-Attention"""
"""
Reference:
- Zhang, Hang, Chongruo Wu, Zhongyue Zhang, Yi Zhu, Zhi Zhang, Haibin Lin, Yue Sun et al. "Resnest: Split-attention networks." arXiv preprint arXiv:2004.08955 (2020)
"""
import torch
from torch import nn
import torch.nn.functional as F
from torch.nn import Conv2d, Module, ... |
e3651e2fdc3e7a7266065dabcb906ee42421c60f05a22bb26c98aeaaf89e96a0 | Python | 3,818 | 87 | """Demonstrates the key steps needed to create new Layer subclasses."""
import numpy as np
import matplotlib.pyplot as plt
from nems import Model
from nems.distributions import Normal, HalfNormal
from nems.registry import layer
from nems.layers.base import Layer, Phi, Parameter
fitter_options = {'options': {'maxiter... |
7c31580ba75fffab9c13a92ce03021301a3e406dfa95b13bc044cdeae7078eba | Python | 3,819 | 128 | from __future__ import annotations
from pathlib import Path
from typing import NamedTuple
from neuralib.util.utils import joinn
__all__ = [
'DataOutput',
'TempDirWrapper'
]
class DataOutput(NamedTuple):
name: str | None
"""cli_io.code"""
directory: Path | TempDirWrapper
"""cli_io.directory(... |
bd556757f68329d54968b13cf38e2219996e4fd4467fbade0000475d0e6a8ee7 | Python | 3,822 | 117 | """
GTF.py https://gist.github.com/slowkow/8101481
Kamil Slowikowski
December 24, 2013
Read GFF/GTF files. Works with gzip compressed files and pandas.
http://useast.ensembl.org/info/website/upload/gff.html
LICENSE
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modif... |
f9945805b886e6d7c0bf80bc9b539451691f66774acd7644cd55c15f4e354c24 | Python | 3,822 | 52 | import logging
from brainscore_core.supported_data_standards.brainio.assemblies import NeuronRecordingAssembly, walk_coords, array_is_element, DataAssembly
from brainscore_vision import data_registry, load_stimulus_set, stimulus_set_registry
from brainscore_core.supported_data_standards.brainio.s3 import load_assembly... |
5f8c5406dd7052dec13ab6e99515ffe41d9ae4b1b26d7cc3f5b0d0396b39c7a5 | Python | 3,823 | 92 | import os
import numpy as np
alg_name = 'graph_saint'
parallel_starts = 16
available_gpus = ['7,4', '7,4']
# args dict
args_dict = {'ds_name': 'node_vessap_roi3_pb_minRadiusAvg',
'log_dir': '../tensorboard_logs',
'device': 1,
'log_steps': 1,
'num_layers': 3,
... |
85fa3657b5eb5011bfaa7d3e35b2866d4ea314972edc8f05daf350e49d43ca61 | Python | 3,823 | 115 | """Download and preprocess data."""
import os
import shutil
import zipfile
import nibabel as nib
import numpy as np
from tensorflow.keras.utils import get_file
PROJECT_DIR = "demos/unpaired_ct_abdomen"
os.chdir(PROJECT_DIR)
ORIGIN = "https://github.com/ucl-candi/datasets_deepreg_demo/archive/abdct.zip"
ZIP_PATH = "a... |
b559585c083ba90364fc7e0bcf879130651e4ad9426be0b2a7e8d77ac94d0cd6 | Python | 3,823 | 93 | import argparse
from itertools import product
import numpy as np
def parse_args():
parser = argparse.ArgumentParser("Make anchors of chromatin interactions into uniform sizes.")
parser.add_argument("input", help="The input bedpe file. Should have at least 7 columns."
+ " ... |
228a53ddaea89423c114022a62f50694a1ae3af6cb7bb04c4ec945b1fe507cbf | Python | 3,824 | 142 | import torch
import torch.nn as nn
class Conv(nn.Module):
"""
A single 2D convolution layer with ReLU activation
Parameters:
in_channels: the number of channels of the input tensor
out_channels: the number of learnable kernels and output layers
Returns:
a tensor of size [ba... |
c186a522a14694c633bf362187dd358c9d2c064b0b76e592d6ffda57fd58d9fb | Python | 3,824 | 114 | from pathlib import Path
from typing import Optional
import click
import numpy as np
import skimage
from simple_mri import SimpleMRI, load_mri, save_mri
from gmri2fem.utils import mri_facemask, nan_filter_gaussian
def convert_T1_to_R1(
T1map_mri: SimpleMRI,
scale: float = 1000,
t1_low: float = 1,
t1... |
c99736798f6606d2a687589387861b2757f0de3228fa72b6d9441d787f732923 | Python | 3,824 | 117 | # 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 agreed to in writing, software
# distributed under th... |
0a0b365cb9977a305a563a39968b67def6ded88e056dfb31270b8a5dd1b0cfda | Python | 3,825 | 100 | """
Module to handle tree data.
Defines a tree and a node class as well as functions for importing data
"""
import os
from lasagna.tree.tree import Tree
from lasagna.utils import data_type_from_string
def parse_file(fname, display_tree=False, col_sep=',', header_line=None, verbose=False):
"""
Import tree da... |
0a680c0eb344dbcb16765fc81e888b553063e00367b61cb1926320c00baeade5 | Python | 3,826 | 88 | # @SNTService snt
# @UIService ui
"""
file: Analysis_Demo_(Interactive).py
author: Tiago Ferreira
version: 20260925
info: Exemplifies how to programmatically interact with a running instance
of SNT to analyze traced data. Because of all the GUI updates, this
approach is _sign... |
5ab4ca801828547315f2c5d7b7d8c9f6501d40f6a928c9e3e045ed59962c0b4c | Python | 3,826 | 130 |
import unittest
import SVMTK
class SubdomainMap_Test(unittest.TestCase):
def test_add_subdomain(self):
smap = SVMTK.SubdomainMap(2)
smap.add("01",2)
a = smap.get_tags()
self.assertEqual(a[0],0)
self.assertEqual(a[1],2)
smap.add("11",3)
a = smap.... |
5b381062bcb0b0fe4d5084d9e0796cb6c8cd6a197c97de0297875080fa3ee02d | Python | 3,827 | 97 | """Logo assets for the GUI, per pipeline.
Three pipelines share one window, so the logo follows the mode — the same way
the tab set and the version label do. Only MEA-NAP has artwork today; the other
two fall back to it, so the GUI is complete now and gains their branding the
moment someone drops a file in.
**To add ... |
d8c16ecf4b42d75e9b97403f60f677cd2e11655fbcd1f98fbaed6601c27be723 | Python | 3,827 | 165 | # 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 Julius Zimmermann, julius.zimmermann[AT]uni-rostock.de
#
# This program is free softwa... |
215b40cb527163dad50a6839482428a6cf71045f1faf9f7b0fb3c06d03d5e5a7 | Python | 3,828 | 124 | #!/usr/bin/env python
"""Direct ParslBackend demo on an HPC compute node: 5-molecule thermo screen.
Must run inside a PBS interactive allocation on Polaris or Aurora::
# Polaris
qsub -I -A <proj> -l select=1 -l walltime=01:00:00 -q debug -l filesystems=home:eagle
# Aurora
qsub -I -A <proj> -l select=1... |
91dd347d9f20932f6505269fa247ad4ada1276f7ad51610eac0efe373143ff2e | Python | 3,828 | 114 | import torch
import torch.nn.functional as F
import torch.nn as nn
import numpy as np
import math
def cosine_beta_schedule(timesteps, s=0.008):
"""
cosine schedule as proposed in https://arxiv.org/abs/2102.09672
"""
steps = timesteps + 1
x = torch.linspace(0, timesteps, steps)
alphas_cumprod = ... |
619b575528733f15503f1d86b9fe2bcd144175ad84b80261fac0cc4e20a89deb | Python | 3,830 | 138 | import contextlib
import os
import sys
import warnings
import pytest
from qtpy import PYSIDE2, PYSIDE6, PYSIDE_VERSION, QtWidgets, _parse_version
from qtpy.QtWidgets import QComboBox
from tests.utils import pytest_importorskip, using_conda
if PYSIDE2:
pytest_importorskip("pyside2uic", reason="pyside2uic not inst... |
9931ee8013c74fbc011c3d3b4e1eec8ee25b0e923c48b77809cc4e6c31f365cc | Python | 3,830 | 151 | """
Registration tools
"""
import nibabel as nib
import numpy as np
from dipy.align.imaffine import AffineMap
from dipy.align.imwarp import DiffeomorphicMap
__all__ = [
"read_affine_mapping",
"read_syn_mapping",
"read_old_mapping",
]
def reduce_shape(shape):
"""
Reduce dimension in shape to 3 if... |
f16d59846daeb6585f013019b492a0118df6100d50204c9af0b40be3f6f7f3df | Python | 3,831 | 109 | """
Checkpointing facility
"""
from pathlib import Path
import torch
class Checkpointer:
def __init__(self,
model,
checkpoint_path,
save_frequency=None,
model_prefix='model',
submodel_names=None):
"""
Description:... |
f8675f6e061a696215b496189ac554c58e8f7ea17bcc5910df388500e6412ff3 | Python | 3,831 | 129 | import unittest
from bx.intervals.cluster import ClusterTree
class TestCluster(unittest.TestCase):
def setUp(self):
self.tree = ClusterTree(0, 0)
def insertpairs(self, pairs):
for i, (s, e) in enumerate(pairs):
self.tree.insert(s, e, i)
def test_merge_case(self):
pai... |
86fc33f878ccf438c573b591244b2341cf88331ba306e6c9b5bcb45d176c0f71 | Python | 3,832 | 105 | #!/usr/bin/python
#
## @file
#
# Conversion of XML node(s) to dictionaries.
#
# Hazen 09/14
#
## gf
#
# Return a function that can be used to extract the value of a field from an ElementTree node.
# Function arguments:
# param: node A ElementTree xml node.
#
# @param field The name of the field (or None).
# @param ... |
7627c7fdaa002179ac7dd965a4a59c3c40f433b5d9cce447a882cf1a5ed9c4ef | Python | 3,833 | 137 | """Run RF correlation analysis and plot RF/retinotopic maps.
This remains a convenient workspace script, but the reusable parts now come
from the public ``waven`` package API.
"""
from __future__ import annotations
import argparse
import os
import sys
from pathlib import Path
from typing import Optional, Sequence
P... |
4edf332c04e08fffee7e8016da3a89a3b35b3c7b1c11b0597cead05e9728d6fe | Python | 3,834 | 118 | # Import Packages, Libraries and Files
from psychopy import visual, core, event, sound, __version__, monitors
import os
from psychopy.hardware import keyboard
import random
# stop the script by pressing escape
def prepare_audio_stim():
sounds = {}
sounds['match']=[]
sounds['nonmatch']=[]
voice_g = ['m... |
b1afac779fa496eb209dc3fe6c224e98984793b88e9a6b416754999c6a902a27 | Python | 3,834 | 116 | '''
C2H6Cl
'''
import numpy as np
import sys
def intro():
print("""
SHORT List of potential energy surfaces for C2H6Cl:
P: potential energy, G: Gradient, D: Nonadiabatic coupling vector
This is listed at the end of description to show the availability.
For example: P/G means both potential energy... |
e38381394ec310a3bcf54a990ec278d6a69572f8f43109038d5f87819d06b6d9 | Python | 3,834 | 80 | #get drug features using Deepchem library
import os
import deepchem as dc
from rdkit import Chem
import numpy as np
import hickle as hkl
import random
import os
def get_chem_feat():
drug_smiles_file=r'Dataset/chemicals.smiles'
save_dir=r'CarcGC_data\drug_graph_feat'
pubchemid2smile = {item.strip().split(',... |
e98d2a3225bf1c1c724c86e0bbdb5ed991d42f36b4bf933e588910ce05f1bfe0 | Python | 3,834 | 111 | #############################################################################
# Copyright (C) 2020-2026 MEmilio
#
# Authors:
#
# 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 License.
# You may... |
08f37d8728045576845d756138090a1101b484e8b0d4c633b10f6672cfa9cc84 | Python | 3,835 | 120 | """
Bicephalous convolutional autoencoder with a
sparse encoder and a dense decoder.
"""
import torch
from torch import nn
from .encoder import Encoder
from .decoder import Decoder
class BiModel(nn.Module):
"""
Autoencoder
"""
def __init__(self,
norm = 'batch',
acti... |
1625dee6486f8e222cb294c8850ed71a8ebbf7ad9e99eefa1bda97801ff70845 | Python | 3,836 | 95 | #!/usr/bin/env python
"""
A serial interface to the W1 Spinning Disk from Yokogawa/Andor.
Jeffrey Moffitt 5/16
Hazen Babcock 5/17
"""
import storm_control.sc_hardware.serial.RS232 as RS232
class W1SpinningDisk(RS232.RS232):
def __init__(self, **kwds):
super().__init__(**kwds)
# Define error co... |
8b910897e5fc82bef94c5274b7b390684c4520573f38b3290d51cb8422457c8a | Python | 3,836 | 95 | """ NormAct (Normalizaiton + Activation Layer) Factory
Create norm + act combo modules that attempt to be backwards compatible with separate norm + act
isntances in models. Where these are used it will be possible to swap separate BN + act layers with
combined modules like IABN or EvoNorms.
Hacked together by / Copyr... |
c1229c691c3d558ea0a7329d322c75b5b17522460c6c84239bad8f2193248fcb | Python | 3,836 | 138 | #!/usr/bin/env python3
import arbor as A
from arbor import units as U
import pandas
import seaborn
import sys
try:
from bluepyopt import ephys
except ImportError:
print("Please install bluepyopt to run this example.")
exit(-42)
# (1) Read the cell JSON description referencing morphology, label dictionar... |
eccae3c51dc53294df89df4eaa622144f6c539cb98000899ff22bcdd5d9eb792 | Python | 3,838 | 77 | #!/bin/python3
###########################################################################################
### Runs Arbor simulations of a single current-based synapse that undergoes early- and ###
### late-phase plasticity. Averages over batches, each with a certain number of trials. ###
############################... |
15d497e1afc1a5d932c20d6636ddaa7206b5bfc941a23f1655a105243484b900 | Python | 3,839 | 128 | import json
import argparse
import yaml
import copy
from flair.utils import logging
from flair.algorithms import dict_merge
logger = logging.init_logger()
class Params(object):
"""
Parameters
"""
def __init__(self, params):
self.params = params
def __eq__(self, other):
if not i... |
7cc272c135e254abf79a0340a02c4e743678b081f43aa45cffc6324c35ebf647 | Python | 3,839 | 118 | import logging
import re
from pathlib import Path
from typing import Optional
import pandas as pd
from brainways.project.info_classes import SliceInfo
from brainways.utils.cell_detection_importer.cell_detection_importer import (
CellDetectionImporter,
)
class QupathCellDetectionsImporter(CellDetectionImporter):... |
bcdbfc05d4dbc4beb6d2c4b8c45b91321b10feb73d57a351d395e7dd303c8c07 | Python | 3,840 | 102 | import pandas as pd
import numpy as np
def make_1d_overlap_data(treatment_bounds=(0, 75),
control_bounds=(25, 100)):
"""Generate 1d overlap data with integer covariates
Args:
treatment_bounds (tuple, optional): Bounds for covariates in treatment
group. Defaults to... |
607cc92e9323fe42a5db1a29d970ecca6224ea245264abd4bb3d4ef75232f192 | Python | 3,841 | 89 | import numpy as np
from scipy import ndimage
def lcn(image, sigmas=(12, 12)):
""" Local contrast normalization.
Normalize each pixel using mean and stddev computed on a local neighborhood.
We use gaussian filters rather than uniform filters to compute the local mean and std
to soften the effect of e... |
800a76bcb045f35372c35a91e069b0d662e78cdbcb843c6477483f86b74fbaa9 | Python | 3,842 | 51 | '''
Quick script to run encoding analysis over
all subjects in learning task.
All options available to `subject_rerp_mt1.py` can
be passed to this script.
NOTE: Running these analyses with `s_bsl=llm` (default)
requires that w2v2 activations have been extracted, pro-
jected and evaluated. Please see:
`audio_w2v2... |
8833fce73d846d452dc685e3d6d4742213adacc321b9a9b59df5f51bc59edbd1 | Python | 3,843 | 139 | import math
import matplotlib.pyplot as plt
import pandas as pd
from AFQ.viz.utils import COLOR_DICT, display_string
__all__ = ["visualize_tract_profiles"]
def _plot_tract(ax, df, tract_name, metric, color, label=None):
sub = df[df["tractID"] == tract_name].sort_values("nodeID")
if sub.empty:
retur... |
9efa7e94cf4c1dd88fabb50c6a28b54a89243ad2cc77a874aaf5e68ac61e5142 | Python | 3,843 | 143 | # -*- coding: utf-8 -*-
import numpy as np
from scipy.linalg import svd
def _fit_circle_2d(x, y, dist_w):
"""
Least square for circle fitting in 2D.
Parameters
----------
x: np.ndarray
x coordinates
y: np.ndarray
y coordinates
dist_w: np.ndarray
Radius. Allows for ... |
b432cdb9ade2014edb653d602508df1116baa1927c193bcd0819bc256f542e5d | Python | 3,843 | 117 | from pathlib import Path
from snakemake.logging import logger
import wbuild
import copy
def returnPath(path, str_=True):
return str(path) if str_ else Path(path)
def checkFileExists(files):
"""
:param files: single filename or iterable of filenames
:return: list of existing files
"""
files =... |
5f904dd543006dea9eabf76ab6a7f35c1206b10e982c160cc4b58e1f96819348 | Python | 3,845 | 99 |
# # by Shaoxuan Yuan at 2024/04/22
# import cv2
# import os
# from albumentations import HorizontalFlip, Rotate, Compose, ElasticTransform, CoarseDropout
# # 数据增强的变换序列
# def get_transforms():
# return Compose([
# HorizontalFlip(p=0.5),
# Rotate(limit=45, p=0.5),
# ElasticTransf... |
fa767dfbd2830bf664edb1feb1d9fa762bfa2bf0e9d08c6d90fb781d100d0416 | Python | 3,845 | 83 | 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... |
eda8d38b5e50f7993300a4aa4474f007d168b7896e6dcf5aed58dca36abdae89 | Python | 3,846 | 92 | import torch.nn.functional as F
from torch import nn, Tensor
import torch
import pdb
def pytorch_cos_sim(a,b):
"""
Computes the cosine similarity cos_sim(a[i], b[j]) for all i and j.
:return: Matrix with res[i][j] = cos_sim(a[i], b[j])
"""
if not isinstance(a, torch.Tensor):
a = torch.tens... |
09f5e586133770df435980047ca4db707ca016132d8933447e15146d484a1ad6 | Python | 3,847 | 100 | import os
from argparse import ArgumentParser
import numpy as np
import torch
import torch.nn.functional as F
from Functions import generate_grid_unit, save_img, save_flow, transform_unit_flow_to_flow, load_4D, imgnorm
from miccai2020_model_stage import Miccai2020_LDR_laplacian_unit_add_lvl1, Miccai2020_LDR_laplacian... |
510f49b313b9af96f4d2721d8e1e98c370601320a675a7e2354ebb1a5fccaddb | Python | 3,847 | 90 | import numpy as np
import pandas as pd
import scripts.DigitalCellSorter as DigitalCellSorter
import os
import time as tm
import rpy2.robjects as robjects
def run_DigitalCellSorter(DataPath, LabelsPath, CV_RDataPath, GeneListPath, OutputDir, GeneOrderPath = "", NumGenes = 0):
'''
run DigitalCellSorter
... |
5fee2847e40b766a256bc25b412c0a5ac80ee85c2587d237ac126ee15bf7bfff | Python | 3,847 | 97 | import jax
import jax.numpy as jnp
import matplotlib.pyplot as plt
import os
import plot_utils
from matplotlib.colors import rgb2hex
jax.config.update("jax_default_matmul_precision", "high")
plt.rcParams["font.sans-serif"] = ["DejaVu Sans"]
plt.rcParams["font.family"] = "sans-serif"
plt.rcParams.update({
"fo... |
427a15ca2ee53580811e324f59d8b511c6f9a848464644ea069fc03599322c2e | Python | 3,848 | 85 | # This file is part of connectome-manipulator.
#
# SPDX-License-Identifier: Apache-2.0
# Copyright (c) 2024 Blue Brain Project/EPFL
import os
import numpy as np
import pytest
import re
from bluepysnap import Circuit
from numpy.testing import assert_array_equal
from scipy.sparse import csc_matrix
from utils import TE... |
189240bed3ded8bedab9f7ca9b9d68f703d5be9255d8eec1ce139fbf03070038 | Python | 3,849 | 107 | import os
import numpy as np
import pandas as pd
import time as tm
from sklearn.neighbors import NearestCentroid
import rpy2.robjects as robjects
def run_NMC(DataPath, LabelsPath, CV_RDataPath, OutputDir, GeneOrderPath = "", NumGenes = 0):
'''
run baseline classifier: NMC
Wrapper script to run... |
5f37d530e9acaef43b1270ea190d19c2b717ed5632d1664cf3d1444a8e97ccf4 | Python | 3,850 | 89 | """Reading a finished run's per-recording acquisition rates back off disk.
CAT-NAP takes the frame rate from each recording's own ``ops.npy`` rather than
from a setting — which is what MATLAB does too (``suite2pToAdjm.m`` assigns
``Params.fs`` from the file and discards whatever the GUI held). The
consequence is that ... |
c3e624752d025889e6f41a3bf202144307ee5c1892b781e0b956adcad536491e | Python | 3,850 | 150 | # -*- coding: utf-8 -*-
__author__ = "Joaquim Viegas"
""" JQM_CV - Python implementations of Dunn and Davis Bouldin clustering validity indices
dunn(k_list):
Slow implementation of Dunn index that depends on numpy
-- basec.pyx Cython implementation is much faster but flower than dunn_fast()
dunn_fast(points, l... |
0aeea479f4ec3f9217e44bd58ca422e0b70633486f7a4aba9db342a49f26726f | Python | 3,851 | 106 | import os
import numpy as np
import pandas as pd
import time as tm
from sklearn.svm import LinearSVC
import rpy2.robjects as robjects
def run_SVM(DataPath, LabelsPath, CV_RDataPath, OutputDir, GeneOrderPath = "", NumGenes = 0):
'''
run baseline classifier: SVM
Wrapper script to run an SVM clas... |
22d5f57b39000d80733000ce10859aecd6c5b220b935a0bded98e689f270080d | Python | 3,851 | 92 | from .util import Partition, new_vectors
import numpy as np
import datetime
import concurrent.futures
# build a little one‐arg function that “remembers” both features & median_function
def make_compute_median(feats, median_fn):
def _compute(cl):
return median_fn(feats[cl], axis=0)
return _compute
def... |
a5b3ec56407065a09694ca9e44e64109104869359e0b203b91debfddf96d78c8 | Python | 3,851 | 121 | from langchain_core.messages import AIMessage
from chemgraph.graphs.single_agent import route_report_tools, route_tools
def test_route_report_tools_routes_to_tool_before_report_exists():
state = {
"messages": [
AIMessage(
content="calling report tool",
tool_cal... |
0837ea0c8d5c12dbf46f3688c23498c31171e7db6abf2a9f2fe1a7094e35846f | Python | 3,853 | 96 | import torch
from featurevis.utils import varargin
class Ensemble():
""" Average the response across a set of models.
Arguments:
models (list): A list of pytorch models.
readout_key (str): String identifying the scan whose neurons will be outputted by
the model
eye_pos (t... |
3b4d13dac80a0bed2852585848acb8016051c1157ab3ac69a22c125de08e7dc4 | Python | 3,853 | 119 | """
Use this script to create required synchronization ('sync') files, which define the relationship
between frames across different cameras over time.
Use this script if you know your camera frames are triggered and reliably synchronized.
If your cameras are not natively synchronized, but you can collect timesta... |
2e8631a096649454c0dc40fc38324008224d74e283d4d82f9da14574f95cc072 | Python | 3,854 | 102 | import torch
from utils import common_functions as c_f
from utils.module_with_records import ModuleWithRecords
class BaseReducer(ModuleWithRecords):
def forward(self, loss_dict, embeddings, labels):
self.reset_stats()
assert len(loss_dict) == 1
loss_name = list(loss_dict.keys())[0]
... |
610843617ad986c04c54b637037e971afb2902d598661a78f87f38b23bf78b0b | Python | 3,854 | 103 | """End-to-end CAT-NAP run with cell-type subnetwork analysis on the example data.
Run from the repo root::
uv run python python/run_catnap_subnetwork_demo.py [--groups E/I|columns] [--out DIR]
Uses the gitignored ``local/example2pdataWCellTypes`` dataset (the same one
``python/test_pipeline_catnap.py`` checks pa... |
672ab642c32f18d0c61b3f5732e6a6154eb8d1826231197ecd49c0a2e7f88451 | Python | 3,854 | 149 | #!/usr/bin/env python3
#
# Make a plot using matplotlib
#
# F. Nedelec, 13-15 November 2013
#
# How I installed matplotlib in Jan 2015 (Mac osx 10.10):
#
# brew install python3 --framework
# pip3 install numpy
# pip3 install nose
# pip3 install matplotlib
#
# Alternative:
# git clone git://github.com/matplotlib/matplot... |
a9fa820c078c8e60824b0a2e0a534a05d6ee07a1d6c2f1db6e1c2f808e83046a | Python | 3,854 | 110 | from tweepy import Client
from collections import namedtuple
import datetime
import logging
from platform import python_version
import time
import warnings
import requests
import tweepy
from tweepy.auth import OAuthHandler
from tweepy.errors import (
BadRequest, Forbidden, HTTPException, TooManyRequests, Twitter... |
b46122abe16b29e9bc51eafa8bc46f041a29805b78f056a513706f973a64bb85 | Python | 3,854 | 75 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'storm4-misc.ui'
#
# Created by: PyQt5 UI code generator 5.7
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjec... |
cb1264932e765c5c65107e52d699aaed7cd5bc25808350e51dd7b4e69cfd852d | Python | 3,854 | 102 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Generate a linear transformation matrix from the registration of 2 tractograms.
Typically, this script is run before scil_tractogram_apply_transform
For more information on how to use the various registration scripts, see the
doc at:
https://scilpy.readthedocs.io/en/l... |
cca7fb55d3e350be2816cc0532593fda896b7dee3a0423c2828a699ffee23bea | Python | 3,854 | 107 | # -*- coding: utf-8 -*-
import numpy as np
import pytest
from scilpy.tracking.utils import (compute_max_sf_amplitude,
compute_sf_threshold_mask)
from scilpy.tests.arrays import fodf_3x3_order8_descoteaux07
def test_compute_max_sf_amplitude():
# Test with SH data
max_sf = c... |
18884c5a5c6c88ad407979c929ee67dd59be784d4530d88f5dcf937556df0cb0 | Python | 3,857 | 121 | '''
C2H2O
'''
import numpy as np
import sys
def intro():
print("""
SHORT List of potential energy surfaces for C2H2O:
P: potential energy, G: Gradient, D: Nonadiabatic coupling vector
This is listed at the end of description to show the availability.
For example: P/G means both potential energy a... |
364087e1d6c30d28305ed6000fc1ad788349e6e6891380c5a4ba028e7c870cae | Python | 3,857 | 92 | import os
import time
import nibabel as nib
import numpy as np
import scipy.io as sio
hcp_dir = '/path/to/megdata/and/results/';
parcellationDir = ('/path/to/SchaeferParcellation/')
# load subj list
subjList = sio.loadmat(os.path.join(hcp_dir, 'myMEGList.mat'))['myMEG']
subjList = [subjList[i][0][0][4:] for i in ran... |
2127af43d05c3a88289e21726818bcbf7bbfe4af4afd7e03fad4e84fda59f970 | Python | 3,858 | 121 | """Module to evaluate LLM performance on tool-calling workflows."""
import pprint
import json
import datetime
import argparse
from langchain_core.utils.function_calling import convert_to_openai_function
from chemgraph.agent.llm_agent import ChemGraph
from chemgraph.utils.get_workflow_from_llm import get_workflow_from_... |
6645e86bdab2a8be2079c4f48389996c04a30ca9afa355176190cea6c16b2f71 | Python | 3,858 | 110 | # -*- coding: utf-8 -*-
from collections.abc import Iterable
from itertools import chain
from flair.parser.utils.alg import kmeans
import torch
from torch.nn.utils.rnn import pad_sequence
from torch.utils.data import DataLoader, Dataset, Sampler
class TextDataLoader(DataLoader):
def __init__(self, *args, **kwa... |
8fcbe05b16d4b72b72b54425ad1cc1480ee93166c2e7cee47aa1c4ecde31b45b | Python | 3,858 | 109 | import numpy as np
from argclz import AbstractParser
from neuralib.locomotion import CircularPosition
from neuralib.plot import plot_figure
from rscvp.behavioral.util import get_binned_velocity
from rscvp.behavioral.util_plot import plot_velocity_heatmap
from rscvp.util.cli import TreadmillOptions
from stimpyp import ... |
cbf1c68b0fa3881b8ecedb88c56992288588eb2b93b88bcac2638be2b0743e1b | Python | 3,858 | 122 | from typing import Optional
import click
import panta_rhei as pr
import simple_mri as sm
import dolfin as df
import numpy as np
import scipy
import tqdm
from dolfin import inner, grad
from glymphopt.utils import with_suffix
def petsc_to_scipy(petsc_mat):
m, n = petsc_mat.getSize()
indptr, indices, data = pets... |
cfacf464d358d1e1ffef69320bb6f99b941774d49694a058ae20892da64aa221 | Python | 3,859 | 107 | # -*- coding: utf-8 -*-
import numpy as np
from dipy.data import get_sphere
from dipy.reconst.shm import sh_to_sf_matrix
from scilpy.reconst.fodf import get_ventricles_max_fodf
from scilpy.reconst.utils import find_order_from_nb_coeff
from scilpy.tests.arrays import fodf_3x3_order8_descoteaux07
def test_get_ventricl... |
7dbc5ed429b66fde025202dcfd881ff6c1621ce0f924ac5f02504ed7b1e16184 | Python | 3,860 | 94 | from src.wrappers.OsipiBase import OsipiBase
from super_ivim_dc.source.Classsic_ivim_fit import IVIM_fit_sls
import numpy as np
import warnings
class TCML_TechnionIIT_SLS(OsipiBase):
"""
TCML_TechnionIIT_lsqlm fitting algorithm by Angeleene Ang, Moti Freiman and Noam Korngut, TechnionIIT
"""
# I'm thin... |
30523ba9ffe920f96a31b13cb6332b7e0247427478b235848772b5057e883acd | Python | 3,861 | 117 | """Perform multidimensional scaling (MDS) jointly on NSD-synthetic's fMRI
responses of all subjects and of all vertices with ncsnr above a threshold.
Parameters
----------
subjects : list
List of the used NSD subjects.
zscore : int
Whether to z-score [1] or not [0] the fMRI responses of each vertex across
the trial... |
cfb64e20658274b428ddac534e71014589b41839ed59a129a558de088dbba8e7 | Python | 3,863 | 117 | import numpy as np
import pytest
import nelpy as nel
def test_decode1D_simple():
ratemap = np.array([[0.1, 1.0, 0.1]])
# Events at times that will bin into 3 bins
ea = nel.EventArray([[0.2, 1.2, 2.2]], fs=1)
bst = nel.BinnedSpikeTrainArray(ea, ds=1)
posterior, cum_posterior_lengths, mode_pth, mea... |
bf393b2d8418eefeb1ba7348c7a16ff8a20f416ffad7fcb7bbc39e58f669853c | Python | 3,864 | 115 | #!/usr/bin/env python3
import argparse
import os
import nibabel as nib
import numpy as np
import SimpleITK as sitk
def nifti_warp_to_h5(input_nifti: str, output_h5: str, vector_image: str = None):
"""
Convert a 4D NIfTI warp field (X, Y, Z, 3) to an ANTs-compatible HDF5 transform.
Parameters
-------... |
bf5ab298bccd57d41cd7f961da29e5620622c38d8092eb37070aa604586d8284 | Python | 3,864 | 120 | import os
import numpy as np
import h5py
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import scipy.signal
import pywt
# === Paths and Parameters ===
folder_path = r'D:\example'
rec_name = 'example'
filename = os.path.join(folder_path, f'{rec_name}.h5')
dataset_name = 'Raw-0.0'
col_idx = 1
# ... |
0437b310162b5897c68f1513904e4f998216b181129be17876782ce143934de8 | Python | 3,865 | 47 | import numpy as np
import json
import inspect
import pytest
import arborNetworkConsolidationMultiComp as anc
from arbor import units as U
from outputUtilities import redText, cyanText, \
setDataPathPrefix, getDataPath
epsilon = 6e-7 # similar to default tolerance value used by pytest.approx... |
ba987da25ec4107a8cf4cc405b741f5e01f56618a75970ca2674bd75f5e0b39f | Python | 3,865 | 114 | # -*- coding: utf-8 -*-
# python standard library inputs
import os
# external inputs
import nibabel as nb
from scipy.stats import zscore
from nipype.interfaces.afni.preprocess import Bandpass
from nipype.interfaces.afni.utils import TStat, Calc
# local inputs
from ..io.get_filename import get_filename
def get_alff... |
0a7efa9b00da1ed2c385d5176d10322d87b9fbd222574e84ae840fd9e1e5f630 | Python | 3,866 | 99 | import pytest
import numpy as np
from nems.tools.arrays import (
broadcast_axis_shape, broadcast_axes, broadcast_dicts, concatenate_dicts,
apply_to_dict
)
class TestBroadcast:
x = np.random.rand(100, 1, 2, 3)
y = np.random.rand(1, 100, 3, 2)
def test_axes_shape(self):
shape = broadc... |
ed38b73903f5110fe05544c0759bd397a7941f3f6b823da0eb740d9641b30002 | Python | 3,866 | 107 | """
Module for estimating parcellations and functional profiles
Author: Bassel Arafat
"""
import torch as pt
import numpy as np
import OptimalBattery.evaluate as ev
import OptimalBattery.util as ut
######################### Parcellation U Estimation #########################
def estimate_Us(Y, V, method='cos_angl... |
04b2862201059f6af7e26fc8a34328d99b1df2d2c3bd524d8254b3299f6cde75 | Python | 3,867 | 61 | from dtiplayground.dmri.common.tools.base import ExternalToolWrapper
class FiberPostProcess(ExternalToolWrapper):
def __init__(self,binary_path= None, **kwargs):
super().__init__(binary_path, **kwargs)
self.binary_path=None
if binary_path is not None:
self.binary_path=binary_pat... |
4346383db6a3bf55714963e8f1b813c67019fc60b649067ee2bdc23b4d00a0af | Python | 3,867 | 114 | from torch.utils.data import Dataset, DataLoader
from pandas import DataFrame
from torch import tensor, Tensor
class Data_model(Dataset):
"""
A custom dataset class for handling genotype-phenotype data in machine learning models.
Attributes:
substitutions (List[List[str]]): List of unique mutation... |
7fb870627d177b47a657cbede0f044f7941248cf4f0372ea4e7b6ecc8065c798 | Python | 3,867 | 112 | import os
import sys
import numpy as np
import time
import torch
# add path
project_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if project_dir not in sys.path:
sys.path.append(project_dir)
def fetch_knn_points(point_cloud, knn_indices):
b, n, k = knn_indices.shape
knn_indice... |
213652e07d1e9337bc1b87bb5efd61f65af00f15359a659ce04498830ec78452 | Python | 3,869 | 112 | #############################################################################
# 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... |
2a5c8b44924e122214f5a25917d556bd95983a872aa2f6518b3388602d6b37e8 | Python | 3,869 | 114 | from torch_geometric.data import Data
from torch.utils.data import Dataset, DataLoader
from utils import *
import numpy as np
import torch
import scipy.sparse as sp
class Data_class(Dataset):
def __init__(self, triple):
self.entity1 = triple[:, 0]
self.entity2 = triple[:, 1]
... |
665d4e634efcda6a722ebdfb1e9726541cafaaafd0e6bbdef2fa2dbac96b568e | Python | 3,869 | 68 | import pandas as pd
import gzip
import argparse
import os
import matplotlib.pyplot as plt
import numpy as np
def read_tsv_gz(file_path):
assert os.path.exists(file_path), f"File not found: {file_path}"
with gzip.open(file_path, 'rt') as f:
return pd.read_csv(f, sep='\t')
def read_mtx_gz(file_path):
... |
758cbb662f14e4a46f481bfe100f820d709e3f5e6ed7fdaf4f480aab5bc89e43 | Python | 3,870 | 113 | # MIT License
# Copyright (c) Kentaro Wada
from __future__ import annotations
import base64
import io
from typing import Final
import numpy as np
import PIL.ExifTags
import PIL.Image
import PIL.ImageOps
from numpy.typing import NDArray
from PySide6 import QtGui
def img_data_to_pil(img_data: bytes, /) -> PIL.Image.... |
84ec2c123a4395741be2c48c777db942672c7b64f16a862361615edeb6c2055c | Python | 3,870 | 114 | # -*- coding: utf-8 -*-
import itertools
import numpy as np
NB_FLIPS = 4
ANGLE_TH = np.pi / 6.
# directions to the 26 neighbors.
# Preparing once rather than in compute_fiber_coherence, possibly called many
# times.
ALL_NEIGHBORS = np.indices((3, 3, 3))
ALL_NEIGHBORS = ALL_NEIGHBORS.T.reshape((27, 3)) - 1
ALL_NEIGHB... |
629c08db2cdac65e37c5da80e12280d7e755b4e0d0b9b36c646a249fe1e663ff | Python | 3,871 | 59 | """Reconstruct control evidence without assigning undocumented harvest days."""
import json,re
from pathlib import Path
import pandas as pd
from bs4 import BeautifulSoup
from src.acquisition.download import ROOT
def main():
base=ROOT/'data/raw/schmidt'
def blobs(p): return {r['path']:r['sha'] for r in json.lo... |
00c56c5cbeb8da2648e8b5e181a45225b0473ab65280c11d6b021c12dd914ac8 | Python | 3,872 | 121 | from functools import partial
import numpy as np
import lightning as L
import os
from datasets import load_dataset
from torch.utils.data import DataLoader, Dataset, Subset
from transformers import AutoImageProcessor
class DatasetWrapper(Dataset):
def __init__(self, dataset, transform):
super().__init_... |
9428cd74c6b8850158ce4ed4a78ac3d15e3410112621ab4d832a435c0095b5c7 | Python | 3,872 | 125 | """
Read and plot motion traces
"""
import ants
import os
import glob
import numpy as np
import pandas as pd
def my_ants_affine_to_distance(affine, unit):
dx, dy, dz = affine[9:]
rot_x = np.arcsin(affine[6])
cos_rot_x = np.cos(rot_x)
rot_y = np.arctan2(affine[7] / cos_rot_x, affine[8] / cos_rot_x)... |
f712ea78eafcf6478a5ef9a02c98653ebd174b8878ca2ddacf0abb57ee84f2b1 | Python | 3,872 | 96 | import os
from nipype.interfaces.base import BaseInterface, BaseInterfaceInputSpec, TraitedSpec, traits, TraitedSpec, CommandLineInputSpec, CommandLine
class FilterExistingInputSpec(BaseInterfaceInputSpec):
input_file_list = traits.List(desc="List of input files to filter", mandatory=True)
class FilterExistingOut... |
a5eb8fac5c3a47a22d6fe829cf94318137c740a7732df735d42194d240d4e54e | Python | 3,873 | 146 | import os
import json
import torch
import numpy as np
from custom.network import SETresnet50
import matplotlib.pyplot as plt
from matplotlib import gridspec
from tqdm import tqdm
from preprocess import get_preprocess_infer
def patch_attention(m):
forward_orig = m.forward
def wrap(*args, **kwargs):
... |
371591dce833f934e3fec13c07dacbbc0c2dd7b60501b346e65b6d812ca1f7f9 | Python | 3,874 | 120 | #!/usr/bin/env python
"""
File dialog that allows for regex filtering.
Hazen 10/18
"""
import re
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
import storm_control.steve.qtdesigner.qt_regex_file_dialog_ui as qtRegexFileDialogUi
def regexGetFileNames(caption = "Select File(s)", directory = None, extensions ... |
69bb2319941abd219b5073ef42294b08873cbc6d321b9dfb9131dbd17a13ec96 | Python | 3,874 | 98 | """
Creates a plugin that is composed of a new window with a pyqtgraph PlotWidget
On this graph we plot an x-axis cross-section of the image at the level which the
mouse cursor is at.
"""
from PyQt5 import QtGui, QtWidgets
from PyQt5.QtWidgets import qApp
from lasagna.plugins.lasagna_plugin import LasagnaPlugin
from ... |
f2973be40bed78ac154dfaac58c30a6fd02548df16b291c784a92be46deb2309 | Python | 3,874 | 132 | # Copyright (C) CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT
from __future__ import annotations
from enum import Enum
from functools import cached_property
import attrs
from django.conf import settings
from django.db import models
from cvat.apps.engine.models import Project, TimestampedModel
from cvat.apps.... |
9b7ad732f2a98644af1f396cb80ce9e64690aaf0adf51604352f97210f4447cf | Python | 3,875 | 122 | import json
from langchain.schema.messages import AIMessage
import logging
from chemgraph.utils.logging_config import setup_logger
logger = setup_logger(__name__)
def get_workflow_from_log(file_path: str) -> dict:
"""Convert a run_logs file to a workflow dictionary for evaluations.
This function reads a JSO... |
70e6786831e10734c5adc3d80a86cbfe0f8834e6017d29dd71c8affd6869bb25 | Python | 3,876 | 108 | import os
from sys import argv
from pathlib import Path
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 = "", Nu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.