sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
b7eebd051dd2862457d9db979a62f509fb98f0b135732f6594429b5996e77a50 | Python | 3,911 | 117 | from typing import Optional, Sequence
from torch import nn
import torch
import torch.nn.functional as F
def torch_soft_tp_fp_fn_tn(net_output, gt, axes, keep_mask=None):
"""Compute soft tp, fp, fn, tn from network output and gt
Args:
net_output: tensor with dimensions (B, C, W, H)
gt: tensor... |
e457c8c3b68b417dc06a3ab27fe2e9546f2401a8115b48143c27ff41e820c980 | Python | 3,911 | 100 | # Copyright (C) 2020-2024 Intel Corporation
# Licensed subject to the terms of the separately executed evaluation license agreement between Intel Corporation and you.
import numpy as np
from typing import Iterator, Tuple
from openfl.federated import PyTorchTaskRunner
from openfl.utilities import Metric
import torch... |
a45f0444f309998b7d43bacca7df123db6c25ca32b8dcb7e31c6371082d43eda | Python | 3,914 | 105 | # 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.
import math
from typing import Any, Optional
import torch
import torch.onnx.operators
from fairseq import utils
from torch import Tensor, nn
... |
6616755336b6351944c8aaa0711c7f4d39fa6b08b9d77ae5819d0480d59d1248 | Python | 3,915 | 151 | import logging
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from src.constants import (
AIS_LABEL,
DISTANCE_LABEL,
SITE_LABEL,
TERMINAL_LABEL,
TIME_LABEL,
VOLTAGE_LABEL,
)
from src.data import concise_df, get_file_path, is_long_form, wide_to_long... |
0fea87d38536005e2de2e2b083992e724cb8f463ee9ed0e17ae31e0a23743d28 | Python | 3,916 | 101 | # Copyright (c) 2020 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... |
435fb903a08e145d0579a844516736601eb09ccecad0b4368a758c96d69224f4 | Python | 3,920 | 115 | # 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
from tensorflow.python.keras.utils.data_utils import get_file
logger = getLogger(__name__)
def one_hot(labels, cl... |
66237659622c84a9098e157e2ed6d806630882ab0d311a250220e4c84bebb410 | Python | 3,923 | 115 | # Copyright (C) 2025 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
"""
Base classes for Federated Analytics.
This file can serve as a template for creating your own Federated Analytics experiments.
"""
from openfl.federated.task.runner import TaskRunner
from openfl.utilities import TensorKey
from openfl.u... |
673f2294e18260ac73d04879b5fb731fd64a9ee9a85d6db0e7d6cc2492499c5f | Python | 3,925 | 99 | import pandas as pd
import os
###########################################
### Create file list for ACC and methyl ###
###########################################
filetype_list = ['training', 'testing']
for filetype in filetype_list :
metaData = pd.read_csv(filetype + "_metadata.csv")
methyl = metaData[metaData['Om... |
9910ec5eca7454a322be45bd75b742054952ef771410d80f3c0ae74367bf178f | Python | 3,929 | 118 | import abc
from typing import Tuple, Union
import numpy as np
from scipy.ndimage.interpolation import rotate, zoom
import config
from data.utils import symmetric_pad_to_shape
class SegmentationTransform(abc.ABC):
@abc.abstractmethod
def __call__(self, img: np.ndarray, mask: np.ndarray) -> Tuple[np.ndarray, ... |
d1364e7963eb0a56462889104f8e4189de9f41d227b80189018c55ee21dd9c6e | Python | 3,929 | 107 |
from sparse_ct.tool import plot_grid
from sparse_ct.data import image_to_sparse_sinogram, ellipses_to_sparse_sinogram
from sparse_ct.reconstructor_2d import (
IRadonReconstructor,
SartReconstructor,
SartTVReconstructor,
SartBM3DReconstructor,
Proj2ProjReconstructor,
SupervisedReconstructor,
... |
5bba57dcb9672de345614c2feb28fd1baaabfa0178d3f3fb642f93b9e2c950fb | Python | 3,930 | 107 | """
Decomposition
=============
Here we demonstrate how to perform a decomposition of an imaging dataset.
All you need to do is specify the algorithm. Currently, we have several
different algorithms implemented from
`scikit-learn <http://scikit-learn.org/stable/>`_
('PCA','ICA','Factor Analysis','Non-Negative Matrix F... |
82b40f0f072057a5a0fbda3724e1953f56f5f353392651a851fe9a9f331cdb75 | Python | 3,931 | 129 | import tempfile
from unittest.mock import MagicMock
import numpy as np
import pytest
import torch
import torch.nn.functional as F
from e3nn import o3
from mace import data, modules, tools
from mace.tools import scripts_utils, torch_geometric
# Capability contract (tests/conftest.py): skipped locally when schedulefre... |
34d1410c0b355d0b8e0b4cca7b75484897cf6e89cd120ecdb2cb83f5cda18ea9 | Python | 3,932 | 111 | from pathlib import Path
import mne
from .. import io
from ... import logger
def current_source_density(inst, montage=None, **kwargs):
"""
Apply current source density transformation, also called laplacian filter.
Parameters
----------
inst : mne.io.Raw | mne.io.RawArray | mne.Epochs | mne.Evok... |
a22dedc6057bea531649d9db9fc77c0eeb80f348848ffbf04a17d8b846bb50b7 | Python | 3,933 | 141 | import random
import pytest
from geomstats.geometry.full_rank_matrices import FullRankMatrices
from geomstats.geometry.group_action import SpecialOrthogonalComposeAction
from geomstats.geometry.matrices import MatricesMetric
from geomstats.geometry.rank_k_psd_matrices import (
PSDBuresWassersteinMetric,
PSDMa... |
bd88cc8a34aa2cf089384e368183ea38fc58e7a4b78334c4cc8369b6e78fb8b7 | Python | 3,935 | 102 | """The magnetic anchor and its two references.
Not part of ``--target all``: regenerating these needs the ``magnetic``
extra (sphericart). Naming the target without it stops with that sentence
rather than with an ImportError from three frames down.
"""
from __future__ import annotations
from tests.golden import harn... |
b33ed9a48db39c2080e9368f0891b4c979744ae5a550840bd82dc71dc4e850af | Python | 3,937 | 125 | """Run an external scoring subprocess
Run external process: provide specific command line parameters when needed
pass on the SMILES as a series of strings at the end.
"""
from __future__ import annotations
__all__ = ["ExternalProcess"]
import os
import shlex
import json
from typing import List
import logging
import... |
d6a0ff352288da2b1d9f9381d8523c00d3bff4a93abac64fc1cfd0317de93f8a | Python | 3,937 | 110 | '''
Module focused on the preparation of the dataset for the training
and testing phases for the problem of object detection using
the PascalVOC notation.
'''
import os
import json
import torch
from torch.utils.data import Dataset
from PIL import Image
from smithers.ml.utils_objdet import transform
class PascalVOCDat... |
1d956eca4b31111911248c189f486618ff5305c48658c3f681395bd9e47794ff | Python | 3,938 | 98 | # 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."""
import logging
import keras
from openfl.federated import KerasTaskRunner
from src.model import CNNModel
logger = logging.getLogger(__name__)
class CNNTaskruner(Ke... |
4212d898a8c0dae579dd4a3061cdeba79b05e3028baef361fb8c57d88aa4a4b6 | Python | 3,939 | 103 | """
The Stuart-Landau Oscillator
============================
Here, we will introduce the Stuart Landau equations, a model of non-linear oscillating systems near a Hopf bifurcation [1]_.
In cartesian coordinates, the evolution equations of the Stuart Landau oscillator can be written as:
.. math::
\\dot x &= \... |
c75a8760820bb775053a1c1e39f7f111fc3952e175dd025ca62cc4b1a90079ef | Python | 3,942 | 149 | import os
import time
import warnings
import numpy as np
from pydfc import MultiAnalysis, data_loader
warnings.simplefilter("ignore")
os.environ["MKL_NUM_THREADS"] = "16"
os.environ["NUMEXPR_NUM_THREADS"] = "16"
os.environ["OMP_NUM_THREADS"] = "16"
################################# Parameters #####################... |
616e1f75f2a0dc11365abef445a61931f7ff4a25b250e25a42ba10416b0b5bd9 | Python | 3,943 | 112 | import copy
import numpy as np
import torch
from nequip.data import (
AtomicDataDict,
from_dict,
to_ase,
)
def test_to_ase_batches(atomic_batch):
to_ase_atoms_batch = to_ase(atomic_batch)
atomic_batch = AtomicDataDict.to_(atomic_batch, device="cpu")
for batch_idx, atoms in enumerate(to_ase_a... |
6d6dfb6a986282e02b7b450298db6437f470f86b45652a699ece42ff2edb1357 | Python | 3,945 | 85 | """
Loads a dataset and brings it into the required data representation (using Neo).
"""
import argparse
import quantities as pq
from pathlib import Path
import neo
from utils.parse import parse_string2dict, none_or_float, none_or_int, none_or_str
from utils.neo_utils import imagesequence_to_analogsignal, merge_analog... |
3c422ac740803e1a0b67452ceb56f8a6122ef9f69bba08c0ab90e497e7055f54 | Python | 3,948 | 81 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 24 14:43:34 2022
@author: benozzo
"""
import matplotlib.pyplot as plt
from matplotlib import cm
from scipy import stats
import pickle
from library_networks import get_idx_network as get_network_index, get_idx_network_iso, get_idx_network_iso_small, ... |
18464a74295af2bcb1e8e085d243e663fe2257dd7ac5ee4d09c7f1e68e1590bc | Python | 3,953 | 114 | import json
from importlib.resources import files
from io import BytesIO
import cv2
import pytest
from packaging.specifiers import SpecifierSet
from packaging.version import Version
from idtrackerai.base.animals_detection import to_gray_scale
from idtrackerai.utils import telemetry
from idtrackerai.utils.telemetry im... |
415bdb01567fd246bbf7948892e01d621fb559252db4cc2d4798c0bd96c5f2d3 | Python | 3,953 | 102 | """The residual SOC interaction, which `--interaction` offers and nothing built.
`MagneticRealAgnosticResidueSpinOrbitCoupledDensityInteractionBlock` is in
`interaction_classes` and in the `--interaction` choices, and the magnetic tests
all use its non-residual sibling
(`MagneticRealAgnosticSpinOrbitCoupledDensityInte... |
41c072c7e62d851afacc1f925bf712fd29fb954274fc2dff1933bdda5422d09e | Python | 3,955 | 120 | """Plain-data snapshots consumed by the persistence writer."""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Any
import numpy as np
import pandas as pd
from sanpy.trace_overlays import TraceOverlayDefinition
from sanpy.fileloaders.fileMetadata impor... |
8c794cd57aef521d36ea1d4d5f75408de6676d64c758ee7ba68be0e23295a938 | Python | 3,955 | 135 | #!/usr/bin/env python3
import argparse
import matplotlib.pyplot as plt
import numpy as np
import odil
from odil import plotutil, printlog
"""
Demonstrates the use of fields with values centered in cell, faces, and nodes.
"""
def operator(ctx):
res = []
def func(x, y):
return x * 0.25 + y * 0.5
... |
2c601d6a895fe4ec6ec89629ece335362e733862e3612117bcda80a92849042c | Python | 3,956 | 82 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 24 14:43:34 2022
@author: benozzo
"""
import matplotlib.pyplot as plt
from matplotlib import cm
from scipy import stats
import pickle
from library_networks import get_idx_network as get_network_index, get_idx_network_iso, get_idx_network_iso_small, ... |
c7fc00daf525182111b7e531d10a1b709513953be3892c8da95edf6114ce2c99 | Python | 3,957 | 104 |
import random
import numpy as np
import torch
from hyper_dti.settings import constants
def get_collate(mode, split):
""" Wrapper for different collate functions. """
if mode == 'pairs':
return collate_triplets
elif mode == 'drug':
return collate_drug
elif split == 'train':
r... |
d36438787a5662f1af86dbfb8a0838c15037e2e057bbe7900690f4f176eaacf9 | Python | 3,957 | 145 | import ast
import inspect
import pytest
import torch
from mace.calculators import mace_torchsim
from mace.cli import convert_e3nn_cueq, run_train
from mace.tools import model_script_utils
from mace.tools.arg_parser import build_default_arg_parser
from mace.tools.utils import AtomicNumberTable
class _HiddenIrrepsStu... |
8220407e950e54a1133cd8b5b574816d1579d814e3f3263f9a372d92ab3dfb1b | Python | 3,965 | 105 | from .lightning import NequIPLightningModule
from typing import Dict, Any
from lightning.pytorch.utilities.exceptions import MisconfigurationException
from nequip.utils import RankedLogger
import torch
logger = RankedLogger(__name__, rank_zero_only=True)
# Note: Manual `.train()`/`.eval()` mode control for optimizer ... |
a9bd544c4a3167a066bc13ce08a1f8a418aee42e3b62b9127c96b28c28d324d9 | Python | 3,969 | 118 | """Finite-difference stress checks for the published medium Polar model.
Adapted from mace_scf's LocalSplitCharges tests (b7697fb): compact cubic and
triclinic cells, a nonzero normal/shear signal, and periodic-image invariance.
Unlike large dilute boxes, these geometries expose missing electrostatic strain
derivative... |
f4857a13eefd131544b96bcc92f70e412601fdc057101c2082d95e8e31023689 | Python | 3,972 | 107 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 12 15:25:17 2018
@author: ngritti
"""
from csbdeep.models import CARE
# from deeprest.rawDataClass import rawData
# from deeprest.modelClass import modelRest
# from deeprest.timeLapseClass import sampleTimeLapse
import time, os, glob
from tqdm impor... |
8f2b182e801fbc44c93f3c9bbc92d42c67a5af7acc81a5e6472a1b52085ac909 | Python | 3,973 | 124 | # -*- coding: utf-8 -*-
import numpy as np
from scipy.ndimage import gaussian_filter1d
#%%
def return_transient_rate(calcium, nsigma=3):
t_rate = np.zeros(np.shape(calcium))
for neuron in range(len(calcium)):
t_rate[neuron] = transient_mask(calcium[neuron], nsigma= nsigma)
return t_rate... |
971f3da77255f3cef61168c5a777b9fe1897be02f300bf68bd3a36d8d321fb05 | Python | 3,974 | 123 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 12 15:25:17 2018
@author: ngritti
"""
from csbdeep.models import CARE
# from deeprest.rawDataClass import rawData
# from deeprest.modelClass import modelRest
# from deeprest.timeLapseClass import sampleTimeLapse
import time, os, glob
from tqdm impor... |
e593b01ddc9608e7f450032ff5d9b2d5fb28632e903fddfd9508c1771dea8a41 | Python | 3,974 | 130 | import experiment as exp
from data_log import QueuedDataLogger
from canvas import Canvas
class CanvasVideoExperiment(exp.Experiment):
default_params = {
"canvas_id": "1",
"video_url": "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4",
"playback_rate": 1,
... |
c08a24ab41fd048ab99cc5ec73bde5b5610269332f3a9dda960735e7bc71ffc8 | Python | 3,975 | 110 | """
The GOOD-Cora dataset adapted from the `full Cora dataset
<https://arxiv.org/abs/1707.03815>`_.
"""
import os
import os.path as osp
import gdown
import torch
from munch import Munch
from torch_geometric.data import InMemoryDataset, extract_zip
class GOODCora(InMemoryDataset):
r"""
The GOOD-Cora dataset. ... |
f49be02aa2e43bdd40408f75d857d7d0ba3d99a72765ec34e5e5279fe5892e6f | Python | 3,976 | 85 | """
Loads a dataset a brings it into the required data representation (using Neo).
"""
import argparse
import quantities as pq
from pathlib import Path
import neo
from utils.parse import parse_string2dict, none_or_float, none_or_int, none_or_str
from utils.neo_utils import imagesequence_to_analogsignal, merge_analogsi... |
9fa7e563c9e084b06726efd599b7de15809fe50bb750ae16a2279c40a0cc05b3 | Python | 3,979 | 102 | """What a run says when the compiled export fails.
`run_train` saves the model twice: the pickled checkpoint, then a TorchScript
copy next to it under `<name>_compiled.model`. The second one is wrapped in
`try/except Exception`, which is right -- a model TorchScript cannot take is not
a reason to lose a finished train... |
8e3c0de493566978343677b0a557285696cca470f21b29d0a13da7fe03131b47 | Python | 3,985 | 102 | # -*- coding: utf-8 -*-
import os
import requests
from dival.util.input import input_yes_no
from dival.util.download import download_file, compute_md5sum
def download_zenodo_record(record_id, base_path='', md5sum_check=True,
auto_yes=False):
"""
Download a zenodo record.
Unfortu... |
f91c8272a75c1784ac10a16fd6c41e3ba475dc40a66da20885e31d67368d33d6 | Python | 3,987 | 127 | #Loads PSI raw data (projections, darks, blanks) from a single hdf5 file and normalizes the projections.
#Normalized projections are saved as a new hdf5 file. Normalization is done batch-wise due to memory restrictions.
#The input data format is uint16, the output is saved as float32.
import h5py
import tomopy
import ... |
f937dd8ade6a206985396bc871d98568c523af5aa3d87b034a752f3ee5257052 | Python | 3,988 | 103 | # Copyright 2020-2024 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import importlib
import logging
import os
import zipfile
from openfl.federated import Plan
from openfl.federated.data.loader import DataLoader
logger = logging.getLogger(__name__)
def initialize_minimal_dataloader(plan: Plan) -> DataLoade... |
daa014426f8f93afc297e62614066dba8c8446bdcce54d111309c5b1e0c9349a | Python | 3,990 | 102 | """Serialization contracts for automatic Polar compatibility repair."""
import copy
import pytest
import torch
from mace.calculators import MACECalculator
from tests.extensions.polar.test_polar_models import _build_minimal_model
pytestmark = pytest.mark.polar
@pytest.fixture
def polar_calc_model():
return _bu... |
56f14e926664d22e9d98ffd51cedd9059900e82bac7bab5cedf6d23593f6a52f | Python | 3,991 | 122 | # Copyright (C) 2020-2023 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
"""Setup script."""
from setuptools import Command, find_packages, setup
from setuptools.command.build_py import build_py
class BuildPackageProtos(Command):
"""Command to generate project *_pb2.py modules from proto files."""
... |
a5017363264ebf09ed03079551331999b96aa92976e0f9f0bfea612d2fe9ce7c | Python | 3,998 | 123 | from sleepy.processing.processor import Algorithm
from sleepy.processing.parameter import Parameter
from scipy.signal import find_peaks
import numpy as np
class Custom(Algorithm):
def __init__(self):
self.name = "Custom Implementation"
self.durationLow = Parameter(
title = "Lower bou... |
dd81092d584adbeb46de858883647d40eccc0ad113d61e14ba9dd38f5ad6489c | Python | 4,003 | 119 | import glob
import os
import shutil
import accelerate
import torch
from torch.optim import AdamW
from torch.optim.lr_scheduler import CosineAnnealingLR, LambdaLR
from torch.utils.data import DataLoader
from model_angelo.c_alpha.arguments import parse_arguments
from model_angelo.c_alpha.dataset import CASDataset
from ... |
118ddb54b5a89a7f265e049fd3d6f26716b4ab21ad78ce9041007eb2f776d66b | Python | 4,004 | 119 | import math
import random
import geomstats.algebra_utils as utils
import geomstats.backend as gs
from geomstats.test.data import TestData
class AlgebraUtilsTestData(TestData):
tolerances = {
"taylor_functions_even_exp": {"atol": 1e-4},
}
def taylor_functions_even_exp_test_data(self):
fun... |
2da80cb4c0fe56ff67d574283c45904bca3bbfa6aaa70c08323eb549323be6fc | Python | 4,006 | 117 | import os
import numpy as np
from pdb2sql.interface import interface
try:
import freesasa
except ImportError:
print('Freesasa not found')
class BSA(object):
def __init__(self, pdb_data, sqldb=None, chainA='A', chainB='B'):
'''Compute the burried surface area feature
Freesasa is require... |
bf58c3c4a8cc36560de09c322996fb1e0cc55855116d288e179708e439ba184f | Python | 4,006 | 114 | # Copyright (c) 2022 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 ap... |
cf5efe358a54f004b2895d0563ad20a97eff559b8c46abdd5b562b3b29f4154d | Python | 4,009 | 111 | from SHIP import (network,
liN,
inputN,
SurrGradTrainer as trainer)
from braille_task_utils import (load_braille_dataset,
delta_encoding,
izhikevicN,
... |
d2f0f20f4a238807fb79f04b073df763f467f7b14edc3588d8ee50014f6f5083 | Python | 4,010 | 113 |
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import torch
from matplotlib import cm
import mlspm.preprocessing as pp
from mlspm.datasets import download_dataset
from mlspm.models import EDAFMNet
# # Set matplotlib font rendering to use LaTex
# plt.rcParams.update({
# "text.usetex"... |
1c109dad84a44b3d60ae3d1943bf2f1a6dbb1b633cf2241522bb42afa5efe341 | Python | 4,011 | 114 | import pytest
import geomstats.backend as gs
from geomstats.geometry.discrete_curves import SRVMetric
from geomstats.learning.frechet_mean import GradientDescent, variance
from geomstats.test.random import RandomDataGenerator
from geomstats.test.test_case import TestCase
from geomstats.test_cases.learning._base import... |
94b98660c1bdf963bde8bc0e8248552f8b154a4f52f72d87f9bb9d880b3978ad | Python | 4,011 | 121 | __all__ = ["ScaffoldPairGenerator"]
from functools import partial
import logging
import numpy as np
import pandas as pd
from reinvent.chemistry import conversions
from reinvent.chemistry.utils import compute_scaffold, compute_num_heavy_atoms
from reinvent.models.utils.parallel import parallel
from .pair_generator i... |
00b2315d5d21da9811d9900431d9ff4244b57c4f986b5effc8d2265df042169f | Python | 4,012 | 88 | import numpy as np
from numpy.random import randint
from fastdtw import fastdtw
from scipy.spatial.distance import euclidean
from scipy.special import softmax
from sklearn.metrics import confusion_matrix, classification_report
import os
def dtwLit(df, literature_sequences, literature_labels, random_seed: int = None):
... |
5545f97c2b0bf735848459bacfb7940f643e1284f824501ece73067e31105a31 | Python | 4,014 | 133 | # Copyright (c) 2020 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... |
b3276da8457f3ec661853e4542a258222751214182ca251ca0d9813737cf11c8 | Python | 4,015 | 115 | ################################################################################
# Import, Set up MPI Variables, Load Necessary Files
################################################################################
import os
from os.path import join
import sys
import matplotlib
import matplotlib.pyplot as plt
from matp... |
b99e0328b948237e9fc730151421a7d5a94541a10d76be73fd437e397f0048b1 | Python | 4,015 | 91 | from hypothesis import given, strategies as st
from chromadb.api.types import (
optional_embeddings_to_base64_strings,
optional_base64_strings_to_embeddings,
)
import numpy as np
import math
@given(st.lists(st.lists(st.integers(min_value=-128, max_value=127))))
def test_base64_conversion_is_identity_i8(embedd... |
f99b88f5289497cf7c433516b01235f6b74006ab95b95b6d087ac71891428074 | Python | 4,016 | 142 | """Manage IO and signal handling
A context manager to handle IO and signals. Saves data to a file when end of
with block is reached or a signal is received. The data is obtained through
registering a callback. Without this callback no data will be written.
torch.save is used to pickle the data.
"""
import signal
i... |
18be4171fea198364f81b0b921c7ed1b00a67ef4645ae43f96ac4040f4774a8e | Python | 4,018 | 102 | """Real-vs-ghost parity: the core physics contract of the LAMMPS integration.
LAMMPS partitions atoms into local + ghost periodic images and expects the
per-atom energies of the local atoms (and their folded forces) to reproduce
the periodic calculation. This exercises the LAMMPS_MACE wrapper and, through
it, the lamm... |
b907485d3f65eaa523657bcf547728219a2faad512097f5eaed2561ff4359604 | Python | 4,018 | 144 | import pytest
from bigfeta.utils import (
blocks_from_tilespec_pair, ready_transforms)
import numpy as np
import os
import json
import renderapi
import scipy.sparse
import copy
dname = os.path.dirname(os.path.abspath(__file__))
FILE_PMS = os.path.join(
dname, 'test_files', 'montage_pointmatches.json')
... |
f5f0ccae3894d2f6113a2a1c84439fc9993b7d5530ecb6c16747106d528c959c | Python | 4,020 | 125 | from typing import Optional, Sequence, TypeVar
from abc import abstractmethod
from chromadb.types import (
Collection,
MetadataEmbeddingRecord,
Operation,
RequestVersionContext,
VectorEmbeddingRecord,
Where,
WhereDocument,
VectorQuery,
VectorQueryResult,
Segment,
SeqId,
M... |
4c7c58037400e241a61eb960c380c4161b1335a6056eff800173d96ba1e3e7d6 | Python | 4,021 | 110 | # Copyright (c) 2020 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... |
a94767c84e1b35fdadd5b556f384921c30325aa974933c63390abca10273d3b7 | Python | 4,021 | 118 | # This file is a part of the `nequip` package. Please see LICENSE and README at the root for information on using it.
from nequip.data.datamodule import ASEDataModule
from nequip.utils import download_url, extract_zip
from nequip.utils.logger import RankedLogger
import os
from typing import Union, Sequence, List, Call... |
1799a347dca0a50c7eb422cff68f23d3a7ac5fc7fe1684e690b313e518146441 | Python | 4,023 | 150 | from __future__ import print_function
import os
import argparse
import ANNarchy
import numpy as np
import pandas as pd
from time import time as t
plots_path = os.path.join("..", "..", "figures")
benchmark_path = os.path.join("..", "..", "benchmark")
if not os.path.isdir(benchmark_path):
os.makedirs(benchmark_pat... |
13c8098e05be5ef57bd17f49a5239326201c6184ad5354d1c34e35958c76f165 | Python | 4,024 | 101 | import types
import pytest
import torch
from mace.data.augmentation import Random3DRotation
from mace.tools.torch_tools import default_dtype
# ----------------------------------------------------------
# Which symmetries each mode augments
# ----------------------------------------------------------
# non-soc: the f... |
1c7cbeed855d2cf0099835e123d683b69766da74e15e4c2c8f907602f13d1a5b | Python | 4,025 | 102 | import re
from torch_geometric.datasets import Planetoid
from torch_geometric.transforms import NormalizeFeatures
from .TUDataset import TUDatasetExt
from .feat_expansion import FeatureExpander, CatDegOnehot, get_max_deg
def get_dataset(name, task, feat_str="deg", root=None):
r"""A pre-implemented function to r... |
77360cdc721c8e79004f392c3c4c475bb99de6e8eeaaa203f674df9c23cc8534 | Python | 4,026 | 122 | """Random-state utilities for deterministic parallel resampling.
The bootstrap and permutation tests pre-generate one seed per iteration from a
single `random_state`, then give each parallel worker its own `RandomState`
built from its seed. Results are therefore identical for any `n_jobs` and
across CPU and GPU execut... |
cedde9ca0578379a0dda2a06886d3c435e9e8f609d8b08e0f6aa666fdd6d5022 | Python | 4,027 | 117 | from chromadb.api.types import Embeddings, Documents, EmbeddingFunction, Space
from chromadb.utils.embedding_functions.schemas import validate_config_schema
from typing import List, Dict, Any
import numpy as np
from urllib.parse import urlparse
DEFAULT_MODEL_NAME = "chroma/all-minilm-l6-v2-f32"
class OllamaEmbedding... |
03f2ec936dcd1cbe0c019c143701ba388ca04cace74dc73b616b02f279029676 | Python | 4,031 | 91 | import pytest
from reinvent.runmodes.scoring.file_io import TabFileReader
from reinvent.chemistry.standardization.filter_types_enum import FilterTypesEnum
from reinvent.chemistry.standardization.filter_configuration import FilterConfiguration
from reinvent.chemistry.standardization.rdkit_standardizer import RDKitStand... |
6d212d4061c9925c62e4d953c375c8931e3c31e32c5206182f464c884e924dca | Python | 4,032 | 116 | """
BrainVision amplifiers have a default value of -1 for the trigger channel
instead of the conventional 0.
Tested on actiCHamp amplifiers only, verify the default value for your
amplifier.
Correction is done via:
https://mne.tools/stable/generated/mne.io.Raw.html#mne.io.Raw.apply_function
"""
from pathlib import Pat... |
0651e12642a06d5a0ef625f45a105a7f582d747b74e4aea3b259468baeb6f1b1 | Python | 4,034 | 98 | """Sphinx configuration for the VDJdb specification site.
Served as a project page under the org custom domain, so it lives at
``docs.isalgo.dev/vdjdb-db/``. GitHub Pages is already provisioned for this repository with
``build_type: workflow``; nothing here has to create it.
**The schema tables are directives, not ge... |
dc93d0ec5a89de26c84c48c0bb7603505608dca4fd33867cf5206afa356b7a61 | Python | 4,035 | 86 | # -*- 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... |
f8b1254d104ed4bcaa0f74b1621220120998b37cd539f4b6826fb141bd3daa49 | Python | 4,037 | 127 | import logging, itertools
from typing import Dict, List
from util import clustering_louvain_nclust, config_logger
import torch
import numpy as np
from sklearn.cluster import KMeans
from sklearn.decomposition import TruncatedSVD, PCA
logger = config_logger(logging.getLogger(__name__))
def initialize_kmeans(K, Ys, ... |
ad1543be18c379b294a988cfd48a6f31cd2589cf419f933341660e07837a892a | Python | 4,040 | 135 | # -*- coding: utf-8 -*-
import os
import argparse
import logging
import torch
from torch.nn import CrossEntropyLoss, KLDivLoss, NLLLoss, SmoothL1Loss, BCELoss, BCEWithLogitsLoss
import torch
from torch import nn
import torch.optim as optim
from torch.optim.lr_scheduler import ReduceLROnPlateau
import torch.utils.dat... |
510a72dd811abb6e30e2b73474a9118d3c945f83c3c8a43cb080d39e4a459d67 | Python | 4,043 | 185 |
import sys
import argparse
# for py2
try:
BrokenPipeError
except NameError:
import socket
BrokenPipeError = socket.error
from .corpus import (
CORPORA,
corpus_read
)
from .tokenize import tokenize
from .vocab import (
vocab_count,
vocab_quantile,
vocab_pack,
vocab_unpack,
)
from .... |
c2d106a9b6efcfd65246e887f0344836e62e9ffa8d0114e5ec2d7f791b92cd5b | Python | 4,043 | 143 | """Tests for the canonical ``.sanpy`` text loader."""
import numpy as np
import pandas as pd
import pytest
from pathlib import Path
from sanpy.analysisDir import analysisDir
from sanpy.fileloaders import getFileLoaders
from sanpy.fileloaders.fileLoader_sanpy import fileLoader_sanpy
def _write_sanpy(tmp_path, data: ... |
a2451a93ad31e2c837fbdec93503df5c98316d5da0fcfbbbc5b76bb093dc123d | Python | 4,046 | 133 | # ##############################################################
# This file is received from
# https://github.com/DmitryUlyanov/deep-image-prior/blob/master/models/common.py
# The code is licenced under Apache 2.0 licence
# https://github.com/DmitryUlyanov/deep-image-prior/blob/master/LICENSE
# Please also checkout aw... |
5af1f301d363b23f23e9f75b1f43437fc21403c3a29785d9c064d6e7122b51fa | Python | 4,047 | 93 | """
Multivariate Classification
===========================
This tutorial provides an example of how to run classification analyses.
"""
#########################################################################
# Load & Prepare Data
# -------------------
#
# First, let's load the pain data for this example. We ne... |
3a21595aff9f15aa8ccd5522b39e5aa88a96ecf9fb128ca0075b9f750ea99e7a | Python | 4,048 | 115 | from PymoNNto import *
import copy
import pickle
import os
import marshal
compile_class = type(compile('1+1', '<string>', 'eval'))
base_obj_type = TaggableObjectBase#NetworkObjectBase
def add_to_compiled_save_list_and_get_save_str(obj, compiled, compiled_path):
ct = len(compiled)+1
s = '__compile#'+str(ct)+'.... |
c97badf0fa91c8c21f4bc5ca7b3e7e0b794917c582bebfcd31cf606f8a214ea0 | Python | 4,050 | 103 | import numpy as np
import pandas as pd
from pathlib import Path
import matplotlib as mpl
int_types = ['wavefronts_id', 'wavemodes_id', 'wavemode', 'channel_id', 'dim_x',
'dim_y', 'number_of_triggers', 'x_coords', 'y_coords']
float_types = ['spatial_scale', 'sampling_rate', 'recording_length', 'duration',
... |
35c3550a585f0d06c5c0006e7182611eeb94b3e26d41d69cb2375376762cd4a7 | Python | 4,051 | 138 | import experiment as exp
from data_log import QueuedDataLogger
from canvas import Canvas
class CanvasVideoExperiment(exp.Experiment):
default_params = {
"canvas_id": "1",
"video_url": "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4",
"playback_rate": 1,
... |
c343fcb8530462185d66d536f01f97a2aa0d906baf7e5f18e9cc27eb3a81844c | Python | 4,052 | 109 | import logging
import numpy as np
import time
from typing import Optional
import cv2
import json
from tritonclient import utils as client_utils
from tritonclient.grpc import InferenceServerClient, InferInput, InferRequestedOutput, service_pb2_grpc, service_pb2
LOGGER = logging.getLogger("run_inference_on_triton")
c... |
57c7c419fee876699a1fc9a038f085538e3eb0acbce0078dc18b8137aca8cbc8 | Python | 4,053 | 134 | import os
import numpy as np
def standardize_bbox(pcl, points_per_object):
pt_indices = np.random.choice(pcl.shape[0], points_per_object, replace=False)
np.random.shuffle(pt_indices)
pcl = pcl[pt_indices] # n by 3
mins = np.amin(pcl, axis=0)
maxs = np.amax(pcl, axis=0)
center = ( mins + maxs ) ... |
00a7bda3e4d20691099a399d27c64f85d79805684420572ddaa4a13d9a5e10e9 | Python | 4,056 | 136 | import os
import sys
import numpy as np
import pickle as pkl
sys.path.append(os.path.abspath(".."))
sys.path.append(os.path.abspath("../.."))
class BaseFunc(object):
def __init__(self, args):
self.forw_dict = {}
self.back_dict = {}
self._save_dir = './temp'
self._raw_dir = './'
... |
c8cf9b065da68483fcbf82b1b96dcdc7d348bb821df9c8e12dc340e2510c6539 | Python | 4,056 | 121 | """The LibInvent sampling module"""
__all__ = ["LibinventSampler", "LibinventTransformerSampler"]
from typing import List
import logging
import torch.utils.data as tud
from rdkit import Chem
from .sampler import Sampler, validate_smiles
from . import params
from reinvent.models.libinvent.models.dataset import Datase... |
e1ee22b48e47e1c7fabbcc1599d02b20e98c4ebdda1c9f37318eb5358d5e1115 | Python | 4,056 | 101 | """Additional tests for SmilesAssociatedComponentResults and ComponentResults."""
import numpy as np
import pytest
from reinvent_plugins.components.component_results import (
ComponentResults,
SmilesAssociatedComponentResults,
SmilesResult,
)
SMILIES = ["CCO", "c1ccccc1", "CCC"]
SCORES_1 = [np.array([1.0... |
3c950e29c79d314bd696211b2a998bf6f0d93ad9cdc7ae15c3efae4751119559 | Python | 4,057 | 122 | from chromadb.utils import embedding_functions
from chromadb.utils.embedding_functions import (
EmbeddingFunction,
register_embedding_function,
)
from typing import Dict, Any
import pytest
from chromadb.api.types import (
Embeddings,
Space,
Embeddable,
SparseEmbeddingFunction,
)
from chromadb.ap... |
118585edd78b9e5d85fddf543ba0524c426082e2610ef727d05e02dfae12a072 | Python | 4,060 | 119 | import logging
from live2p.server import Live2pServer
### ----- THINGS YOU HAVE TO CHANGE! ----- ###
# Set these first to match makeMasks3D!!!
# I recommend using removing 110 pixels from each side. Maybe 120 for holography. Maybe less for vis stim. But
# it has to match whatever you did in MakeMasks3D.
# also set t... |
fd29811e95139869cb8e1d35aae079ce6272483045900b60db94af9cf08cbd1a | Python | 4,061 | 109 | """
The GOOD-CBAS dataset modified from `BA-Shapes
<https://proceedings.neurips.cc/paper/2019/hash/d80b7040b773199015de6d3b4293c8ff-Abstract.html>`_.
"""
import os
import os.path as osp
import gdown
import torch
from munch import Munch
from torch_geometric.data import InMemoryDataset, extract_zip
class GOODCBAS(InMe... |
94d15687c5cde39af3c97894ba6eccc57de79725c337e71b70597f85c317b1ae | Python | 4,063 | 114 | """Pre-process time series into batched covariance matrices.
The user defines the number of time steps of the batches.
It starts by removing the transient signal by taking a margin on each side
of the sign change. It then creates batches of data that will be used to
build the covariance matrices. In practice, one need... |
c693932ea8bbff31f520799ba6083a8594ef1129e151e537c76fae355f759eb5 | Python | 4,063 | 109 | import torch
from CustomDataset import CustomDataset
from torchvision.utils import save_image
import os
import pdb
import numpy as np
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
from torchvision import datasets
from ImbalancedSampler import ImbalancedDatasetSampler
from PIL imp... |
0066b9ca8fc9c96922fb0b843c403a8f5a80eda0f7a98098fdb8a87246797b54 | Python | 4,064 | 124 | # Copyright (c) 2022 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... |
257192ca59653eabf826974f986b99b887ce32dc3d30e923ebdd3968f3a3e45b | Python | 4,065 | 148 | # -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
import os
import argparse
import logging
import torch
from torch.nn import CrossEntropyLoss, KLDivLoss, NLLLoss, SmoothL1Loss, BCELoss, BCEWithLogitsLoss
import torch
from torch import nn
import torch.optim as optim
from torch.optim.lr_scheduler import ReduceLROnPlat... |
6043df8f26b33dc54e0e57d0fad2c16f823c8c8278b9ff6c30b810d83661cc44 | Python | 4,071 | 178 | """Kernels and kernel pairings using lazy KeOps."""
import geomstats.backend as gs
from geomstats.varifold.base import Pairing
if gs.__name__.endswith("pytorch"):
from pykeops.torch import Vi, Vj
else:
from pykeops.numpy import Vi, Vj
class SurfaceKernelPairing(Pairing):
"""A kernel pairing on surfaces.... |
61f087fe953c9f693cea5bb38e5d66659155c55d6e7d0a9e7d1217b28602bc9a | Python | 4,071 | 111 | # 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.
import logging
from pathlib import Path
import torch
from fairseq import checkpoint_utils
from fairseq.models import (
register_model,
... |
6b6c03503fb2a6d54d0587cc6b7e38fbd1c7072175002411d105aa1db0313b3e | Python | 4,072 | 114 | from PyQt5.QtWidgets import QDialog, QVBoxLayout, QListWidget, QDialogButtonBox, QPushButton, QLineEdit, QHBoxLayout
from PyQt5.QtCore import pyqtSlot, pyqtSignal, QObject
########################################################################
class PickChannelsDialog(QDialog):
"""
Defines the Dialog for sele... |
4d3dc7966c57dbd00a0aba12ea7fdf767b096b61413199c06043bad917a4f55a | Python | 4,073 | 131 | """Compute scores with ChemProp
[[component.ChemProp.endpoint]]
name = "ChemProp Score"
weight = 0.7
# component specific parameters
param.checkpoint_dir = "ChemProp/3CLPro_6w63"
param.rdkit_2d_normalized = false
param.features = "morgan"
param.target_column = "dG"
# transform
transform.type = "reverse_sigmoid"
tran... |
20c3695df56395baa9c69156027f96a7a817e7ad6816c2334a3cffaae578a3de | Python | 4,077 | 134 | from geomstats.test.data import TestData
from .mixins import GeodesicBVPMixinsTestData
class ConnectionTestData(GeodesicBVPMixinsTestData, TestData):
def christoffels_vec_test_data(self):
return self.generate_vec_data()
def geodesic_equation_vec_test_data(self):
return self.generate_vec_data... |
483912aedd173409e909b8b898299f20b44b9cf07f99c87b90222088876128f5 | Python | 4,079 | 123 | from unittest.mock import MagicMock
import unittest
from sleepy.test.core import TestBase
from sleepy.gui.tagging.model.event import IntervalEvent
import numpy as np
import pdb
class IntervalTest(unittest.TestCase):
def getSettings():
settings = TestBase.getSettings()
settings.inter... |
3d41c199c6397b5db46374c4822b43ae6b7585b293c84a455461d35ab0606fe2 | Python | 4,081 | 134 | # -*- coding: utf-8 -*-
"""
Created on Fri Feb 24 15:33:08 2023
@author: nicol
"""
"""
For Fig 2B go to:
Z:\people\gritti\IRIR\supFig2_3
"""
import os
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
import pandas as pd
plt.rcParams.update({'font.size': 15})
rc('font', size=8)
rc('font... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.