sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
d66bb02688f43284a8224dec6947d877f85767e4470de732df9e7961bf4d1720 | Python | 3,450 | 115 | """
Regularized LDA
The code was implemented based on the following paper:
Dornhege et al., "General Signal Processing and Machine Learning Tools for
BCI Analysis Toward Brain-Computer Interfacing", MIT Press, 2007, page 218.
Kyuhwa Lee
Swiss Federal Institute of Technology Lausanne (EPFL)
"""
import math
import num... |
2d917ffd3e577efddb67b068fd692e8bb4d3292e60d9ffd393e2b692101eaf40 | Python | 3,453 | 87 | """Shared body of the two foundation targets.
Underscore-prefixed, so the package skips it during discovery: it is what
``foundations`` and ``foundations_network`` both do, not a target of its own.
The two differ only in whether running them downloads anything, and that
difference is the whole reason they are separate... |
089dff48eb156679d15e952da73be8fc4a9d81c01944533ff9425e4c767e6a44 | Python | 3,454 | 117 | from . import encodings
class Encoder:
# language=rst
"""
Base class for spike encodings transforms.
Calls ``self.enc`` from the subclass and passes whatever arguments were provided.
``self.enc`` must be callable with ``torch.Tensor``, ``*args``, ``**kwargs``
"""
def __init__(self, *args... |
2419f37a03c1e15cd81b17dbcc0b622f6163c29385efd21ef16f0497a073cf1f | Python | 3,454 | 95 | """GNC backend: WashU gradunwarp (gradient_unwarp.py) plus FSL's calc_grad_perc_dev."""
from pathlib import Path
from lib.utils import force_remove
def compute_warp(
ref_volume_nii: str | Path,
coeff_file: str | Path,
scanner: str,
out_prefix: str,
) -> str:
"""
Run gradient_unwarp.py on the... |
5aa1cccf944adce0e76046156624ab33e4930b5a77d0405d5dfe668393d72ea6 | Python | 3,458 | 116 | '''MobileNet in PyTorch.
See the paper "MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications"
for more details.
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
def conv_bn(inp, oup, stride):
return nn.Sequential(
nn.Conv3d(inp, oup, kernel_size=3, stri... |
33c870cb2d494b50b2490bf630eff6f39f372e512fe23572953b81edf828d417 | Python | 3,460 | 111 | from PymoNNto import *
import scipy.cluster.hierarchy as sch
import pandas as pd
class Classifier_base(AnalysisModule):
def initialize(self, neurons):
self.add_tag('classifier')
self.add_tag('cluster_matrix_classifier')
self.corrMatrices={}
def get_cluster_matrix(self, key):
i... |
792fdf9c33ad1d690135c4a274817bb3c7404ab220d4de3665a8f3402b3d8f0b | Python | 3,460 | 129 | import copy
import torch
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib import animation
from mpl_toolkits.mplot3d import Axes3D
from typing import Optional, Dict
# https://github.com/xxxnell/how-do-vits-work
def rand_basis(ws: Dict, device: Optional[str] = torch.device... |
53dc32de04c5746f358eebeb596c2ad3202581b48ab02eb50f7a5eda69164d6e | Python | 3,461 | 103 | # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# 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
#
# Un... |
55393323761a6164ee97dda8744bafc3ef7983c434352afea29f09679a389c8f | Python | 3,461 | 67 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.manifold import TSNE
if __name__=="__main__":
best_split_id = [2, 2, 2, 2, 2, 2] # correspoding to split index for S1, S1, S3, S3, S1, S3
hcp_sessions_list = ['LR_S1', 'LR_S1', 'RL_S1', 'RL_S1', 'LR_S1',... |
868124ac36587420456209fcd905cf96eca9cfe801a63d70ac43e88d5c49b481 | Python | 3,462 | 105 |
import numpy as np
from sleepy.processing.dataset import Dataset
class TestSignal:
def generate(size = 10, numberOfSamples = 1000, windowSize = 10, scale = 1):
"""Generates a test signal that should come close to a slow-wave signal
in terms of amplitudes, negative-to-positive zero-crossin... |
96172d4530ca7e3a06cdffbab0b6fd7afee2662f5c8faef5f9ab1f337113c2c6 | Python | 3,464 | 123 | import random
import torch
import numpy as np
import os
from typing import Union, Dict, Optional, Tuple
from torch import Tensor
from sys import platform
from utils import logger
from utils.ddp_utils import is_master
from cvnets.layers import norm_layers_tuple
def check_compatibility():
ver = torch.__version__.s... |
54affe447b8e3026ca63c37d1fd8cc675b8f531ed07cfbf3d341c927ca61bc16 | Python | 3,466 | 98 | import unittest
import numpy as np
from foldingdiff import custom_metrics as cm
class TestKLFromEmpirical(unittest.TestCase):
"""
Test for KL divergence calculation
"""
def test_two_gaussians(self):
"""The KL divergence between two Gaussians should be infinity"""
# https://stats.sta... |
fb8febad29a451259465b58e99eeea1cd158be7539ac570309e8ed8e555b9b50 | Python | 3,468 | 113 | from pathlib import Path
import mne
import numpy as np
from .io_file_dir import get_file_list
from ..preprocess.events import find_event_channel
from ... import logger
def read_raw_fif(fname, events_ext=None, preload=True):
"""
Load data from a .fif file.
Parameters
----------
fname : str
... |
ce8842923e40abb66ad80b11f51e86864a5d0a6c6c61f38e812629541342a4a3 | Python | 3,474 | 92 | """No anchor builder may default its output path.
Each `build_*_anchor.py` writes a checkpoint and a sidecar, and every reference in
this directory was recorded against the committed bytes. `build_anchor` used to
default `model_path` to the committed `MODEL_PATH`, so calling it with no argument
overwrote the anchor wi... |
1ad5cb2da741d117f1870e9c1c20dc834d4e81ce8b743b066dd69a23e7ffb26d | Python | 3,475 | 88 | import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from matplotlib import transforms
def panel_specs(layout, fig=None):
# default arguments
if fig is None:
fig = plt.gcf()
# format and sanity check grid
lines = layout.split('\n')
lines = [line.strip() for line in lines ... |
9f3a00660f1fb025a0d5435fd1e0ceefdd10f8d4fe1aaadb49487a048c8acfbc | Python | 3,475 | 101 | """Tests for the BrainData helpers in ``nltools.data.braindata.utils``."""
import numpy as np
class TestResolveThreshold:
"""Shared percentile-threshold resolution (#479)."""
def test_numeric_and_none_pass_through(self):
from nltools.data.braindata.utils import _resolve_threshold
data = np.... |
b1a11e31c39ab4d58f65fef52cb88c7e813aaf495f9651d026df0a829dcb053f | Python | 3,475 | 94 |
from tqdm import tqdm
import matplotlib.pyplot as plt
from skimage.transform import iradon, iradon_sart
from skimage.restoration import denoise_tv_bregman
from bm3d import bm3d
from sparse_ct.loss.tv import tv_2d_l2
from .base import Reconstructor
class SartReconstructor(Reconstructor):
def __init__(self, name... |
ebd440c978c2e40e0b6149ef0ea667e90e4a7433a0aebb1606516de4543d9804 | Python | 3,475 | 104 | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch_geometric.transforms as T
from torch_geometric.nn import GCNConv
from torch_geometric.nn.glob import global_add_pool, global_mean_pool, global_max_pool
from typing import List, Optional, Union
from torch import Tensor
from torch_scatter i... |
12acb9e1d9f3b40ad943649a569e1d493d1c8d17442f08d29fa39c27ab2fd494 | Python | 3,479 | 133 | from django.test import TestCase
from celsus.models import Author, CellType, TissueType, Organism, OrganismPart, Disease, Instrument, \
QuantificationMethod, Project, Keyword
from celsus.factories import CellTypeFactory, AuthorFactory, TissueTypeFactory, OrganismFactory, OrganismPartFactory, \
DiseaseFactory, I... |
beba0d5c799b663454dfaff761291a23a5bba558f16cd127438a8550076f0189 | Python | 3,479 | 114 |
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import ppafm.ml.AuxMap as aux
import ppafm.ocl.field as FFcl
import ppafm.ocl.oclUtils as oclu
import ppafm.ocl.relax as oclr
from ppafm.ml.Generator import InverseAFMtrainer
from ppafm.ocl.AFMulator import AFMulator
import mlspm.preprocessi... |
31c357e34a43ccd43ee062387e7ba3ae7f9546147ef72e0138738842f616fd7b | Python | 3,481 | 118 | # pylint: disable=wrong-import-position
import argparse
import copy
import os
os.environ["TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD"] = "1"
import torch
from e3nn.util import jit
from mace.calculators import LAMMPS_MACE
from mace.calculators.lammps_mliap_mace import LAMMPS_MLIAP_MACE
from mace.cli.convert_e3nn_cueq import ru... |
3c6be1f03f86aa4e218aa24a448efae07bf19395fdb623d6ba9e851faf38d9be | Python | 3,481 | 95 | import numpy as np
from fimpy.roi_extraction.corr_algorithms import _correlation_map_jit, _jit_flood
import itertools
from fimpy.utilities import to_4d, to_3d
from lightparam import Param
def correlation_map(video: np.ndarray, window_size=(1, 3, 3)) -> np.ndarray:
"""Calculate the correlation map of a video. Tiny... |
49f167ffa3d95f7576446585a00172290690cbbac4b845e2809e5b8a2fd750c9 | Python | 3,481 | 76 | from pathlib import Path
def write_launch_file(file_path: Path, function_call_str: str):
assert not file_path.exists(), 'launch file already exists'
print(f'{file_path.stem}: {function_call_str}')
with open(file_path, 'w') as f:
f.write('#!/bin/bash \n\n')
f.write('#SBATCH --gpus 1\n')
... |
fc3650eadfdec73d6b7491d31f62893cb8f126f43c24a4cea87be8ede917508a | Python | 3,481 | 114 | # The source code in this file is based on
# http://jamesgregson.ca/loadsave-wavefront-obj-files-in-python.html
# I removed several features which were not needed, cleaned the code, and
# introduced the management of multiple regions in a single .obj file
import numpy as np
class WavefrontOBJ:
def __init__(self)... |
a54fa8066bbce641244eb8386b80d6173eff19fdbbfdccb735b72fd10525f2b9 | Python | 3,484 | 75 | #*----------------------------------------------------------------------------*
#* Copyright (C) 2024 ETH Zurich, Switzerland *
#* SPDX-License-Identifier: Apache-2.0 *
#* *
... |
fff88b45ccfed7e38fa6dddf06d35a614881924bcead5848f481edf5d3c881c1 | Python | 3,484 | 101 | import os
import sys
import numpy as np
sys.path.append("..")
from nsrr import nsrr_utils
from nsrr.nsrr_utils import NSRR_DATA_PATHS, CHANNEL_PRIORITY_LABELS
if __name__ == "__main__":
dataset_name = "shhs1"
verbose_missing_epoch = False
reduced_number_of_subjects = None
channel_pairs_list = None... |
3560d90503dd4792997dd2d2702679ae40271659841ac73825557f1782659a70 | Python | 3,486 | 82 | # This file is a part of the `nequip` package. Please see LICENSE and README at the root for information on using it.
import torch
from lightning.pytorch.strategies import DDPStrategy
class SimpleDDPStrategy(DDPStrategy):
"""Effectively Lightning's :class:`~lightning.pytorch.strategies.DDPStrategy`, but doing man... |
5d9d15b0b8b94928576e47a2c466be79ef0c71954d9035c1dac090de231b5c17 | Python | 3,486 | 86 | """Compatibility repair of PolarMACE whole-model artefacts for graph_longrange.
This does not convert weights or training checkpoint dictionaries. Load trusted
whole-model files with ``weights_only=False``; PolarMACE repairs them on restore.
"""
PBC_HANDLING_MODES = (
"auto",
"realspace",
"pbc",
"slab... |
f70be0e5b3b10e6d4a95615e76cdfaa30ec514126c77025d4cfa833efef0f23b | Python | 3,488 | 93 | from import_data import import_data
from aux_fun import splitting
from testing_approachA import main_testA
from testing_approachB import main_testB
from testing_approachC import main_testC
from plot_results import fig_performance, fig_performance_all_patient, fig_feature_selection_A, fig_feature_selection_B_C
... |
2c0d65904c3d3a518ba68433860b37a5ca2cc2eda284c321b864e637d5577768 | Python | 3,490 | 119 | import numpy as np
from fimpy.alignment.reg_from_skimage import register_translation
from scipy.ndimage.interpolation import shift
from skimage.filters import sobel
from scipy.ndimage.filters import gaussian_filter
def _samesize(source, target):
"""Either crops or expands the source image to have the same size a... |
ea6d2fdff20c2bb828afc5d7daf62fec41a311f9b82564f29861e34e58251532 | Python | 3,490 | 138 |
from sleepy.gui.exceptions import UserCancel
def visualize(function):
"""Decorator function for methods that should only apply changes if the
control is active and whose actions neccesitate a rerender of the ui.
"""
def visualizing(self, *args):
if self.active:
funct... |
0a347faab596a6c010e1bf7037f6153596a43c5289358f5615aa6bdb3b662239 | Python | 3,494 | 108 | """app-pytorch: A Flower / PyTorch app."""
from collections import OrderedDict
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
from torchvision import transforms
from torchvision.datasets import ImageFolder
from torch.utils.data import DataLoader
import os
... |
87f7f3e87915b399d35db167f8877d2470552e6883e2694f4ea352429cc1e17b | Python | 3,498 | 116 | import gc
import os
from pathlib import Path
import numpy as np
import torch
import mlspm.preprocessing as pp
from mlspm import graph, utils
from mlspm.models import GraphImgNetIce
from mlspm.datasets import download_dataset
MM_TO_INCH = 1 / 25.4
def load_data(data_path: os.PathLike):
# Load data
data = n... |
89869341803e55b5d9767fcddcb2563a6092a79106187ae6e9f9ad737fc81b1f | Python | 3,498 | 82 | '''
Class that handles the construction of the reduced network composed
by the premodel, the reduction layer and the final input-output map.
'''
import copy
import torch
import torch.nn as nn
from smithers.ml.layers.tensor_product_layer import tensor_product_layer
if torch.cuda.is_available():
device = torch.devic... |
a34c45110cb0f10a3d28f6878d3b5cc544271103ff99fdf13b7a2731f164f0c3 | Python | 3,499 | 104 | # Copyright (C) 2020-2025 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
"""You may copy this file as the starting point of your own model."""
from logging import getLogger
import numpy as np
import keras
logger = getLogger(__name__)
def one_hot(labels, classes):
"""
One Hot encode a vector.
... |
11be7ef6c941c1a96f0a3d38156aff29e737ee68b5d6d1f51b56b66885fa74d6 | Python | 3,500 | 94 | from sklearn.metrics import precision_recall_curve, roc_curve, auc
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
import pandas as pd
cnn_test_40 = pd.read_csv("./cnn_test_40.csv", sep='\t')
cnn_test_150 = pd.read_csv("./cnn_test_150.csv", sep='\t')
cnn_test_141= pd.read_csv("./c... |
3ac05b8d6184f2a4f520719074011fb2a022e321775055cb75629598ef2d34e6 | Python | 3,501 | 91 | import tensorflow as tf
import numpy as np
def _int_feature(value):
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
def _bytes_feature(value):
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
class TFRecordCreator:
def __init__(self,
tf_recor... |
461e57faa0bd69081a615be15d67bbe4777227bf5d9ae74904c386da3c8a1ae0 | Python | 3,509 | 111 | from typing import Any, Callable, Sequence
import jax
import optax
from jax import numpy as jnp
from flax import linen as nn
import numpy as np
from .flax_utils import linear_activation
Dtype = Any
class TransportModel_entropy(nn.Module):
features: Sequence[int]
dtype: Dtype = jnp.float64
hidden_activati... |
80588a9723bb5a9b9fe306e8c8ed8dcf85886f21187d4922919c3069a2ae27b0 | Python | 3,509 | 76 | from common.evaluation.monitor import PerformanceMonitorVirtual, CustomSaverVirtual
from common.evaluation.measures import get_multitask_classification_measures
from variational.activations import sigmoid_moments_np
class CustomSaver(CustomSaverVirtual):
def __init__(self,
output_folder,
... |
9dc67e41db8a80bd1c3308177d073fae3a193965ad22e86510e86552086d4af0 | Python | 3,511 | 83 | # This file is a part of the `nequip` package. Please see LICENSE and README at the root for information on using it.
import torch
from nequip.data import AtomicDataDict
class NonPeriodicCellTransform(torch.nn.Module):
"""Construct a sensible orthogonal cell for nonperiodic systems without cells.
For structu... |
7c44869ef0206172f7eaf489571a6b5f302fcfe800cdb1ec082c5ddff4bbde97 | Python | 3,514 | 102 | """Tests for the Count API endpoint with read_level support."""
from typing import Tuple
from uuid import uuid4
import pytest
from chromadb.api import ClientAPI
from chromadb.api.models.Collection import Collection
from chromadb.api.types import ReadLevel
from chromadb.test.conftest import (
ClientFactories,
... |
0ff2ead9f788b6c1a070bd8e140fbda9d7cca3e2f6b3f869d637a14e6574f838 | Python | 3,517 | 113 | import os
import argparse
import warnings
warnings.simplefilter(action="ignore", category=FutureWarning)
import pandas as pd
import tensorflow as tf
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
from activation_models.generators import get_activation_models
from custom_model_tools.n_shot_learning imp... |
555559a6a18c0f4d8212c5e50885d49255de8646a19a77b8e01d4e5d0d6f9143 | Python | 3,519 | 92 |
'''
Example showing hardware-timed analog input of a finite number of samples using nidaqmx-python
pinidaqmxegs.ai.hardwareFiniteVoltage
Purpose
Shows how to do hardware-timed analog input using NI's nidaqmx-python package.
More details at https://github.com/ni/nidaqmx-python
This function acquires a... |
d5c37b9071ed1be1a7ab2d72ca15d774155216d126e55d5ffe90001afc622443 | Python | 3,519 | 99 | # -*- coding: utf-8 -*-
import torch.nn as nn
from copy import deepcopy
from dival.reconstructors.standard_learned_reconstructor import (
StandardLearnedReconstructor)
from dival.reconstructors.networks.iradonmap import get_iradonmap_model
class IRadonMapReconstructor(StandardLearnedReconstructor):
"""
C... |
e94db186e429fb397a9385cbf864db3c3e63373f82847818b860aa4c0845f1a4 | Python | 3,522 | 107 | import numpy as np
import torch
from model_angelo.gnn.violation_loss import (
between_residue_bond_loss,
kdtree_between_residue_clash_loss,
within_residue_violations,
)
from model_angelo.utils.protein import get_protein_from_file_path
from model_angelo.utils.residue_constants import (
atomc_dists_bound... |
59ffe0f2b33c3bcb005407c79db97e7f32337ffefdef0fb3a78871276234a4f0 | Python | 3,523 | 116 | """
Wrapper to run FASPR side chain packing on a pdb file.
https://github.com/tommyhuangthu/FASPR
"""
import os
import argparse
from glob import glob
from collections import defaultdict
import itertools
import tempfile
import subprocess
import shlex
import logging
import multiprocessing as mp
from typing import *
fr... |
445bb9887d2e7c5bd7263babf3e0ecfd501ef997748a228a929f6dacc0cda9b9 | Python | 3,524 | 78 | """The reference-year resolver: the parsers that need no network, and the committed table itself.
The network resolvers (PubMed, RCSB, GitHub) are exercised by ``vdjdb refs``, not by the suite --
a test that fails when NCBI is slow is a test that gets disabled. What is asserted here is the part
that has actually gone ... |
913cb637f8fbabf57c377d6db41fcd765a90c3279b934824181f22eeef68aea9 | Python | 3,529 | 132 | import random
import pytest
import geomstats.backend as gs
from geomstats.geometry.invariant_metric import (
InvariantMetric,
InvariantMetricMatrixLogODESolver,
)
from geomstats.geometry.poincare_ball import PoincareBall
from geomstats.geometry.spd_matrices import SPDMatrices
from geomstats.geometry.special_o... |
6e66cb92c1b3ed7e15de7681b17a3c87af24eaf6da6d0727288ffc57727af4e2 | Python | 3,530 | 94 | import os
import re
import pandas as pd
from tqdm import tqdm
import matplotlib.pyplot as plt
import numpy as np
import nibabel as nib
from common.adni.utils import check_projection
from common.adni.update_mri_metadata import check_valid_spacing, get_reordered_spacing
from nibabel.processing import conform
if __name_... |
88db9b5b6e94249de95b8f9e58991a7609d5169007784dfcf5901518afdb75c9 | Python | 3,530 | 97 | import random
import numpy as np
from scipy import linalg
from scipy.linalg import lapack
import logging
from gpytorch.lazy import RootLazyTensor
from gpytorch.utils.memoize import add_to_cache
def set_random_seed(seed):
"""Set seeds across modules for reproducibility"""
np.random.seed(seed)
random.seed... |
0b9646f509a4f36f85949e9045540e41474b5185924c0b4dd505400deba2a1fa | Python | 3,531 | 91 | """`PolarMACE.forward` returns the electrostatic keys its consumers read.
Seven of the model output keys in the inventory are produced in one dict in
`PolarMACE.forward` and nowhere else: `spins`, `total_charge`, `fermi_level`,
`external_field`, `spin_density`, `spin_charge_density` and `charges_history`. The
existing... |
cfbdb84b724e42ee3d588721734fef2525a1a61ccc6015b22500ca52bd96e0b9 | Python | 3,531 | 96 | """Tests for immutable metadata finalized by file loaders."""
from dataclasses import FrozenInstanceError, fields
import pyabf
import pytest
import numpy as np
from sanpy.fileloaders.epochTable import epochTable
from sanpy.fileloaders.fileLoader_base import fileLoader_base
from sanpy.fileloaders.fileLoader_abf import... |
f1b5db5147c626c1ea4d9a250ea3acc00c9085ad3dd091415d8084411c196b5a | Python | 3,532 | 89 | """Extracts only the relevant data from the full MODA database to save storage.
It saves the extracted signal for each subject in independent npz files under
the resources/datasets/moda/signals_npz/ directory.
These files are the input for the generate_moda_segments.py script.
"""
from __future__ import absolute_impo... |
562447a742f1f7009410ba099a95dc1da2901ce01947153496659f3879daa1e1 | Python | 3,533 | 85 | import pickle
import zipfile
import argparse
import numpy as np
import jax
def str2bool(v):
if isinstance(v, bool):
return v
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse.Ar... |
5ae7a4188c594671d3259576034973a7439e85317079fac3b8b083062c02c8b3 | Python | 3,534 | 135 | """Bayesian optimization according to:
Brochu, Cora, and de Freitas' tutorial at
http://haikufactory.com/files/bayopt.pdf
Adopted from http://atpassos.me/post/44900091837/bayesian-optimization
"""
# Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
# Alexandre Passos <alexandre.tp@gmail.... |
d59fa416a0dc3a7211c772e03d55383428b1f030d3adecf0b3ec447bec7f85d8 | Python | 3,536 | 91 | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
"""Image augmentation functions."""
import math
import random
import cv2
import numpy as np
from ..augmentations import box_candidates
from ..general import resample_segments, segment2box
def mixup(im, labels, segments, im2, labels2, segments2):
... |
b7ff5e9f6d1448f2ed114566c291dfe1ebead804b66c41cf53b12893ac3b7205 | Python | 3,537 | 101 | """Tests for the shared frame validation in nltools.data.validation."""
import numpy as np
import polars as pl
import pytest
from nltools.data.validation import _validate_frame
class TestValidateFrame:
def test_none_returns_empty_polars(self):
out = _validate_frame(None)
assert isinstance(out, p... |
09e4a917e7d7e14cbde5497597420b4b0d3d08f1000d317daa828d2297adb922 | Python | 3,540 | 110 | # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# 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
#
# Unle... |
2e9f3ef97fd930d505aeb00d9b5df92852f4dab31240560f892b0c84918bde9c | Python | 3,541 | 129 | """Finite differences machinery."""
import geomstats.backend as gs
def forward_difference(array, delta=None, axis=-1):
"""Forward difference in a Euclidean space.
Points live in R^m, but are a k-dim embedding (e.g. a curve).
Assumes points are in correspondence for cases higher than dim=1.
Paramete... |
69ea6203064f672cc81ac117deab5f573ca9e42e2876e7ee6688eb9096e41bea | Python | 3,542 | 98 | import os
import sys
import hashlib
from flwr_datasets import FederatedDataset
from flwr_datasets.partitioner import IidPartitioner
from PIL import Image
import numpy as np
from tqdm import tqdm
EXPECTED_DATASET_HASH = 'ee5342b063299eda95304b0e0388e403a3c65ce5a07cabea4c62a3efdb419a5983c7bb204e55d771ae643642ed440182'
... |
a4f5b1333a90e60e54d1fb7bc50f0f11fc39a171c11356e10278f0c0f3da4f9d | Python | 3,543 | 84 | # Copyright (C) 2025 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
from src.runner_fa import FederatedAnalyticsTaskRunner
import pandas as pd
import numpy as np
class SmokersHealthAnalytics(FederatedAnalyticsTaskRunner):
"""
Taskrunner class for performing federated analytics on the Smokers Health ... |
641284d41b06e324ec68532062fe112fa74a29f60af65e1ca68556d7d799abaf | Python | 3,545 | 121 | import os.path as osp
import numpy as np
from easydict import EasyDict as edict
__C = edict()
# Consumers can get config by:
cfg = __C
#########################
# Directory options #
#########################
__C.data_dir = "bbdd"
__C.model_dir = 'models'
__C.result_dir = 'results'
#########################
# ... |
92aa9cfd953e81b0fe43087a1da802fa440f4a3bdd160d2ba0bae1af7c0fb863 | Python | 3,546 | 115 | """
"""
from pprint import pprint
import pandas as pd
import sanpy
class epochAnalysis:
def __init__(self, ba: sanpy.bAnalysis):
retDictList = []
df = ba.asDataFrame()
files = df["file"].unique()
for file in files:
dfFile = df[df["file"] == file]
sweeps =... |
bafbb6080d30f7e3da4efd88401bf56588234daf84a54f7236943a061088960e | Python | 3,548 | 115 | """Generic REST interface from Syngenta"""
from __future__ import annotations
__all__ = ["REST"]
from typing import List
import requests
import numpy as np
from pydantic.dataclasses import dataclass
from .component_results import ComponentResults
from .add_tag import add_tag
from ..normalize import normalize_smiles... |
891af276fe542e477b53e8efb723666addd8d8812bf9ba173ebf430005b3f6fd | Python | 3,550 | 112 | import torch as T
import yaml
import nibabel
import sys
from monai.losses import DiceLoss
from monai.networks.nets.unet import UNet
import numpy as np
import torch as T
from monai.data import (DataLoader, Dataset)
from monai.metrics import compute_meandice
from monai.transforms import (
AddChanneld,
Compose,
... |
650ab8cf831223bc0398ec3fc324bb15b0705c5be2ce1d8ee0bf7410efeab412 | Python | 3,551 | 121 | import numpy as np
#creates 1D, 2D or 3D generators.
#the grid starts with a low resolution step size (max-min)/5
#and doubles its resolution per axis gradually.
#The longer you let the for loop run, the more detail you will get.
def infinite_resolution_1D(minx, maxx, max_resolution=-1):
points = np.array([-10000... |
4593358aa371421f34203d0f62b3090da5f93fcc23007fd9ed42b97c4b436030 | Python | 3,553 | 94 | # Copyright 2020-2024 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
"""Adam optimizer module."""
from typing import Dict, Optional, Tuple
import numpy as np
from openfl.utilities.optimizers.numpy.adam_optimizer import NumPyAdam
class NumPyYogi(NumPyAdam):
"""Yogi optimizer implementation.
Impl... |
4d65fa3a0a4c1639e4f1f99d8ed02cfb243a63e75dd48bf3af10a7bec1d6f76f | Python | 3,554 | 110 | """Brownian motion defined on a manifold."""
import geomstats.backend as gs
class BrownianMotion:
"""Class to generate a realization of Brownian motion on a manifold.
Parameters
----------
space : Manifold
Manifold to generate Brownian motion on.
Example
--------
>>> import os
... |
a1921034ae524d27542886f804d468126384b1f040fa485e557e1a8d9cde461f | Python | 3,554 | 106 | """
Code for computing lDDT scores.
Usage as a script to calculate the lDDT betwen each sampled structure and its
corresponding folded structures as used for scTM calculation:
python lddt.py <sampled_dir> <folded_dir>
Writes a json file with lDDT scores for each sampled structure to its correpsonding
folded structure... |
b08aeb717f51d4d2dddc80d0117ac5d91d3848422f41923a0bd3042ad41fc6d0 | Python | 3,554 | 92 |
'''
Example showing continuous hardware-timed analog input using nidaqmx-python and matplotlib
pinidaqmxegs.ai.hardwareContinuousVoltage
Purpose
Shows how to do hardware-timed analog input using NI's nidaqmx-python package.
More details at https://github.com/ni/nidaqmx-python
This function acquires c... |
09b22df4bb1e2921a4126bf83febd6c027f98e77989de9e44e83677360f1253c | Python | 3,555 | 84 | ###############################################################################
# recived from: https://raw.githubusercontent.com/NVIDIA/partialconv/master/models/partialconv2d.py
# BSD 3-Clause License
#
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Author & Contact: Guilin Liu (guilinl@nvidia.com... |
3691885cfeb3c6be7a1dfd24947c83964755b67a2dee6248cedec27c55705716 | Python | 3,557 | 131 | from PymoNNto import (
Network,
SynapseGroup,
NeuronGroup,
Behavior,
EventRecorder,
SxD,
float32,
)
import numpy as np
import time
import matplotlib.pyplot as plt
from globparams import *
settings = {"dtype": float32, "synapse_mode": SxD}
class TimeResolution(Behavior):
def initialize... |
ef237072ccab1ac88bad35a3f300378d9f7728279a656124309a312863a87456 | Python | 3,558 | 98 | from __future__ import annotations
import itertools as it
from argparse import ArgumentParser
from pathlib import Path
from typing import Iterable
import pytest
from hypothesis import given
from hypothesis import strategies as st
from snakebids.exceptions import ConfigError
from snakebids.plugins.bidsargs import Bid... |
20cc9ec1599a0a06ea8bc81007e731c0e5b32d4ef8601e5c40e8313ce87b5169 | Python | 3,563 | 94 | import itertools as it
import logging
import pyfizi
__all__ = ["check_valid_snp", "check_valid_alleles", "flip_alleles"]
# Base-handling code is from LDSC...
# complementary bases
COMPLEMENT = {'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C'}
# bases
BASES = COMPLEMENT.keys()
# true iff strand ambiguous
STRAND_AMBIGUOUS = {'... |
3131aacc9d7943c6704db8083f300bb1ed573e4d68bc499eee64200cbb66faff | Python | 3,569 | 103 | # Copyright 2025 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import hashlib
import os
from importlib import util
from typing import Generator
from urllib.parse import urlparse
from openfl.federated.data.sources.data_source import DataSource, DataSourceType
class S3DataSource(DataSource):
"""Class fo... |
b32bf71ab0f98563a5638413ec4551acf4b1bb8c9fbb0b458da63fd3e3b5981b | Python | 3,571 | 118 | # Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... |
f54a55e6321b7594e7847c7157b93ea67ef9eaaa6d07a01857a021dadd77db83 | Python | 3,571 | 104 | # Copyright (c) 2023 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... |
a0b6015c71ea2f61e65f6985c02551403531b4cf8ebb91e418af923438f2b51d | Python | 3,572 | 118 | """
Gradient descent on a sphere.
We solve the following optimization problem:
minimize: x^{T}Ax
such than: x^{T}x = 1
Using by operating a gradient descent of the quadratic form
on the sphere. We solve this in dimension 3 on the 2-sphere
manifold so that we can visualize and render the path as a video.
To ... |
47a492eef17768d5f65d7bce21619d8f1b0f2cc56a50b3630546a269a0d5f70d | Python | 3,574 | 119 | import renderapi
import numpy as np
from scipy.sparse import csr_matrix
from .utils import AlignerTransformException
__all__ = ['AlignerTranslationModel']
class AlignerTranslationModel(renderapi.transform.AffineModel):
"""
Object for implementing translation transform
"""
def __init__(self, transfo... |
6fed937c8469dad6feab1c092a10f95602576f00dc1f3ff48f1c0c5a73f4b336 | Python | 3,578 | 112 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 12 15:25:17 2018
@author: ngritti
"""
from deeprest.rawDataClass import rawData
from deeprest.modelClass import modelRest
from deeprest.timeLapseClass import sampleTimeLapse
import time, glob, os, shutil
from tifffile import imread, imsave
from skim... |
d1f5226cb2b88e9327295eb31219364d04b1a84b59e94b1006a779e2e00a5867 | Python | 3,578 | 110 | import geomstats.backend as gs
from geomstats.test.data import TestData
class SubRiemannianMetricCometricTestData(TestData):
fail_for_autodiff_exceptions = False
def inner_coproduct_test_data(self):
smoke_data = [
dict(
cotangent_vec_a=gs.array([1.0, 1.0, 1.0]),
... |
ea2893cfe466abc372ce6ebf04abf9bca26857dfc35354a42213078afbb58919 | Python | 3,579 | 97 | from tensorflow.keras.preprocessing.image import load_img, img_to_array
import glob, numpy as np, matplotlib.pyplot as plt, cv2.cv2 as cv2
def collect_images_from(path, exclude_early_stages=True, exclude_pediatrics=True):
normal_images = list()
for img_name in glob.glob(pathname=path + '/normal/*'):
i... |
197ad252102bc791227d9a8a63be0fc1b5d1119ecd208445c98c3c9f5a579090 | Python | 3,581 | 91 | import torch
from torch.autograd import Variable
from reinvent.models.transformer.core.network.module.subsequent_mask import subsequent_mask
def decode(model, src, src_mask, max_len, device, decode_type):
"""[summary]
Args:
max_len (int): max length for produced sequence (coded sequence)
typ... |
17f47bfebe699d6347cb5cb7b754fd1090aa4dc70173e9c46645832c3de8cd72 | Python | 3,582 | 94 | import numpy as np
from utils import smile_to_graph
from shogun import StringCharFeatures, SubsequenceStringKernel, RAWBYTE
def warn(*args, **kwargs):
pass
import warnings
warnings.warn = warn
from grakel.utils import graph_from_networkx
from grakel.kernels import WeisfeilerLehman, VertexHistogram, EdgeHistogram,... |
6f3e5850f190f85fad1c4c0cfeada69949f731978aae307b92dc8fe86452140b | Python | 3,582 | 127 | import random
import pytest
from geomstats.geometry.grassmannian import Grassmannian, GrassmannianCanonicalMetric
from geomstats.geometry.quotient_metric import QuotientMetric
from geomstats.geometry.scalar_product_metric import ScalarProductMetric
from geomstats.geometry.stiefel import Stiefel, StiefelCanonicalMetri... |
43f34b32d596b0c014031cc88f7ea8294635578207e67638bd23711d12494c16 | Python | 3,583 | 93 | # -*- coding: utf-8 -*-
#
#
# PyRates software framework for flexible implementation of neural
# network model_templates and simulations. See also:
# https://github.com/pyrates-neuroscience/PyRates
#
# Copyright (C) 2017-2018 the original authors (Richard Gast and
# Daniel Rose), the Max-Planck-Institute for Human Cogn... |
662493a199909e2496658e93cd80a094ac646b428cda172839e4667b5bb8f777 | Python | 3,583 | 92 | from PymoNNto.Exploration.Network_UI.Network_UI import *
from PymoNNto.Exploration.Network_UI.TabBase import *
import scipy.cluster.hierarchy as sch
import matplotlib.pyplot as plt
def generatePgColormap(cm_name):
pltMap = plt.get_cmap(cm_name)
colors = pltMap.colors
colors = [c + [1.] for c in colors]
... |
20ff59ee71ef33a4ac9f69a5423f87a7880e397ca0a2cb85f57b01c8828f00e7 | Python | 3,584 | 127 | """Input file reader for scoring
Assumes two formats: SMI or CSV
SMI file is assumed to have either one or two columns, SMILES in the first, no header!
CSV file is always assumed to have header
FIXME: review again if both formats should be treated as one singular, tabular
format
"""
__all__ = ["TabFileReader"... |
a08410ddcf3f5d197b77bc1e87eb1d6280ec1e6e690d3e68a07a280b0e901ec8 | Python | 3,585 | 117 | import click
from corgie import scheduling
from corgie.log import logger as corgie_logger
from corgie.data_backends import pass_data_backend
from corgie.layers import get_layer_types, DEFAULT_LAYER_TYPE, str_to_layer_type
from corgie.boundingcube import get_bcube_from_coords
from corgie import argparsers
from corgie.a... |
e9d7396bf1c3e68823b6b1f713cdaa7f69ac0f3d9c61c2b157f6d58c49099484 | Python | 3,585 | 81 | #class to download and load dataset
import subprocess
import os
import nibabel as nb
import pandas as pd
import numpy as np
import matplotlib_surface_plotting as msp
class MagiccDataset():
def __init__(
self,
figshare = 'https://figshare.com/ndownloader/files/39446125?private_link=82c8f6ebda38af670cd1'):
... |
03f96a93711bd7cc6f4d3766ffcfa1b7e1cce45bb6fa8f00d573bf5fa65e7569 | Python | 3,587 | 157 | from Purkinje_morpho_1 import Purkinje_Morpho_1
from Purkinje_morpho_1_number import number_ind_1
from neuron import h,gui
import numpy as np
import multiprocessing
import matplotlib.pyplot as plt
import random as rnd
#per disabilitare tutti i generatori random
seed = 123456
rnd.seed(seed)
h.use_mcell_ran4(1)
h.mcell... |
9b490982d2760d8a5faaee51aba771860f7826117050f713b3b1c0728c846153 | Python | 3,587 | 97 | # Copyright 2020-2023 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import pytest
import logging
import subprocess
import os
import json
from tests.end_to_end.utils.tr_common_fixtures import (
fx_federation_tr,
)
from tests.end_to_end.utils import federation_helper as fed_helper
from tests.end_to_end.ut... |
00b9550f3c7534973ad77a8c569b6e2c7a034853136aad26506f58650c7f6c47 | Python | 3,588 | 108 | """Conde for building dendrogram trees for a given neuroimaging dataset which includes
Structural Connectivity (SC) and Functional Connectivity (FC) matrices."""
from src.tree_functions import *
from src.connectivity_functions import *
from src.io_functions import load_data
import os
import sys
import json
import niba... |
7156e7b8a76bb9eb4955165b74ac25afaa90bce9649932d8177e3eb8d100d9a6 | Python | 3,592 | 117 | #!/usr/bin/env python3
import argparse
import numpy as np
import odil
def operator(ctx):
extra = ctx.extra
res = []
for key in ["uc", "un", "ufx", "ufy"]:
res += [(key, ctx.field(key) - extra.ref[key])]
res += [("a", ctx.field("a") - extra.ref["a"])]
net_a = ctx.neural_net("net")(ctx.... |
6b93b7e1a7e7ebd799fad8fdb560402b2ee2d393b1f577a106762a9b4032054e | Python | 3,595 | 134 | """Run K-means on manifolds for K=2 and Plot the results.
Two random clusters are generated in separate regions of the
manifold. Then K-means is applied using the metric of the manifold.
The points are represented with two distinct colors. For the moment
the example works on the Poincaré Ball and the Hypersphere.
Comp... |
df2a1ef241d23484c7ead1e9cd1532ca40c17658bc28d0f63fd25c9c4de449c3 | Python | 3,595 | 94 | #
# For licensing see accompanying LICENSE file.
# Copyright (C) 2022 Apple Inc. All Rights Reserved.
#
from torch import nn, Tensor
from typing import Optional, Tuple
from . import register_norm_fn
@register_norm_fn(name="instance_norm")
@register_norm_fn(name="instance_norm_2d")
class InstanceNorm2d(nn.InstanceNo... |
7d4989607cde8b6e477f3d77a3fd03a4d66ad4698931c23adb0166e8403b5a38 | Python | 3,597 | 109 |
#import sys
#sys.path.append('/path/to/script/')
import barcode as bcode
"""
USER GUIDE FOR BARCODE DETECTION AND STRENGTH TRACKING
Author: Charlie Clarke-Williams (2022)
PRIOR REQUIREMENTS
--------
To detect barcodes over regions of interest, the IMF instantaneous amplitude timecourses must be saved. To do this:
... |
dc6efdebc891932fe639d59397551892c995a58ec6de080c9662cd14049f3fff | Python | 3,600 | 100 | from __future__ import annotations
import io
from io import StringIO
from pathlib import Path
from typing import Any, OrderedDict
import pytest
from hypothesis import given
from hypothesis import strategies as st
from pyfakefs.fake_filesystem import FakeFilesystem
from pytest_mock import MockerFixture
from pytest_moc... |
3ee1bbf8d3943b6f16c58ef58caeaceeba2fe9f21e741dd02ee9f94ef4cfefc9 | Python | 3,602 | 104 | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""isort:skip_file"""
from .adaptive_input import AdaptiveInput
from .adaptive_softmax import AdaptiveSoftmax
from .base_layer import BaseLaye... |
dd532621a9316910af37d8f1c96d5a1bd4dc26f8e699801385d73fe50ce51992 | Python | 3,611 | 72 | """
Logic for wavefunction evaluation.
"""
import logging
from typing import Tuple, Optional, Dict
import jax
import functools
from deeperwin.configuration import EvaluationConfig, PhysicalConfig
from deeperwin.hamiltonian import get_local_energy, calculate_forces
from deeperwin.loggers import DataLogger, LoggerCollect... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.