sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
8395cd5215a75b1d3f0735a5e4d90dc995e5af13a7307ac621cc8b006c2f8686 | Python | 2,843 | 81 | # 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, ... |
8b519798cee0f1a3dbbf9acaaefa78bf910c166aab391f842d11b1e4a95fd729 | Python | 2,843 | 79 | """
Code to calculate IVIM maps
Segmented fitting approach
First fit D using a WLLS
"""
import numpy as np
import statsmodels.api as sm
import scipy
def ivim_biexp(bvalues, D, f, Dp, S0=1):
return (S0 * (f * np.exp(-bvalues * Dp) + (1 - f) * np.exp(-bvalues * D)))
def segmented_IVIM_fit(bvalues, dw_data, b_cu... |
26abe704e643abd94596667a59d50ca6e3dcbaf08de97db8ccacede70dbb7fb6 | Python | 2,844 | 74 | # 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 ARM64, LOGGER
from ultralytics.utils.checks import check_requirements
from .base import BaseBackend
class PaddleBackend(Bas... |
9ef036236f7d05abb30e6e4310576651131109c7b5c5096edc335ab1ab98435d | Python | 2,844 | 101 | """Test QtSql."""
import sys
import pytest
from qtpy import PYQT5, PYQT_VERSION, PYSIDE2, PYSIDE_VERSION, QtSql
@pytest.fixture
def database_connection():
"""Create a database connection"""
connection = QtSql.QSqlDatabase.addDatabase("QSQLITE")
yield connection
connection.close()
def test_qtsql()... |
cbb7ec248d0fb0054998f5e6f835fe864314e391c21f6c52a7caada26e7e7b96 | Python | 2,844 | 98 | from collections.abc import Sequence
from copy import deepcopy
from unittest.mock import patch
import numpy as np
import pytest
import torch
from eir.data_load.data_preparation_modules import prepare_omics
def test_prepare_genotype_array_train_mode():
test_array = torch.zeros((3, 100), dtype=torch.uint8).detach... |
9f964f0a63a8155c6645fa0ed5be9ea568e86957ad8cdebb9241d70f60ecd7e0 | Python | 2,845 | 81 | import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import torch
from model.Ouroboros import Ouroboros
from utils.chem import cal_SAScore
if __name__ == '__main__':
# check GPU
print('CUDA available:', torch.cuda.is_available()) # Should be True
print('CUDA capability:', to... |
e424faeb4f0166fbda699ec92614d44c67b23b31bcc5d7bcbaa69f427071a35a | Python | 2,845 | 82 | # This file was automatically generated by SWIG (http://www.swig.org).
# Version 4.0.2
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info as _swig_python_version_info
if _swig_python_version_info < (2, 7, 0):
raise Runtime... |
2a7b28877b842135890100b363a56fd8712eaab437df5ab5ece1baa2efbb6682 | Python | 2,846 | 97 | # Copyright 2014-2015 Numenta Inc.
#
# Copyright may exist in Contributors' modifications
# and/or contributions to the work.
#
# Use of this source code is governed by the MIT
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/MIT.
import datetime
import pandas
import unittest
fr... |
c140cdc2eceb21630b3bb9b1c8d21c8676823c24f8b1259f6f31a44131fcc3ad | Python | 2,846 | 85 | import os
import time
import torch
import random
import numpy as np
import ray
import click
import EIANN.utils as ut
@ray.remote(num_gpus=0.5, num_cpus=1)
def run_seed(seed_idx, network_config_file_name, data_dir):
network_seed = 66049 + seed_idx
data_seed = 257 + seed_idx
ut.set_all_seeds(seed=network_s... |
d36eae902493ec084d5e9f666d1c61821907df2186b34ba2fbc2fdb47df9b78b | Python | 2,846 | 92 | import os
os.environ["POLARS_MAX_THREADS"] = str(snakemake.threads)
import pandas as pd
import sys
import math
import polars as pl
coverage_within_n_sd = snakemake.params.coverage_within_n_sd
MIN_coverage = snakemake.params.min_coverage
def get_min_coverage(median):
sd = math.sqrt(median)
mmin = median - c... |
7ea7e99ed6fd45ddebcfd6a10eee8d3e53996994baeeffc6d3656178fe4bff47 | Python | 2,847 | 93 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from random import sample, randint
from progress.bar import Bar
import os
import loader
import net_models
from datetime import datetime
import numpy as np
import pandas as pd
import pickle
import matplotlib.pyplot as plt
import rsatoolbox
import fire
def main(model="co... |
90394898d839108842aecda41c7fc82510c6fa807192d76354c1906d5e0d2f0f | Python | 2,847 | 115 | #!/usr/bin/env python
#
# scan.py
#
# copyright F. Nedelec and S. Dmitrieff 2007--2018
"""
Execute specified command in given directories, sequentially using a given number of processes
Syntax:
scan.py command directory1 [directory2] [directory3] [...] [jobs=N]
Example:
scan.py 'play image' r... |
1a419f1bd9003f2af2c8fadcf37257bb63b654beccea21d047fba9375c1056c1 | Python | 2,848 | 78 | import numpy as np
import numba
from tqdm import tqdm
from sklearn.feature_selection import mutual_info_regression
from joblib import Parallel, delayed
import time
from typing import Optional, Tuple
import logging
class MutualInformationCalculator:
"""Calculate mutual information between genes."""
@stati... |
82df94109a7ecfba21950ad9cac567c14d27230907d10d10f8feae2425e1252f | Python | 2,848 | 81 | #! /usr/bin/env python
"""Generate a scaled point cloud xyz file from a labelled mrc map
usage: mrc2xyz input.mrc output.xyz -l label_int"""
__author__ = "Benjamin Barad"
__email__ = "benjamin.barad@gmail.com"
__license__ = "GPLv3"
import click
import glob
import mrcfile
import numpy as np
import pandas
@click.com... |
a9e64923e4eb931e50702662a56c57a078c9c48064977bc02735cb1321a3ed62 | Python | 2,848 | 67 |
import os
import numpy as np
from PIL import Image
import torch.utils.data as data
import torchvision.transforms as transforms
from sklearn.neighbors import NearestNeighbors
import datasets.dataset_utils as dataset_utils
class TestDataset(data.Dataset):
def __init__(self, dataset_folder, database_folder="databa... |
c98016e1ca0af1dc7bb085c6c00486ad8f6187cc234bf89767bf82f234ac5cce | Python | 2,848 | 91 | from typing import Literal
import numpy as np
from argclz import AbstractParser, argument
from argclz.dispatch import Dispatch, dispatch
from neuralib.plot import plot_figure
from neuralib.plot.colormap import insert_colorbar
from rscvp.util.cli import TreadmillOptions
from rscvp.util.cli.cli_camera import CameraOpti... |
d1c8752f8b07966637e29ad8ea043edf3b1664aeeb3ffee1dd91b974e62369d8 | Python | 2,848 | 59 | import unittest
import tests.allow_clipping.test as allow_clipping_test
import tests.alternative_3_splice_site_novel.test as alternative_3_splice_site_novel_test
import tests.alternative_5_splice_site_novel.test as alternative_5_splice_site_novel_test
import tests.darts_model.test as darts_model_test
import tests.fixe... |
4b3adec8fb3cbd9344239a6a60e52c647556663c7d48b10fabfbb2d246e3b8b4 | Python | 2,849 | 71 | import torch
from torch.nn.parallel import DistributedDataParallel as DDP
from ..utils import common_functions as c_f
# modified from https://github.com/allenai/allennlp
def is_distributed():
return torch.distributed.is_available() and torch.distributed.is_initialized()
# modified from https://github.com/JohnG... |
9f6cc9aa90c0030addab930369a39646cccca2def2e32b48bf14b5a13141d92e | Python | 2,849 | 63 | # @String(value="<HTML>This script creates an illustration of a tracing canvas.<br>N.B.: Paths can also be exported as vector graphics<br>using <i>Reconstruction Plotter...</i> or <i>Create Figure...</i>",visibility="MESSAGE") msg
# @String(label="Tracing Canvas", choices={"XY", "ZY", "XZ", "3D"}, style="radioButtonHor... |
e12834befae412e8455fab9791f97a60395d6997217d38ba8ebe190f7b268a14 | Python | 2,849 | 100 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: Vicky
usage: python generateSummaryFiles.py metric_summary
"""
import glob, xlsxwriter, csv, sys, ntpath, os
from shutil import copyfile
metricsPath = 'finalreport/'
summaryPath = 'finalreport/summaries/'
def main(arg1='metric_summary'):
createMetrics... |
654abed6bafa38a3da2ceacace9e29727709026f9ae73318d9da49cfdec18f9f | Python | 2,850 | 82 | #############################################################################
# Copyright (C) 2020-2026 MEmilio
#
# Authors: Martin J. Kuehn, Wadim Koslow, Daniel Abele
#
# Contact: Martin J. Kuehn <Martin.Kuehn@DLR.de>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file exce... |
4a41952d73c1ae886acfa6fbd2fd24a33caf489d75fa1078d74bbe4b5ce7174b | Python | 2,852 | 100 | """Logging utilities."""
import logging
import os
import sys
from contextlib import contextmanager
@contextmanager
def set_logging_level(logger: logging.Logger, level: int) -> None:
"""Temporarily change the logging level of a logger.
Parameters
----------
logger : logging.Logger
Logger to c... |
5cce88fe11d8048679609528254ed9c4dbea84fef1f744dc35dd1787b1ac91c6 | Python | 2,852 | 75 | import numpy as np
import pandas as pd
import scipy.sparse as sp
from scipy.sparse import csr_matrix
from sklearn.cluster import KMeans
from typing import Tuple, Optional
import logging
class ExpressionDiscretizer:
"""Discretize continuous gene expression values."""
@staticmethod
def discretize(adata... |
a6c5b2804ecf0f80a4cb83284c92c08236849135f0a9e9afdcd4ca90a55a6a9a | Python | 2,852 | 69 | """impyute.contrib.compare.py"""
import importlib
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# pylint: disable=too-many-locals, dangerous-default-value
def compare(imputed, classifiers=["sklearn.svm.SVC"], log_path=None):
"""
Given an imputed dataset with la... |
05d371e3582e700ea857c700d1dcbb8674f1ce43f628f1b01f4a9512333291a1 | Python | 2,854 | 81 | from typing import Final, Literal
import pingouin as pg
import polars as pl
from argclz import as_argument
from neuralib.plot import plot_figure
from neuralib.util.verbose import publish_annotation, printdf
from rscvp.statistic.core import StatPipeline, print_var
from rscvp.statistic.sql.util import as_validate_sql_t... |
100a9f6955049ee4a15161b2d0918a989c7044241818cc7ba9014dd2f944df6a | Python | 2,854 | 73 | """
Copyright 1999 Illinois Institute of Technology
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publis... |
64e4522efc61eadc62f833c0ca0f9716cd8b4959bc543a6b6ea16d856bec1014 | Python | 2,854 | 88 | import os
from collections import defaultdict, namedtuple
from datetime import datetime, timedelta
from json import dumps
import numpy as np
import tensorflow as tf
from model import ModelConfig, UNet
from postprocess import extract_amplitude, extract_picks
import pandas as pd
import obspy
tf.compat.v1.disable_eage... |
a65d49165303d627582c2577725d65959bd5675f641cba4926bc6f10238d504d | Python | 2,854 | 90 | #%%
import brainpy as bp
import brainpy.math as bm
import numpy as np
import matplotlib.pyplot as plt
from cann import CANN1D
#%%
#set default ramndom seed for reproducibility
np.random.seed(0)
#set backend to cpu
bm.set_platform('cpu')
num_p = 10
mbar = 0
cann = CANN1D(num=64, mbar=mbar, tau=3, tau_v=144)
vbar = bm.... |
8cd53c3756ac8443748a98e07f169db7e98f6a73ab1b3925835eedaffb64c157 | Python | 2,855 | 95 | """
Classes for char-to-int mapping and int-to-int mapping.
:Author: James Taylor (james@bx.psu.edu)
The char-to-int mapping can be used to translate a list of strings
over some alphabet to a single int array (example for encoding a multiple
sequence alignment).
The int-to-int mapping is particularly useful for crea... |
e038d72e606677bb27afa1ea9b9d2a8d150ab8de58c3ca08832649962ca6b63d | Python | 2,855 | 105 | # MBTR descriptor functions
# Imports
import json
import glob
import numpy as np
import numpy.typing as npt
import ase
import ase.io
import dscribe.descriptors
from modules.build_data.fhi_aims.descriptors.default_settings import (
DEFAULT_MBTR_SETTINGS,
)
from modules.tools.strings import xyz2formula
from modu... |
c54e83cdab5c8fae9f0d3044adf6bbf44f478a17671c1ecc6ea86e7f4146da0f | Python | 2,857 | 84 | import numpy as np
from tqdm import tqdm
id_list=np.load('/data2/whr/lyh/twibot22_baseline/Twibot-22/id.npy')
id_include=(np.load('/data2/whr/lyh/baseline2/Twibot-22'+'/id_include.npy',allow_pickle=True))
id_include=list(id_include.item())
id_list=list(id_list)
train_id=[]
val_id=[]
test_id=[]
# with open(r'/data2/whr... |
dac2a685fdfed300ab668c47ac22c48d39d7675947f05ee843f869dee66017e7 | Python | 2,857 | 96 | from pathlib import Path
import click
import numpy as np
import scipy
from simple_mri import SimpleMRI, load_mri, save_mri
def clean_dti_data(dti: Path, mask: Path, output: Path):
dti_mri = load_mri(dti, dtype=np.single)
dti_mri.data = extend_to_9_component_array(dti_mri.data)
dti = dti_mri.data
mas... |
010c959d511ea375691e53a47a05cf57359169c913742b84371495c81dc9d42a | Python | 2,858 | 71 | import argparse
import logomaker
import glob
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
from os.path import basename
from os.path import join
import utils
'''
- Outputs a multi-page PDF comparing attribution analysis results for all models in ensemble
- One logo (sequence) ... |
077f23caefa1fd2b4b2a99a4aa81b636759a4cc15933518712cd81651817163d | Python | 2,858 | 84 | # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
import logging
import torch
try:
from cc_torch import get_connected_components
HAS_CC_TORCH = True
except ImportError:
logging.debug(
"cc_torch not found. Consider installing for better performance. Command line:"
" ... |
f7a60312b1b31af6ac4c98b0b7ba632f3d32498b4ad78f1c055f2768760e2a41 | Python | 2,858 | 68 | #!/usr/bin/python
#########################################
# Author: Yunjiang Qiu <serein927@gmail.com>
# File: feature_frag2bin.py
# Create Date: 2015-07-07 18:11:28
#########################################
import sys
import argparse
def main():
parser = argparse.ArgumentParser(description='')
parser.add_... |
3081a4b7759dfdb2bf4622059ed9dcd29ac237f8f3a65f4578603af8af907807 | Python | 2,859 | 81 | 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
import pandas as pd
stimuli = []
image_paths = {}
stimuli_directory = 'images'
'''
Dataset Information:
- From Baker 20... |
3e7a65803ed75354c9290c1eaa5a187a67270f39f80b53ea310d18ec38c4ee5a | Python | 2,860 | 98 | import h5py
import os
import yaml
from matplotlib.patches import Rectangle
import matplotlib.pyplot as plt
import numpy as np
DIR = os.path.dirname(os.path.realpath(__file__))
HOME_DIR = DIR.rsplit('/', 1)[0].rsplit('/', 1)[0]
print('> HOME: ', HOME_DIR)
# %% load images
f = h5py.File(DIR + '/llr_regu_shot-retro-2.... |
051b48977468ef4cd9608ec2606365eae560b944e498665cb97cb363c38e0654 | Python | 2,861 | 72 | import torch
from utils import common_functions as c_f
class WeightMixin:
def __init__(self, weight_init_func=None, **kwargs):
super().__init__(**kwargs)
self.weight_init_func = weight_init_func
if self.weight_init_func is None:
self.weight_init_func = self.get_default_weight_... |
7805f9a5d55632c9ac2f925be5f20bc587a4767e852ba04006ff776435d70e3f | Python | 2,861 | 87 | #!/usr/bin/env python
"""Setup script for H-FNO-MultiPhysics package."""
from setuptools import setup, find_packages
from pathlib import Path
# Read the README file
this_directory = Path(__file__).parent
long_description = (this_directory / "README.md").read_text(encoding="utf-8")
# Read requirements
requirements = ... |
b76888521f4c72cd2ff7c786de9ddc4a2409ffa282660d5f032d9215508758d5 | Python | 2,861 | 97 | """
:Author: M. Simionato
:Date: April 2004
:Title: A much simplified interface to optparse.
You should use optionparse in your scripts as follows.
First, write a module level docstring containing something like this
(this is just an example)::
'''usage: %prog files [options]
-d, --delete: delete all files... |
2bee7f45185cf8c73d7fd07c2956bc89c1e4e667679c3a59831b218c90b386e2 | Python | 2,864 | 64 | #!/usr/bin/env python3
import pandas as pd
import numpy as np
import argparse
import subprocess
import os
import gzip
def load_pair_data(path):
if path.endswith('.txt.gz'):
return pd.read_csv(path, sep='\t', usecols=['pair_id', 'slope', 'slope_se'], index_col=0, dtype={'pair_id':str, 'slope':np.float32, '... |
04f9ef425381c8853509544a2401440f1e30be364709f14f2c827da47cd4f019 | Python | 2,865 | 73 | # Copyright (C) CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT
from datetime import timedelta
from django.test import override_settings
from django.utils.timezone import now
from rest_framework import status
from rest_framework.test import APITestCase
from cvat.apps.engine.tests.utils import ForceLogin
from cv... |
3813d4b12f015aa97cd6cb5ae37c432e7fffbeb5cbfb521463c51b6ab35a3df1 | Python | 2,865 | 107 | import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pytest
from nelpy import core
from nelpy.core import EpochArray, SpikeTrainArray
from nelpy.plotting import core as plotting_core
matplotlib.use("Agg")
@pytest.fixture
def epocharray_and_data():
# Create a simple EpochArray and matching... |
63f0cdca287eb91fd672588617c6c8c8a8ef38a699a0b3031195e84ca22f1182 | Python | 2,865 | 83 | from typing import Optional, Tuple
from matplotlib import pyplot as plt
from matplotlib.axes import Axes
from matplotlib.figure import Figure
from matplotlib.colors import to_rgb
from matplotlib import colormaps
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np
from ..tools._cell_shape_modelin... |
70c814de5b371387e88a1abbfaedf4db99dd92122f9da6df4ed1509c780d7124 | Python | 2,865 | 99 | # kmer count
import keras
import json, math,sys
import sys,random
import numpy as np
import datetime, os, re
from sklearn import metrics
from sklearn.svm import LinearSVC as SVC
from sklearn.ensemble import RandomForestClassifier as RF
from sklearn.linear_model import LogisticRegression as LR
K = 6
def hashGenerate(s... |
ec1c1e035964c5c5009feccf04425932f6c31743c8f1f30e29dfbafa29ed21a3 | Python | 2,865 | 46 | """Family size, subtraction, annotation and identity checks for the post hoc tier."""
import hashlib,json
from pathlib import Path
import numpy as np
import pandas as pd
import pytest
ROOT=Path(__file__).resolve().parents[1]
pytestmark=pytest.mark.skipif(not (ROOT/'tables/dna_maintenance/primary_tests.csv').exists(),re... |
95fc82d16793c88e1cf366aab9b0fd37159b7ae432a2380188193d2e77d0dbd4 | Python | 2,866 | 68 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import tempfile
from scilpy import SCILPY_HOME
from scilpy.io.fetcher import fetch_data, get_testing_files_dict
# If they already exist, this only takes 5 seconds (check md5sum)
fetch_data(get_testing_files_dict(), keys=['tractometry.zip'])
fetch_data(get_test... |
583d15d392e1e356e4d38acc34a113a2358d45d48d7e905b6b2845ae2345d588 | Python | 2,867 | 83 | from dataclasses import dataclass
from pathlib import Path
import numpy as np
from eir.setup.input_setup_modules.common import DataDimensions
from eir.setup.input_setup_modules.setup_array import (
ArrayNormalizationStats,
get_array_normalization_values,
get_data_dimension_from_data_source,
get_dtype_... |
6ede5eb7cad378ac1acbb3fca7e610ca335b59dc1994b0a905d4ca9202ad685b | Python | 2,867 | 86 | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
bf0592e771517165fb49de9f1bd0e4c90505801da0f2a914ffe8116e2e531e37 | Python | 2,867 | 84 | import numpy as np
from brainscore_core.supported_data_standards.brainio.assemblies import PropertyAssembly
from brainscore_core.metrics import Metric, Score
NSAMPLES = 1000
def ks_similarity(p, q):
z1 = np.zeros_like(p)
z2 = np.zeros_like(p)
z1[0] = 1
z2[-1] = 1
kolm_raw = np.max(np.abs(np.cum... |
cc3e31baecd91874f7c251728e1070e91b7c2cb6cd6c14c5fd24721c51916caa | Python | 2,867 | 84 | import numpy as np
from sklearn import metrics
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 OptimalBattery.construct as ct
import OptimalBattery.plot as plot
from Opti... |
08b0363638c97a0755836b47204ed7668d7195737de387168d7ef17d6a0805cf | Python | 2,868 | 96 | from dataclasses import dataclass
from typing import TYPE_CHECKING, Literal
import torch
from torch import nn
from eir.models.input.array.array_models import al_pre_normalization
from eir.models.input.array.models_locally_connected import LCLModel, LCLModelConfig
from eir.models.layers.projection_layers import get_1d... |
19ccfb74b6dc6fa736bbd88d10b71f8e8affabbe9dbe03eb0f9f68b4d25e2bcc | Python | 2,868 | 90 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 25 17:29:15 2023
@author: rl05
"""
import os.path as op
from mne import (read_epochs, make_forward_solution, write_forward_solution,
read_source_spaces)
import config
data_dir = op.join(config.project_repo, 'data')
preprocessed... |
7e018b7b84867785e2e38ee8c67adcb95a9e89d1cfb310a51a268a4032b68670 | Python | 2,868 | 69 | import os
import argparse
import SimpleITK as sitk
def main():
"""
Converts one or more NIfTI files to RAS orientation using SimpleITK.
Accepts either a single file or a folder of NIfTI files.
"""
parser = argparse.ArgumentParser(description="Convert NIfTI file(s) to RAS orientation using SimpleITK... |
8fe7933b76054ccefcaa416b771489540753e902fc1079cdd528703edc821c15 | Python | 2,868 | 96 | #!/usr/bin/python
#
## @file
#
# Handles coordinate manipulations, mostly converting back
# and forth between pixels and microns.
#
# Hazen 02/13
#
import storm_control.sc_library.hdebug as hdebug
## Point
#
# There is a lot of conversion back and forth between real positions
# (in microns) and display positions (in ... |
cfd16ae8606217692745fa576c13b60912b68030f0249052e87794f55149ab8b | Python | 2,868 | 91 | import pytest
from eir import train
from eir.train_utils.utils import seed_everything
from tests.test_modelling.test_modelling_utils import check_performance_result_wrapper
seed_everything(seed=0)
@pytest.mark.parametrize(
"create_test_data",
[
{"task_type": "multi", "modalities": ("sequence",)},
... |
0a67adfe560589124c8b20746decc2d37e10d023f23bb353a7e03b04b6b6798a | Python | 2,870 | 106 | #!/usr/bin/env python3
"""
Extract schema from a trained EBM model.
This script extracts the schema (feature names, types, statistics) from
a trained EBM model and saves it to a JSON file for later validation.
Usage:
python extract_model_schema.py \\
--model-path path/to/model.pkl \\
--output-path... |
2f858731d28dbc2bf72b448f662786070be2fad2473f800b583fdf3f00352409 | Python | 2,870 | 84 | """Run demo.
This script can be used to play with and test prototype tasks with a
keyboard/mouse interface. It is nearly the same as moog_demos/run_demo.py.
Run with the following:
$ python3 run_demo.py --config=path.to.your.config
See also the flags at the top of this file. There are options for rendering
settings,... |
5f5fab8029e5ae317ab73539711d4c02561c39826b26a981365a09ae3283bd10 | Python | 2,870 | 83 | from dataclasses import dataclass
import h5py
import numpy as np
from matplotlib import pyplot as plt
from scipy.signal import find_peaks
@dataclass
class Waveform:
db_brain: np.ndarray
db_scalp: np.ndarray
mua_brain: np.ndarray
mua_scalp: np.ndarray
times: np.ndarray
def __post_init__(self)... |
b1e385820136c558e52367b5388d2f55fb0159aa1d1038a904350ad6305d11d9 | Python | 2,870 | 95 | #!/usr/bin/env python
# Copyright 2014-2015 Numenta Inc.
#
# Copyright may exist in Contributors' modifications
# and/or contributions to the work.
#
# Use of this source code is governed by the MIT
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/MIT.
import argparse
import os
tr... |
bfba8f187d42747e49b0a249f54059010560b390bc1c806c9669be3de86a95da | Python | 2,870 | 104 | #!/usr/bin/env python
#
## @file
#
# Control of Holoeye SLM, though this could probably be used
# with any device that works in a similar fashion. It takes
# over the screen that (hopefully) corresponds to the Holoeye
# and displays full screen images in that display.
#
# Hazen 07/14
#
from PyQt5 import QtCore, QtGui,... |
f301a53db5947c04010aefa8cd70c0191e9bddad46a09b17c5c2aff750ea2ddd | Python | 2,870 | 75 | from itertools import count
import datajoint as dj
from scipy.interpolate import InterpolatedUnivariateSpline
from .preprocess import Sync, fill_nans, SpikeMethod, Prepare, BehaviorSync, ExtractRaw, ManualSegment, Method
from .preprocess import Spikes as PreSpikes
from . import preprocess, vis
import numpy as np
impor... |
99564808824938974b36271ebd33792c4a8a338b69c24af754fb46d924cb334c | Python | 2,871 | 72 | """
Metrics to asses violations of positivity
"""
import numpy as np
import pandas as pd
def _check_mean_group(mean_group):
mean_group = int(mean_group)
if mean_group not in {0, 1}:
raise ValueError('mean_group needs to be equal to 0 or 1')
return mean_group
def cross_covariance(X, a, mean_grou... |
352628be2ae08e0fee0b161e7b9d334a6fedd9f4141a711b8d7ef18c5aea500a | Python | 2,872 | 83 | import os.path as op
import dipy.data as dpd
import nibabel as nib
import nibabel.tmpdirs as nbtmp
import numpy as np
import numpy.testing as npt
from dipy.align.imaffine import AffineMap
from dipy.align.streamlinear import whole_brain_slr
from dipy.io.streamline import load_tractogram
import AFQ.data.fetch as afd
fr... |
ef3f8051d8e66f75f2a560fa07a191c3fdd84466d0520adee59536e630f95fdd | Python | 2,872 | 86 | from monai.transforms import (
Compose,
EnsureChannelFirstd,
EnsureTyped,
LoadImaged,
ResizeWithPadOrCropd,
ScaleIntensityRanged,
Spacingd,
SelectItemsd,
RandAffined
)
from custom.transforms import (
CropByKeyd,
LocalizeByRuleBased,
CacheStopHereTransfromd
)
def get_pre... |
bf0fead198a73b72db0838ce4922df1622831bbc05cc6301c9a54584734846fb | Python | 2,873 | 65 | import nighres
import os
import nibabel
import numpy
import glob
import scipy.ndimage
inpath = '/home/pilou/Projects/Cerebellum/Cerebellar-segmentation-ABC/'
in_sfx = 'nighres/topology/'
prev_sfx = 'nighres/tissues/'
out_sfx = 'nighres/surfaces/'
wmrawprior_sfx = '_anat_inv1_s2c10_lcpca-den_qt1map-t1_cr_def-img_msk_... |
cf433f08177c5f4c22e67eb6bbec37724ca7449d7c4074ada915d3811ad7a282 | Python | 2,873 | 91 | """ Conv2d + BN + Act
Hacked together by / Copyright 2020 Ross Wightman
"""
from typing import Any, Dict, Optional, Type
from torch import nn as nn
from .typing import LayerType, PadType
from .blur_pool import create_aa
from .create_conv2d import create_conv2d
from .create_norm_act import get_norm_act_layer
class ... |
259dafe992c0dd544beecdc1934401d4dda0e82576b41b6ee99dcfc23f6e8dae | Python | 2,874 | 90 | from typing import Optional
import torch
from torch import Tensor
from torch.nn import Linear, Parameter
from torch_geometric import EdgeIndex
from torch_geometric.nn.conv.cugraph import CuGraphModule
from torch_geometric.nn.conv.cugraph.base import LEGACY_MODE
from torch_geometric.nn.inits import zeros
try:
if ... |
4c6729d06c9d3d669a12a13a8975d684bed7336e3a8cc3209d0ab83fdc6b98d0 | Python | 2,875 | 93 | #!/usr/bin/env python3
import argparse
import matplotlib.pyplot as plt
import json
import math
import sys
# Read JSON output of lfp example from stdin and plot.
#
# The JSON data for timeseries is structured as:
# <string>: { "unit": <string>, "time": [ <number>... ], "value": [ <number>... ] }
# or:
# <string>... |
603ef5502ea9b75fa92e01cd885627587c2d00b6bd5071f104f0f367d0a56f62 | Python | 2,875 | 49 | from pathlib import Path
def default_ops():
""" Default arguments to run stimulus and choice modes """
return {
# Paths for data and models
"root_path": str(Path("/home/user/Documents/Cebra_code/")), # Root directory containing all subfolders
"data_path": str(Path("/home/user/Document... |
8c99a202867a9c0b64abb175dfc50fdf7e52d83ccc1162ae06f3924ab0bad4cb | Python | 2,876 | 78 | import numpy as np
from matplotlib.axes import Axes
from scipy.signal import find_peaks
from tqdm import tqdm
from argclz import AbstractParser
from neuralib.io import csv_header
from neuralib.plot import plot_figure
from neuralib.suite2p import get_neuron_signal, sync_s2p_rigevent
from neuralib.util.verbose import pu... |
21668b57e5379c85ce9cc3a84773be8b1a4e11c589b6d74297bd8df060bbe0ec | Python | 2,878 | 82 | # cec2017.utils
# Author: Duncan Tilley
# Additional functions for graphing and benchmarking
def surface_plot(function, domain=(-100,100), points=30, dimension=2, ax=None):
"""
Creates a surface plot of a function.
Args:
function (function): The objective function to be called at each point.
... |
31f00f48a472c2f577f97aef10de08298d4d91e73df7556b60f5409257068803 | Python | 2,878 | 100 | import argparse
import dataclasses
import json
from urllib import request
@dataclasses.dataclass
class Settings:
api_url: str = "https://zenodo.org/api/deposit/depositions/14266867"
def get_file_list(settings: Settings) -> list[dict[str, str]]:
url = f"{settings.api_url}/files"
with request.urlopen... |
161a868488d7e5d360566808e81a4bdd9bb48ad45e0b10e79bf7d1d01a870495 | Python | 2,879 | 87 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Remove outliers from image using the RANSAC algorithm.
The RANSAC algorithm parameters are sensitive to the input data.
NOTE: Current default parameters are tuned for ad/md/rd images only.
"""
import argparse
import logging
import nibabel as nib
import numpy as np
... |
d632257630157a089efb031fe0c4d4b2e0a47d300fb8a54ba3d07723f676eb5e | Python | 2,879 | 64 | from tqdm import tqdm
def extract_ca_atoms(input_file, output_file, res_file, step, model_start=1, model_end=50000, special_res=None):
# 计算总行数
with open(input_file, "r") as f:
total_lines = sum(1 for _ in f)
with open(input_file, "r") as f_in, open(output_file, "w") as f_out, open(res_fil... |
364a82934b27154c86186292f58597c1ff19000512e5a61d41a4e361f142b60b | Python | 2,880 | 75 | import torch
import torch.nn as nn
class VGG(nn.Module):
def __init__(self, features, num_classes=1000, init_weights=False):
super(VGG, self).__init__()
self.features = features
self.classifier = nn.Sequential(
nn.Linear(512 * 7 * 7, 4096),
nn.ReLU(inplace... |
a67c1d240ad996a5b820e923f3fde8a220da2152100a43fde725996fd2c40d4d | Python | 2,880 | 56 | from brainscore_vision.model_helpers.check_submission import check_models
from brainscore_vision.model_helpers.activations.pytorch import PytorchWrapper
from brainscore_vision.model_helpers.activations.pytorch import load_preprocess_images
from torchvision.models import convnext_tiny
import functools
import os
dir_path... |
7f0525be9da0ed5ddd3d0fbcf8e7b8c62ffe652cf440c1935c06bfee76c381af | Python | 2,881 | 49 | from pathlib import Path
def default_ops():
""" Default arguments to run stimulus and choice modes """
return {
# Paths for data and models
"root_path": str(Path("/home/user/Documents/Cebra_code/")), # Root directory containing all subfolders
"data_path": str(Path("/home/user/Document... |
0f64b240fff66d0ccdd0413961d15986d2fa1ef184c0af931e6d1245e49fc344 | Python | 2,882 | 86 | """
construct master list (per subject) of units with fields:
unit_number date v_probe spikes_dir
with subsequent fields to be added by add_fields_to_master_list
"""
import os
import pandas as pd
import numpy as np
from utils.get_session_info import find_sessions_nested, get_spk_metadata
from ast import literal_eval
... |
983906b9b6df01416100b9fb83d65363bb92674ca63a0ae321b167c06e0b8f4b | Python | 2,882 | 124 | # -*- coding: utf-8 -*-
# python standard library inputs
from pathlib import Path
# external inputs
import numpy as np
import nibabel as nb
from numpy.linalg import inv
__all__ = ['read_vox2vox', 'read_vox2ras_tkr', 'vox2ras_tkr']
def read_vox2vox(input_lta):
"""Read vox2vox.
This function reads a freesur... |
72d865fa3ddb4b54169dda80d1d0abf6c32e9c3280b61e46415a59a605f5fde9 | Python | 2,883 | 82 | # @String(value="This script measures all SWC/TRACES files in a directory",visibility="MESSAGE") msg
# @File(label="Input directory", style="directory") input_dir
# @String(label="Consider only filenames containing",description="Clear field for no filtering",value="") name_filter
# @boolean(label="Include subdirecto... |
4c0b94983f5e90f1a02f962d77822fc670d087ff456898b2d1254a3a886c37ba | Python | 2,884 | 73 | import numpy as np
import torch
from distances import LpDistance
from utils import common_functions as c_f
from utils import loss_and_miner_utils as lmu
from miners.base_miner import BaseTupleMiner
class AngularMiner(BaseTupleMiner):
"""
Returns triplets that form an angle greater than some threshold (angle)... |
6b08f957ce122d18d8b7a6a64ee9f775e29e69e47b6d4087b33ea74e8cefcbca | Python | 2,884 | 68 | # /------------------------------------------------------------------------------+
# | 03-Mar-2026 |
# | Copyright (c) Bone Imaging Laboratory |
# | All rights reserved ... |
ec9f13776471251e231589dbe4e31ae5abab8469af6384363d15675bee57c1bd | Python | 2,884 | 82 | # NOTE: More than 256GB CPU memory required to run this script.
# Use `--low-memory` to reduce memory consumption by using half-precision
import os.path as osp
import time
import argparse
import torch
import torch.nn.functional as F
from torch_sparse import SparseTensor
from torch_geometric.nn import LabelPropa... |
f250d6378ebc7b593e7abc30e033ba91a34ed4af7cebf7a1df4e4f83e4fb2a6b | Python | 2,884 | 112 | """
Various useful utilities, mostly taken from the ASPN Python cookbook.
"""
import types
seq_types = (tuple, list)
def flatten(*args):
for arg in args:
if type(arg) in seq_types:
for elem in arg:
yield from flatten(elem)
else:
yield arg
def cross_lists... |
2e897ee15d73582b2d3cf7c9873e693a357fa57d4d35ed9538b313597172017f | Python | 2,885 | 96 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Script to smooth a surface with a Laplacian blur.
For a standard FreeSurfer white matter mesh a step_size from 0.1 to 10
is recommended
Smoothing time = step_size * nb_steps
small amount of smoothing [step_size 1, nb_steps 10]
moderate amount of smoothing [st... |
f83a1a84a66b6cbf13b841a23e4af40be8e4088218d2122a7d7a4a70b4e17417 | Python | 2,886 | 87 | from pydantic import BaseModel, Field
from typing import Union
from chemgraph.models.atomsdata import AtomsData
class WorkerTask(BaseModel):
"""
Represents a task assigned to a worker agent for performing tool-based computations.
Attributes:
task_index (int): The index or ID of the task, typicall... |
2d45a11e4c8d936cbe82f5c48b03e308447fa7436844dfb0474c058300b29413 | Python | 2,887 | 63 | """Default graph budgets agree across persisted, evaluation, and UI configs."""
import pytest
import toml
from pydantic import ValidationError
from chemgraph.eval.cli import build_config_from_args, parse_args
from chemgraph.eval.config import BenchmarkConfig
from chemgraph.memory.schemas import MainAgentGraphConfig
f... |
4c399326bb644e08a974f6cb97fde47a0b3f0864f6aaa585571de3af931cc53e | Python | 2,889 | 83 | #############################################################################
# Copyright (C) 2020-2026 MEmilio
#
# Authors: Henrik Zunker
#
# 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 Lice... |
ba1d54acd1f6469731dcf364249dc3cebaebaee859c65257aef585594891d20a | Python | 2,889 | 97 | import csv
import pandas as pd
import torch
from tqdm import tqdm
import json
f = open('/data2/whr/czl/TwiBot22-baselines/datasets/cresci-2015/node.json')
users = json.load(f)
id2index = {}
k = 0
for user in users:
id2index[str(user["id"])] = k
k+=1
print("k: {}".format(k))
label_list = pd.read_csv("/data2... |
bcb778b69c9042b1c93ca711db9223e61332f818a9cdbb7d134b45c23bcac067 | Python | 2,889 | 89 | """Local multi-agent MCP example over stdio.
Spawns ChemGraph's built-in MCP server (chemgraph.mcp.mcp_tools) as a
local subprocess, loads the exposed tools, and runs ChemGraph with the
multi_agent workflow. The planner decomposes the query into parallel
executor tasks (one per molecule) using the Send() pattern.
Us... |
4e325866a233997c09e1d71397e6e99b6e1f1c9cf54e1fd5a11e1e40d00d1eeb | Python | 2,890 | 49 | from pathlib import Path
def default_ops():
""" Default arguments to run stimulus and choice modes """
return {
# Paths for data and models
"root_path": str(Path("/home/user/Documents/Cebra_code/")), # Root directory containing all subfolders
"data_path": str(Path("/home/user/Document... |
6a31ebcb2f30533ea2a155eb0cd8a5902b115c06b28d51e0c0f0ac3577b5ed2a | Python | 2,891 | 86 | from functools import partial
import torch
from torch.nn.modules.loss import _Loss
from .functional import focal_loss_with_logits
__all__ = ["BinaryFocalLoss", "FocalLoss"]
class BinaryFocalLoss(_Loss):
def __init__(
self,
alpha=0.5,
gamma: float = 2.0,
ignore_index=None,
... |
1071f81947e5364ad92829f3e6e6c7d9139367b1aa7f87ae8e7fbee005324574 | Python | 2,893 | 89 | #!/usr/bin/env python
"""Test that all bundled assets are accessible after installation.
This script verifies that the FLYNC package includes all required data files.
Run after installing the package to ensure assets are properly bundled.
"""
import sys
from pathlib import Path
def test_assets():
"""Verify all ... |
9ac6708dd385bbc43981ab818ce430fb3f070f635d73bb7f1f3e7b3aebdb2d6a | Python | 2,893 | 69 | import torch
import torch.nn as nn
import numpy as np
from ..models.filters import EdgeFilter2d, GaussianFilter2d
from ..ops.features import texture_filter
__all__ = ['MultiscaleBasicFeatures']
class MultiscaleBasicFeatures(nn.Module):
def __init__(
self,
in_channels,
intensit... |
b4492e97098e02ccc9d716c0e0b88e14839708d66d708c08a1889d95e7f2976c | Python | 2,894 | 80 | import torch
from mlcg.data import AtomicData
from typing import Optional
from .scatter import scatter
def calc_weights(data: AtomicData) -> torch.Tensor:
"""
Compute per-atom radial weights relative to each molecule's geometric center.
The weight for each atom is the Euclidean distance from the atom to... |
70ba83f478b8ec977630e37d4eb5ac0306a8d594fd527e3c9e3831c7f2a79744 | Python | 2,895 | 79 | #!/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... |
5cae0d1c18afd8f3605a1f72a192282ec79756097203e7f62d96a68429066b78 | Python | 2,896 | 92 | import pandas as pd
import time
import csv
import spacy
from tqdm import tqdm
import content_features as cf
import os
nlp = spacy.load('en_core_web_lg', disable=['parser', 'ner'])
def get_content_vector(tweets):
links = cf.count_urls(tweets)
mentions = cf.count_mentions(tweets)
content_vector = {
... |
0cfba7f10f23dc9c7622e1bff0a60fd7fad14c5d6f4a4e09e92159ad4c30ca9e | Python | 2,897 | 31 | from testsetclass import TestsetClass
class AHB21(TestsetClass):
def __init__(self):
self.weak = 1.0
self.molecules = ['4B', '5A', '5B', '21B', '20', '18', '17B', '11B', '10B', '3A', '18A', '19A', '12A', '15A', '2', '6B', '15B', '17', '16B', '9', '14', '20A', '2B', '21', '17A', '7B', '9A', '12', '... |
170b229f663197574a4e2b4b0e7e89230526c4431116b4c1c46918699fe9ef1f | Python | 2,897 | 80 | import pytest
from pytest import approx
from brainscore_vision import benchmark_registry, load_benchmark
from brainscore_vision.benchmark_helpers import PrecomputedFeatures
from brainscore_vision.benchmark_helpers.test_helper import NumberOfTrialsTests
from brainscore_vision.benchmarks.muzellec2026.benchmark import (... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.