sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
534145d87b268ff15cdd052a14813aa0b74d43e0013a73ebd1e121b89e7e157d
Python
5,380
155
# 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 dataclasses import dataclass, field from typing import Dict, List import torch from fairseq import metrics, utils from f...
5238093623f72a4459aedb552873382bf7a4dbb96339f32ecca3aeb223655025
Python
5,384
151
from typing import Sequence, Union import torch import torch.nn as nn from monai.networks.blocks.convolutions import Convolution, ResidualUnit from monai.networks.layers.factories import Act, Norm from monai.networks.layers.simplelayers import SkipConnection from monai.utils import alias, export class UNet_double(nn...
cef8f9a3c6a2d4b0aac357f190c3ec9bc075c17cd238fe1aa07332dc6220a4c2
Python
5,385
152
from typing import Optional, List import torch from torch import Tensor import torch.nn.functional as F from torch.nn import (ModuleList, Linear, BatchNorm1d, Sequential, ReLU, Identity) from torch_sparse import SparseTensor from ..models import ScalableGNN from ..models.pna import PNAConv cla...
d35ec82b78b489443324379fe990513c1bf1d7ca61aff1832b1247a2bd3358a9
Python
5,386
164
from pathlib import Path # Method for starting up child processes. Valid values are "spawn" and "fork". # See https://docs.python.org/3/library/multiprocessing.html#contexts-and-start-methods process_start_method = "spawn" # Logging level of process and main loggers. log_level = "INFO" # Max number of recent log lin...
7559da245f696b21117782abf8ce0175cc1ba900e44899f679a47f55c7c7c341
Python
5,387
137
# This file is a part of the `nequip` package. Please see LICENSE and README at the root for information on using it. """ Functions for loading models from checkpoint files. """ import torch import hydra import warnings from nequip.model.utils import ( override_model_compile_mode, _EAGER_MODEL_KEY, ) from neq...
74134ddaa4dd3e36cbea991da1a439088097b8a56e89dc15556207706ce4bdb3
Python
5,389
161
"""Utility functions.""" # Authors: Mainak Jas <mjas@mgh.harvard.edu> # Sam Neymotin <samnemo@gmail.com> # Christopher Bailey <cjb@cfin.au.dk> import numpy as np from .externals.mne import _validate_type def _hammfilt(x, winsz): """Convolve with a hamming window. Parameters ---------...
8ee0d672fbde50a60aee7dfdde1fe277bdae4156720b91f94e809657705c2b39
Python
5,390
153
"""Build, validate, and reopen a local-only DANDI Dandiset.""" from __future__ import annotations import logging import re from dataclasses import dataclass from pathlib import Path from typing import Sequence from dandi.dandiset import Dandiset from dandi.organize import FileOperationMode, OrganizeInvalid, organize...
02253615d5d0f5d97cd0252c1e2a4087ef1a52595131d7c5b1993221da17485a
Python
5,391
165
""" Loss functions! """ from typing import Optional, Sequence, Tuple import torch from torch.nn import functional as F from foldingdiff import utils def radian_l1_loss(input: torch.Tensor, target: torch.Tensor) -> torch.Tensor: """ Computes the loss between input and target >>> radian_l1_loss(torch.tens...
837f41e14754b6fe3341b807e0416cff0ebfe263c9d53435935a43a8e0978318
Python
5,392
138
import pytest import pathlib import subprocess import numpy as np import torch from nequip.data import to_ase from nequip.integrations.ase import NequIPCalculator from ase.io import read from conftest import _check_and_print from hydra.utils import instantiate @pytest.mark.parametrize( "device", ["cpu"] + (["...
9cbda2e81eaa4372c767c4ddc939b487acc773e7b2fa75ca52b537154601463b
Python
5,392
167
import random import geomstats.backend as gs from geomstats.test.data import TestData from .base import VectorSpaceOpenSetTestData from .lie_group import MatrixLieGroupTestData from .matrices import MatricesMetricTestData class GeneralLinearTestData(MatrixLieGroupTestData, VectorSpaceOpenSetTestData): trials = ...
5e8bb371cf4ad42787484ed1d9cfb6bf4d9c8d8c18c7873f0ba66e0353725364
Python
5,399
159
from chromadb.api.types import ( Embeddings, Documents, EmbeddingFunction, Space, ) from typing import List, Dict, Any, Optional import os from chromadb.utils.embedding_functions.schemas import validate_config_schema from typing import cast import warnings BASE_URL = "https://api.cloudflare.com/client/...
88f3e05208a5393a86ab7611a6c1130874bb83cabc9809ee50aff1c75658827b
Python
5,401
171
"""Generates preprocessed metadata (age and sex) from NSRR datasets. It creates a csv file with columns subject_id, age and sex, one row per subject, one file per dataset. This file allows analyzing the distribution of per-subject sleep spindle features by sex and age. """ import os import sys from pprint import ppri...
d1aa028a1abe9be92482fa56fc1ec2362513b93d21fd58137f51051fc6fcab33
Python
5,409
179
# This file is a part of the `nequip` package. Please see LICENSE and README at the root for information on using it. import os import json import hashlib import pathlib import shutil from datetime import datetime from typing import Optional, Callable, Final from nequip.utils.logger import RankedLogger logger = Ranke...
34db57b132f8aa66538336e54b72ee52c2e15a7434f6f9df0e9761ad5d08d2d8
Python
5,414
148
from qtpy.QtCore import QPointF, Qt, Signal # type: ignore[reportPrivateImportUsage] from qtpy.QtGui import QColor, QColorConstants from qtpy.QtWidgets import QInputDialog, QVBoxLayout, QWidget from idtrackerai.GUI_tools import ( AddBtn, CanvasMouseEvent, CanvasPainter, CustomList, LightPopUp, ...
94bfd9953e5a672076b45a99458d98d9174547e5179c73066bb545e90b95cc3b
Python
5,416
178
from __future__ import annotations import numpy as np import scipy import scipy.stats as stats from neurodesign import msequence def order( nstim: int, ntrials: int, probabilities: list[float], ordertype: str, seed: int | None = 1234, ): """Generate an order of stimuli. :param nstim: Th...
fa5e1109ca80f40acee5f8c3ad7a140622398972de4cf68671febf076219c7be
Python
5,416
155
# Copyright (C) 2020-2024 Intel Corporation # SPDX-License-Identifier: Apache-2.0 """Docs configuration module.""" # 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: # http://www.sphinx-doc.org/en/maste...
175946a71e457bbec938a182353e05e317dc512279596c5a5a770714dce76cf2
Python
5,420
151
from typing import Any, Callable, Dict, List, Optional, Sequence, Set import numpy as np import numpy.typing as npt from chromadb.types import ( LogRecord, VectorEmbeddingRecord, VectorQuery, VectorQueryResult, ) from chromadb.utils import distance_functions import logging logger = logging.getLogger(_...
45839394436e227fe35cebcb05221143fc69203f1a3bb825c4666143de4ec7de
Python
5,423
141
# Copyright 2020-2025 Intel Corporation # SPDX-License-Identifier: Apache-2.0 pass import numpy as np import logging from openfl.experimental.workflow.interface import FLSpec, Aggregator, Collaborator from openfl.experimental.workflow.runtime import LocalRuntime from openfl.experimental.workflow.placement import aggre...
aa00b04da908e09a4670e82934709724294d886102f42082bc36bbb4476d907d
Python
5,424
155
"""Tools to generate a Snakemake-based BIDS app. This legacy module once had the core snakebids bidsapp implementation, but now is a simple wrapper around :mod:`snakebids.bidsapp` with the :class:`~snakebids.plugins.SnakemakeBidsApp` plugin. For new apps, this functionality can be more flexibly implemented with: .. c...
89fb69cb3fd4219aa867787dc51fc788f293751638f9139542b6567065b7128a
Python
5,425
143
# 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 # # Un...
069a39ff75ae718b41bbe003cf3ec10fa2a9472f824f6835f9350786b81d2ea3
Python
5,426
124
""" This script takes in the sequence fasta files generated from Step2 and processes each sequence in each fasta file through the iupred tool. Note that the input files have to be of naming convention step2/[prot,peptide]_sequences.fasta, and that the results will be stored in the subfolder step3, in the current workin...
e9bbd0b11f1cc460e62a469581431b9d092f051b6c06384ee8d2f8af497fc13f
Python
5,426
130
# -*- coding: utf-8 -*- # # # PyRates software framework for flexible implementation of neural # network models 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 Cognitive...
a20ff8e30d30950398bbef42077025c5ae63bb162db33b575d910e0f7835a15a
Python
5,429
154
"""Programmatic NaviDiv demo — no Streamlit required. Loads sample_molecules.csv (bundled in this directory), runs all diversity metrics, prints a summary table, and writes outputs to ./demo_output/. Usage: conda activate NaviDiv python run_demo.py Requirements: navidiv installed (pip install -e /path/to/Nav...
df7dfdabb1df72cbf5a04e39bd76cc5c40e8410e132df177b3df9acd955fdb08
Python
5,429
145
import torch import torch.nn as nn from .nnutils import create_var, index_select_ND #from mpn import atom_features, bond_features, ATOM_FDIM, BOND_FDIM import rdkit.Chem as Chem ELEM_LIST = ['C', 'N', 'O', 'S', 'F', 'Si', 'P', 'Cl', 'Br', 'Mg', 'Na', 'Ca', 'Fe', 'Al', 'I', 'B', 'K', 'Se', 'Zn', 'H', 'Cu',...
1b430c39fcdd413325dda18cd383143dc450053354e1f280a5b9c0eae3b9d10d
Python
5,430
150
# Method signatures differ between Qt bindings, so overrides can't match them all # pyright: reportIncompatibleMethodOverride=false import logging from collections.abc import Sequence from qtpy.QtCore import Signal # type: ignore[reportPrivateImportUsage] from qtpy.QtCore import Qt from qtpy.QtGui import QWheelEvent ...
0a2ee598da39aeaae676c4548242608f5cd8a137a83ce52e0d79a94420074d25
Python
5,431
174
from uuid import uuid4 import pytest from chromadb.api import ClientAPI from chromadb.errors import ConditionalWriteConflictError from chromadb.test.conftest import reset, skip_if_not_cluster EMBEDDING = [1.0, 2.0, 3.0] def _collection(client: ClientAPI, name: str = "conditional_txn"): reset(client) retur...
9b88a7aeab335ec90676ae4538cd9e18a380abfcc890465c4f38101b5def07b6
Python
5,433
152
"""Tests for nltools.algorithms.neighborhoods module.""" import numpy as np import nibabel as nib import pytest from scipy import sparse from nltools.algorithms.neighborhoods import ( _SphereNeighborhoods, compute_searchlight_neighborhoods, ) # ===============================================================...
0801504e3c35b6da3cb0f6c79c343643db41cafd665da23296636ef14137d937
Python
5,434
177
import logging import os import shutil from collections import OrderedDict import torch from torch import distributed as dist from torch import nn from torch.nn import functional as F from sklearn.metrics import confusion_matrix import numpy as np logger = logging.getLogger(__name__) def reduce_tensor(tensor, n): ...
b5515fb918985457a2469508a8667bb87063675e59b07827566dd6cf63116bad
Python
5,435
100
# -*- 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...
11d82a23151d952e4fc596d634428504aaeb62adf71c46a12d47cf5c23c72b76
Python
5,437
188
from __future__ import print_function, division """ Brain-Glass Interface Controls the visual feedback on Google Glass. When connected with USB cable, connect to the local loopback network (127.0.0.1). adb executable must be in the system's PATH environment variable. Kyuhwa Lee, 2018 Swiss Federal Institute of Tech...
81c34c160dfb2fe3d6a836c43152043dc51276bd16257b0942fe8816c125d04c
Python
5,444
148
# 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...
6d38021672c2e2693cb657020e5e9b184e1885ea0d180d908384b6d682b8871e
Python
5,445
190
#!/usr/bin/env python3 import argparse import matplotlib.pyplot as plt import numpy as np import odil from odil import plotutil, printlog """ Infers unknown constant parameters of an advection-diffusion equation from the solution at the initial and final time. """ def get_ref_u(t, x, args): """ Returns an...
1e0668379ba0a8a55da50c5ad3dc5ab85354e75e44abff4745c795d4b1a79e14
Python
5,446
135
"""Contract tier: the ML-IAP energy/force writeback, on both couplings. LAMMPS ships two ML-IAP Python couplings with *different* writeback APIs, and the difference is invisible until the model has already run: * ``src/KOKKOS/mliap_unified_couple_kokkos.pyx`` — ``eatoms`` has a getter (a view sized by ``nlistatoms`...
04eba62ef527c85d1c998badb0360269aa0ea9a06a4251a1b19e825f2e6e6dbd
Python
5,452
166
import pytest import geomstats.backend as gs from geomstats.test.random import RandomDataGenerator from geomstats.test.test_case import TestCase from geomstats.test.vectorization import generate_vectorization_data class _ManifoldTestCaseMixins: # TODO: check default_coords_type correcteness if intrinsic by compa...
c334a5a50c978410997d14f60061d9efc5aae9296400dbbddc2f6c05dc0f953d
Python
5,456
128
"""The antigen nomenclature patch. `curate/patch.py` was 45 % covered. Three of its behaviours were each chosen to reproduce a measured legacy result, and none of them had a test: `NA` is a gene symbol rather than a missing value, duplicate epitopes resolve to the last entry, and an empty patch cell falls back to the ...
61055f7224af0adea9400500dc52a0582c91692bffb2d75807d44527bde40d61
Python
5,457
148
# -*- coding: utf-8 -*- # ---------------------------------------------------------------------------------------------------------------------------------- # Функция для вычисления Most Similar Words # # Парметры: # tmlda_filename: файл в формате TMLDA, из словаря которого берутся слова для поиска ближайших ...
36ef5f3b0dbeb67e1c3c7100980bc5a71df8cf637b6b48b5f42be78910b88120
Python
5,461
169
#Translates DNA sequences in all 6 reading frames, ignoring start / stop codons. from Bio import SeqIO from Bio.Seq import Seq from Bio import AlignIO import sys import tempfile import subprocess from collections import Counter from scipy.spatial import distance import numpy as np import os def translate_6frames(inpu...
71765c6fa45926b540d3ebd7957862165c79b78f70c50dba9c62b663ced463aa
Python
5,461
188
import numpy as np import scipy.signal as sig import scipy.stats as stats from scipy.stats import median_absolute_deviation as mad import pickle from pyimzml.ImzMLWriter import ImzMLWriter from pyImagingMSpec.inMemoryIMS import inMemoryIMS from scipy.io import loadmat import random from tqdm import tqdm from ...
679ca1ccfc464fb2914b09d9f7802d06fce553d53d21cc6e36377346f0139e9f
Python
5,462
138
import gc import logging from itertools import pairwise from pprint import pformat import numpy as np from idtrackerai import ListOfBlobs, ListOfFragments, ListOfGlobalFragments, Session from idtrackerai.base.network import IdentifierBase from idtrackerai.utils import track def tracker_API( session: Session, ...
4f42f6cc4977ff9e4eeed622253630f739206b5babd7d767757e070b971c18a8
Python
5,464
163
# Copyright 2020-2024 Intel Corporation # SPDX-License-Identifier: Apache-2.0 """Common functions for gRPC transport.""" import logging import threading from concurrent.futures import ThreadPoolExecutor import grpc from openfl.protocols import aggregator_pb2 logger = logging.getLogger(__name__) MAX_METADATA_SIZE_...
563cd382c63746016c37926f1cfdbcb52ee7c6b97f7f891deb87b235e774f65e
Python
5,465
147
import pydicom as dicomio import SimpleITK as sitk import glob import xml.etree.ElementTree as ET import platform import numpy as np import nibabel directory_split = "\\" if platform.system() == "Windows" else "/" def get_length(number_of_slices, thickness): return (number_of_slices * thickness) / 10 def convert...
6dc5e18728d430616feb494fd4f59b6cb728557a3c35cf9dfcac2e2700cfa26f
Python
5,468
151
''' Utilities to perform the creation of JSON files starting from the xml files. ''' import json import xml.etree.ElementTree as ET import argparse import os parser = argparse.ArgumentParser() parser.add_argument("voc07_path", help="Path to VOC2007 folder", type=str) parser.add_argument("voc12_path", help="Path to VOC...
1041700ea68593789e3e276ed01d888e18936be9f78839783c4e89964af92f3c
Python
5,469
101
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 6/12/23 11:29 AM # @Author : zhangchao # @File : demo.py # @Email : zhangchao5@genomics.cn import os import sys import warnings import argparse from typing import Union from spatialign import Spatialign sys.path.append(os.getcwd()) warnings.filterwarnin...
534775572864c65830e6c7086fdc5657247e70864c0e0b0cdbdc0de97e6bd48f
Python
5,472
143
"""Exercise the real checkpoint downloader with offline HTTP responses.""" import io from email.message import Message from pathlib import Path from unittest.mock import Mock import pytest from mace.calculators import foundations_models as fm class Response(io.BytesIO): """Minimal context-managed HTTP response...
e4890fb93ce399e79c14c30e7c27f43e30c101222cf9ce6b098dd01f046b2986
Python
5,472
181
#! /usr/bin/env python import platform from pathlib import Path import os import subprocess import shutil from setuptools import setup, find_packages, Command from setuptools.command.build_py import build_py descr = """Code for biophysical simulation of a cortical column using Neuron""" DISTNAME = "hnn-core" DESCRIP...
63c5376a484396576b6ea53b992bd014db20e483dc5fc03c8185c08ac1f32ae2
Python
5,473
108
# Copyright 2020 Forschungszentrum Jülich GmbH and Aix-Marseille Université # "Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements; and to You under the Apache License, Version 2.0. " from mpi4py import MPI import os import json from nest_elephant_tvb.utils import create_...
3521e57c08e5777dfb6579aa201c36c3637d7c32b00d26e1e146f1b67bb38184
Python
5,474
169
#!/usr/bin/env python from hnn_core import ( MPIBackend, duecker_ET_model, simulate_dipole, ) from hnn_core.hnn_io import ( write_network_configuration, ) def create_duecker_model_with_drives(): """Create a Duecker ET model network model including 3 evoked drives. Builds the Duecker ET netwo...
8055f060a2ea4f2a2d6e1cdbfa0adfaefea242e817925861611a9a9670e330e6
Python
5,474
147
import paddle import paddle.nn.functional as F from ppdet.modeling.losses.clrnet_line_iou_loss import line_iou def distance_cost(predictions, targets, img_w): """ repeat predictions and targets to generate all combinations use the abs distance as the new distance cost """ num_priors = predictions....
28e2f95f8c0b0e1b37c4dfc42dd7018a7835d6d0e1e570bb408998718e9435f2
Python
5,476
169
from PyQt5.QtWidgets import QMainWindow, QAction, QShortcut from PyQt5.QtGui import QKeySequence from PyQt5.QtWidgets import QStackedWidget from PyQt5.QtGui import QIcon from sleepy.gui.tagging.view import NullView, TaggingView from sleepy.gui.tagging.control import TaggingControl from sleepy.gui.processing.core ...
c40f7305d04cb09b6a27990f99c0bc14548afd43e64113081879cd7609ed0693
Python
5,476
172
""" Shared pytest fixtures for nltools test suite. This module provides common fixtures used across test modules. # Brain Data Fixtures Guide # ========================= # # Choose the right fixture for your test: # # | Fixture | Voxels | Samples | Use Case | # |----------------...
6d46e0ecb1d6db148fa5037ffda06104f84090543dd5d875bbaa731f65c186de
Python
5,477
101
import numpy as np from scipy import sparse import time from suns.PostProcessing.evaluate import GetPerformance_Jaccard_2 def refine_seperate(masks_final_2, times_final, cons=1, thresh_mask=0.5, ThreshJ=0.5): '''Refine segmented neurons by requiring them to be active for "cons" consecutive frames. The ou...
357919d2a7c093bd56df0f9102d6310206920226224ad706e0a493def5fa609b
Python
5,478
165
""" Auditory Steady State Response Stimuli @author: Mathieu Scheltienne """ import numpy as np from ._sound import _Sound from ... import logger class ASSR(_Sound): """ Auditory Steady State Response Stimuli. Composed of a carrier frequency 'fc' which is amplitude modulated at 'fm'. By default, a ...
54d0494ecc56c3f1726e0dfd4686aaa177979ca0c633ccd3ef20c2d294ac4583
Python
5,479
177
from collections import Counter from pathlib import Path import click import pydicom def print_stats(counter: Counter) -> None: for key, value in counter.items(): print(f"\t\t{key} - {value}") @click.command() @click.option( "-d", "--dicom-dir", type=click.Path(exists=True, readable=True, p...
a1982d1c26f36e217589ab44bc02c06b3ea1e4bd6f625294ef77b1d50ce2e7d9
Python
5,483
131
# -*- coding: utf-8 -*- # # # PyRates software framework for flexible implementation of neural # network models 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 Cognitive...
0e4121960a1c60603505122886b7f81b83b497d69880d0a4d026c8fc5091dd45
Python
5,485
160
import types import pytest import torch from e3nn import o3 from mace.calculators.lammps_mliap_mace import LAMMPS_MLIAP_MACE from mace.modules import blocks from mace.modules.blocks import ( RealAgnosticDensityResidualInteractionBlock, RealAgnosticResidualNonLinearInteractionBlock, ) from tests.integrations.l...
8f47c818cc803397f27221abf52b3fe173ee92cb5dcae745499951059ca800e4
Python
5,487
162
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: malfatti @date: 2019-07-27 Loads data recorded by Open Ephys in Binary format as numpy memmap. DatLoad(Folder, Processor=None, Experiment=None, Recording=None, Unit='uV', ChannelMap=[]) Parameters Folder: str Folder containing at least the s...
dacf03e1c2d7afa429fa074e59b12bf44445e99bd211f11256225af813360220
Python
5,488
191
"""Exponential barycenter. Lead author: Nicolas Guigui. """ import logging import geomstats.backend as gs from geomstats.geometry.euclidean import Euclidean from geomstats.geometry.lie_group import LieGroup, MatrixLieGroup from geomstats.learning.frechet_mean import ( BaseGradientDescent, LinearMean, _Ba...
05d23960667994bde0cbcb3f4bf8a4a413887147ad536ea24eab88ffaf182ab8
Python
5,492
156
# This document contains functions used to analyze time series of vasomotion # Input data is time series data from 2p imaging. Images are first processed in FIJI to create csv files of diameter changes over time # Output is values from the provided functions that can be used to examine metrics of vasomotion time s...
c1fd59909dda59b43cfdc1a353f3b6417eeeb21609692828e4cc8885db40ad8c
Python
5,493
142
""" Analysis of Delayed Differential Equations ========================================== In this tutorial, you will learn how to implement and solve delayed differential equation (DDE) systems via PyRates. DDEs take the general form .. math:: \\dot{\\mathbf{y}} = \\mathbf{f}(\\mathbf{y}, t, \\mathbf{y_{\tau}}) ...
72b537736302b1a2549c3fb6407f2d5103e9ed17e07c4b3fc9f7c7f0ae329f73
Python
5,494
211
import numpy as np from numba import njit import pandas as pd @njit def _computeDistance(p1, p2, dxy=0.1, dz=0.5): """compute euclidean distance of two points in space. Points are in (Z, Y, X) format""" di_z = (p1[0] * dz - p2[0] * dz) ** 2 di_y = (p1[1] * dxy - p2[1] * dxy) ** 2 di_x = (p1[2] * dxy - ...
a3836c956d46530349c8f866505e49588fd88a529da17281923f584911c87f00
Python
5,494
154
"""mass_ss.py: Defines the MASS class that manipulates the MASS database.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from sleeprnn.data.dataset import Dataset from sleeprnn.data.dataset import KEY_EEG, KEY_MARKS, KEY_N2_PAGES, KE...
5a1f895eb75f84038acf0128d49c528284f2317c7d4c8784662e41a65471cd96
Python
5,497
160
""" Create BANKSY Matrix from annadata Yifei May 2023 """ import os import numpy as np import matplotlib.pyplot as plt import scipy.sparse as sparse from scipy.sparse import csr_matrix, issparse import anndata import gc from datetime import datetime from banksy.main import concatenate_all def create_banksy(adata: a...
0f51f59e940352355c07e3407c5adea698039e0ecf0d74678aa0e85f2b3b283d
Python
5,498
193
# ============================================================================== # Copyright 2025 Technical University of Denmark # Author: Nikolas Borrel-Jensen # # All Rights Reserved. # # Licensed under the MIT License. # ============================================================================== import jax.numpy...
9f374fed7d187743294fc355893ab677dd38d8a5b6db6cb569727e5cd740bc97
Python
5,499
162
from sleepy.processing.processor import Algorithm from sleepy.processing.parameter import Parameter from .Classifier import classifierTSI from .Tree import Tree import numpy as np import csv from .utils import sfd, flatten import dill import multiprocessing from multiprocessing import Semaphore from .Simulation import ...
a099fae7f2fbe61693726ef96b89a1cd897ad0c5baa5f801030523d5fe8877ce
Python
5,501
170
import os import click from corgie.log import logger as corgie_logger from corgie.boundingcube import get_bcube_from_coords from corgie.cli.compute_stats import ComputeStatsJob from corgie.argparsers import ( LAYER_HELP_STR, corgie_optgroup, corgie_option, create_stack_from_spec, ) from corgie.cli.norm...
3f1aad85853a304e099d8e6cdeddaf0f8c9582d1042c3020ad0004a0d8cc54f1
Python
5,503
171
import gc import torch import torch.nn as nn import torch.nn.functional as F crossentropyloss = nn.CrossEntropyLoss() # the reconstruction function: mse, mse, bce def reconstruction_loss_BCE(X, A_norm, X_hat, Z_hat, A_hat): """ reconstruction loss L_{rec} Args: X: the origin featur...
8a854d321e67dccbabc25e92de0dfb6af8194a4fb3a04b1f1894ec1270e224b6
Python
5,505
162
import matplotlib.pyplot as plt import numpy as np import csv ekw = dict(ecolor=(0, 0, 0, 1.0), lw=1, capsize=3, capthick=1) color1 = (0, 176/255, 80/255, 1) color2 = (1/255, 127/255, 157/255, 1) color3 = (120/255,110/255,120/255,1)#(117/255,117/255,117/255,1)#(253/255, 97/255, 0, 1) #color11 = (0, 176/255, 80/255, ...
6ff8daf1ef03393ab189d4d2197dded64eab78fc5d55e44fb40fc821999f795a
Python
5,508
113
"""The proteome authority for `antigen.gene` (#632): the table's shape, and what it must not claim.""" from __future__ import annotations from pathlib import Path import polars as pl import pytest from vdjdb.curate import antigens as A TABLE = Path("proofreading/epitope_proteome.tsv") @pytest.fixture(scope="modul...
ccfaf6d97fea7bf59b054f6225ebabbfe13ccb2d0eb2ccd5bdedb3168f3fefab
Python
5,512
151
"""Copying that leaves the clone owning its own buffers. A data class holds polars frames whose storage may be a view onto a NumPy array the user still holds, and frames whose `pl.Object` cells are Python objects shared with the original. Copying either naively hands the clone a buffer or a cell somebody else can muta...
7bae53ce8d71fedc9d500895d2758ae96a5ed2619c205eac32465cd6a624cf43
Python
5,514
182
import pickle import os import random import torch import numpy as np from torch.utils.data import Dataset, DataLoader from .mol_tree import MolTree from .jtnn_enc import JTNNEncoder from .mpn import MPN from .jtmpn import JTMPN from .vocab import Vocab class PairTreeFolder(object): def __init__(self, data_fold...
84e4a3fc65ce74bae401763b8e7a83aa57bf0bb4db3e87209a90cd5bcfe07694
Python
5,515
93
"""Distinct-junction overlap screens for tracing experimental provenance.""" from __future__ import annotations import polars as pl STRATUM = ["species", "antigen.epitope", "mhc.a", "mhc.b", "mhc.class"] GROUP = ["chunk.file", "reference.id"] MIN_SHARED = 5 MIN_CONTAINMENT = 0.20 def overlaps(records: pl.DataFrame,...
80f30e028b812ce15c4644ca48d1d7f605e5ab564f288409a636d0160b36bbbb
Python
5,517
141
import numpy as np from scipy.stats import pearsonr from numpy.testing import assert_warns, assert_raises, assert_array_almost_equal, assert_allclose try: from gemmr.estimators import SparsePLS from gemmr.estimators.r_estimators import _check_penalty, _check_penalty_cv, _fit_and_score_spls, \ _select_...
61fef6104617ba5d26fe5c90b356baeb2bbce83de11904514812e6b0b9d72869
Python
5,522
219
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from brian2 import * from scipy import optimize import re # regular expressions # Initialization areas = ['EC', 'DG', 'CA1', 'CA3'] types1 = ['exc', 'inh'] types2 = ['E', 'I'] scale_aussel = 150*umetre # ============== # Optimization # ============== def parse_coords(fn...
0a3d00c09e062be66c61f6d7d3b9d07dfef3562404b5edbd8aa4c39e329f808d
Python
5,524
183
""" Implementation of dFC methods. Created on Jun 29 2023 @author: Mohammad Torabi """ import time import numpy as np from ksvd import ApproximateKSVD from sklearn.linear_model import orthogonal_mp_gram from ..dfc import DFC from ..time_series import TIME_SERIES from .base_dfc_method import BaseDFCMethod #########...
9e9c476f349d74d1f021e0014dbcb1977284c48e7dad57692dcdc28feceb1fc2
Python
5,524
139
"""experiment for the ADT Network.""" import glob import json import logging import os # set gpu private os.environ['TF_GPU_THREAD_MODE'] = 'gpu_private' import tensorflow as tf import numpy as np import sys # add base path to sys sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..')) from task2_regres...
95823a44e6656e885d97b8d8e7743db2cff47df117fa0d53440bfdeb5e0547f9
Python
5,527
187
# -*- coding: utf-8 -*- import random import os #import sys #import collections #import gc import numpy as np import tensorflow as tf from sklearn.model_selection import KFold #from sklearn.utils import shuffle #from JSLog import JSLog #from JSData import JSData #from JSModels import JSModel_MH_DSCNet #from JSExpe...
904c7331364164d80ca90f207491fdfa9f95e614af4e3ddf8789d6bb21ce436b
Python
5,530
139
from typing import Optional import config import pandas as pd explicit_folder_coding = { '184_styleGAN2_Gamma2_013000kimg': 'StyleGAN 2 & $\\gamma$: 2', '184_styleGAN2_Gamma5_020000kimg': 'StyleGAN 2 & $\\gamma$: 5', '184_styleGAN2_Gamma8_025000kimg': 'StyleGAN 2 & $\\gamma$: 8', '184_styleGAN3_Gamma2...
f76d5d6bb6bfa6d4baab9eab252364b26d97801137637f9075ce504987cddf36
Python
5,530
147
import logging from idtrackerai import IdtrackeraiError, ListOfBlobs, Session from idtrackerai.utils import create_dir, remove_dir from .segmentation import compute_background, load_custom_background, segment def animals_detection_API(session: Session) -> ListOfBlobs: """Segments the video and returns the detec...
cb6f5022c1896063b269b3847d308bc1668c3c5b8cc2aacdbf59c6aa51e812b6
Python
5,533
167
# Copyright (C) 2020-2024 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 torchvision import datasets, transforms from openfl.federated import PyTorchDataLoader logger = getLogger(__n...
5f2598f28ffb532a540dfc96362f7dfbf7a2be52afddf92d2196179c16d3b5b1
Python
5,534
218
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from brian2 import * from scipy import optimize import re # regular expressions # Initialization areas = ['EC', 'DG', 'CA1', 'CA3'] types1 = ['exc', 'inh'] types2 = ['E', 'I'] scale_aussel = 150*umetre # ============== # Optimization # ============== def parse_coords(fn...
e124d8bb416be75b322429e64882990f3e8138a57b2b93139ff8bf1fd499e15e
Python
5,535
155
import numpy as np import torch from torch_geometric.nn import to_hetero, SAGEConv, GraphConv, TransformerConv, GATConv from torch.nn import Linear, Dropout, ReLU, Tanh import random class GrigSearchGNNEncoder(torch.nn.Module): def __init__(self, hidden_channels, out_channels, nb_hidden_layer=2, layer_type='s...
5e24fc41109a3b1c08648e1f5ad613dd5d181d5730e0a985a1d0f3ed99580e88
Python
5,536
207
#!/usr/bin/env python3 # # Sniffles2 # A fast structural variant caller for long-read sequencing data # # Created: 27.08.2021 # Author: Moritz Smolka # Maintainer: Hermann Romanek # Contact: sniffles@romanek.at # import bisect import re import statistics import sys import time from typing import TYPE_CHEC...
6ad845dfdd829583db5ef90d1baef00bca6f9ae5e0a2bc345eba9e6f0a93e18a
Python
5,536
139
# 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.model.utils import _EAGER_MODEL_KEY from nequip.train.lightning import _SOLE_MODEL_KEY from nequip.nn import graph_model from nequip.data._nl import DEFAULT_NEIGHBORLIST_BACKEN...
0fdc817e35038306d0a6a25a0036c123bac88743d94823b655bacacefb0e009e
Python
5,539
149
# 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 ...
70c1b9fd8f827374b97ca55bdacd883fa46fd06af0b3a93ac87fd519a7508cdf
Python
5,540
150
# # For licensing see accompanying LICENSE file. # Copyright (C) 2022 Apple Inc. All Rights Reserved. # from torch import nn from typing import Optional from utils import logger from ..layers import LinearLayer, GroupLinear, norm_layers_tuple supported_conv_inits = [ "kaiming_normal", "kaiming_uniform", ...
6391d92e574e58b995eab5f0a61d148cb1bce0ad9109c015d75c0ba5dc8d9811
Python
5,541
163
"""Transformer for manifold-valued data. Lead author: Nicolas Guigui. """ from sklearn.base import BaseEstimator, TransformerMixin import geomstats.backend as gs from geomstats.geometry.matrices import Matrices from geomstats.geometry.skew_symmetric_matrices import SkewSymmetricMatrices from geomstats.geometry.symme...
ba159f58931f06ee1bf4e70ca3f00e5e92e9a536453a9c89e2d723924b5136e9
Python
5,544
124
import os.path as osp import numpy as np from tqdm import tqdm import torch from sklearn.utils import shuffle from torch_geometric.data import InMemoryDataset, download_url from torch_geometric.data import Data, DataLoader class MD17(InMemoryDataset): r""" A `Pytorch Geometric <https://pytorch-geometric....
bc4fad5a0af81befa87d076a240cea2458e30c294730eccba5d2eb0aba63aa4b
Python
5,544
159
import vimba from video_stream import ImageSource import time import numpy as np FRAME_QUEUE_SIZE = 10 class AlliedVisionImageSource(ImageSource): default_params = { **ImageSource.default_params, "exposure": 8000, "trigger": True, "frame_rate": None, "cam_id": None, ...
ada4d4f6ce98a5a0cf63610d1ea0ef1723b0f908af21a936b2eb6c2b4bb7da68
Python
5,547
138
#!/usr/bin/env python3 """Enforce the v0.6.0 keyword-only ``*`` marker convention (CLAUDE.md). The convention: a keyword-only ``*`` marker is required after the primary data argument in ``__init__`` and in any public method/function with 3+ kwargs. This is a *structural-absence* check (the ``*`` is missing) which semg...
5d7c91422e3aa22d0bbd120a78e97b614e2ecda1a7a7e562f3f7b46daea5aae1
Python
5,550
160
from typing import Sequence, Union import torch import torch.nn as nn from monai.networks.blocks.convolutions import Convolution, ResidualUnit from monai.networks.layers.factories import Act, Norm from monai.networks.layers.simplelayers import SkipConnection from monai.utils import alias, export class UNet_single(nn...
b5d6e58175c203aa1a50ff9d115b894f1f7de268ad52d8bd27dcaacef0afc04b
Python
5,551
137
import pickle import numpy as np from aux_fun import remove_SPH ,construct_target_A, performance from regularization import get_firing_power, alarm_generation, alarm_processing from evaluation import alarm_evaluation, sensitivity, FPR_h, statistical_validation import os def main_testA(patient, approach, data_li...
2e44bd2c95005ec5d52a9ce44203099c7e8e8496a9d61ce48482126eff01689e
Python
5,555
119
import sys import os import re import numpy as np import subprocess import math import scipy import silhouetteRank.spatial_genes as spatial_genes from shutil import copyfile from operator import itemgetter from scipy.spatial.distance import squareform, pdist from scipy.stats import percentileofscore from sklearn.metric...
e67aeac4d125f8759c352a673d658c4464f20418c4598f401558ffcf30654e91
Python
5,556
178
from __future__ import annotations from collections import Counter from typing import Any, Dict, Iterable, List, Optional, TypedDict from chromadb.api.types import Documents, SparseEmbeddingFunction, SparseVectors from chromadb.base_types import SparseVector from chromadb.utils.embedding_functions.schemas import vali...
3a950d926b909c7404639e8b0b237434c2deb33eb527199b028e9fe3017430df
Python
5,557
174
"""Create a model adapter from a Torch pickle file""" __all__ = ["create_adapter"] import os import time import uuid import pathlib import pprint import logging import torch from reinvent import models from reinvent.utils import prior_registry from reinvent.models import meta_data logger = logging.getLogger(__name...
243793ed5e86beab02170eafe29d7e5fc83d42b279a060c635261209a5d06ff9
Python
5,558
150
# 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...
78e5ad257a8832bd0161ca572320681f688d96e2b7a30a485e091badcadb02d3
Python
5,558
181
# ============================================================================== # Copyright 2023 Technical University of Denmark # Author: Nikolas Borrel-Jensen # # All Rights Reserved. # # Licensed under the MIT License. # ============================================================================== import jax.numpy...
87b03f2401184e738271a03956ec42c70307c421929cab46b648cc1662ef2073
Python
5,560
168
import numpy as np from sklearn.metrics import matthews_corrcoef, confusion_matrix, roc_curve, auc, precision_recall_curve import prettytable as pt import torch def eval_metrics(probs, targets,cal_AUC=True): threshold_list = [] for i in range(1, 50): threshold_list.append(i / 50.0) if cal_AUC: ...
b34eda7b7961886e8852f9edd1438d7f93620ab597aca4957a519515364bdd25
Python
5,560
149
import torch import torch.nn as nn import torch.nn.functional as F import rdkit.Chem as Chem from .nnutils import create_var, index_select_ND ELEM_LIST = ['C', 'N', 'O', 'S', 'F', 'Si', 'P', 'Cl', 'Br', 'Mg', 'Na', 'Ca', 'Fe', 'Al', 'I', 'B', 'K', 'Se', 'Zn', 'H', 'Cu', 'Mn', 'unknown'] ATOM_FDIM = len(...
605104f11437b2ff95a93f1b52288c2f396734566d1726948e25b05dd67a38fa
Python
5,562
135
""" The GOOD-CMNIST dataset following `IRM <https://arxiv.org/abs/1907.02893>`_ paper. """ import os import os.path as osp import gdown import torch from munch import Munch from torch_geometric.data import InMemoryDataset, extract_zip class GOODCMNIST(InMemoryDataset): r""" The GOOD-CMNIST dataset following ...
ea70a47c387b23b3dc4845dcec47713091300e48fe6c2b32063c29fe39c5029a
Python
5,563
185
import os import sys import copy import random import numpy as np import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import matplotlib.pyplot as plt import seaborn as sns import utils as u import analysis_utils as au from ray.tune import Trainable l...