sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
c55d92f2223d7ec5c91b0e306e09c27ee8a8d607ae2d5e16c8425a05dd1dae13
Python
1,233
43
from infomap import infomap name = "ninetriangles" filename = "../../{}.net".format(name) infomapWrapper = infomap.Infomap("-N5 --silent") infomapWrapper.readInputData(filename) infomapWrapper.run() tree = infomapWrapper.tree print("Found %d top modules with codelength: %f" % (tree.numTopModules(), tree.codeleng...
16e954ff9c51cfa4a81ba4b20567faa18f53f9a9adf40064a5c1416cef01953f
Python
1,235
47
"""A decorator to ensure that torch parameters are on the correct device This decorator makes sure that tensor and parameter arguments given to a method are transferred to the right device given the device as it has been set for the instance. """ __all__ = ["consistify"] from functools import wraps import torch de...
fadde27ef58931ad08ac60967ba826bc5f6d5729effaffca42b62a6942f9ba82
Python
1,237
26
import torch from torch_geometric.data import Data, Dataset class MarginalSubgraphDataset(Dataset): """ Collect pair-wise graph data to calculate marginal contribution. """ def __init__(self, data, exclude_mask, include_mask, subgraph_build_func) -> object: self.num_nodes = data.num_nodes self...
ae205d3dfdbe5b9ac195a1f35381dda530ed81bad0e877a431271d3d30620840
Python
1,239
36
from typing import Optional, Tuple, List from chromadb.api import BaseAPI from chromadb.api.types import ( Documents, Embeddings, IDs, Metadatas, ) def create_batches( api: BaseAPI, ids: IDs, embeddings: Optional[Embeddings] = None, metadatas: Optional[Metadatas] = None, documents:...
c9c100e1d994d55ce37a4a08f4854d0d14219a30d541c1f69ac6900a0e5a19ab
Python
1,239
38
from ..abstract_dataset import AbstractDataset import os import numpy as np import matplotlib.pyplot as plt import matplotlib.tri as mtri class NavierStokesDataset(AbstractDataset): parametric = True time_dependent = False description = "back step navier stokes TODO" data_directory = os.path.join(os....
ed2a9f3e5c84cd33c49edf14518808daf43c80477eae852ae9e5ee41e424a2f5
Python
1,239
34
# Generated by Django 4.1.1 on 2022-10-28 10:57 from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('celsus', '0016_remove_rawdata_project_rawdata_file'), ] operations = [ migrati...
37f1db620e941621803c1d71d09b6496bffa9f9ff54992126bbbc743f285fbd5
Python
1,242
32
from sklearn.metrics import auc, precision_recall_curve, roc_auc_score, accuracy_score, mean_absolute_error, mean_squared_error import numpy as np import math def prc_auc(targets, preds): """ Computes the area under the precision-recall curve. :param targets: A list of binary targets. :param preds: A...
d2d022a8027a06d1350cf8c04f0a6057ed7b5f77463e90b13466db12f7c23e9a
Python
1,242
41
import os.path as osp import pickle import argparse import os from tqdm import tqdm import time from termcolor import cprint t1 = time.time() parse = argparse.ArgumentParser() parse.add_argument('--start', default=0, type=int) parse.add_argument('--num_mols', default=1000000, type=int) parse.add_argument('--save_path...
57d32302cd76dd0817dddcc230e2745271ceca2ce72ba6d2432a79cd269fb315
Python
1,243
32
# -*- 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 Bra...
2e018b321ffedf806183ecd18f0f43019becf158777e3fdc3083c173032b0945
Python
1,245
40
from PyQt5.QtWidgets import QDialogButtonBox, QDialog from sleepy.gui.builder import Builder from sleepy import SLEEPY_ROOT_DIR from sleepy.gui.settings._view import VIEW class SettingsView(QDialog): def __init__(self, control, application): """View displaying the settings managed by an instance...
561dd574f62900197cdfe9385f0c6dcc325474408732392a5f25023133ea798a
Python
1,245
46
"""Plot a square on H2 with Poincare half-plane visualization.""" import matplotlib.pyplot as plt import geomstats.backend as gs import geomstats.visualization as visualization from geomstats.geometry.hyperboloid import Hyperboloid def main(): """Plot a square on H2 with Poincare half-plane visualization.""" ...
28ecaa4c5bf206609c87f336cfecc70bfed6efeab9a8508942f5817750026431
Python
1,246
54
import pytest from neurodesign import Design, Optimisation def test_design_smoke(exp): design = Design( order=[0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1], ITI=[2] * 20, experiment=exp, ) design.designmatrix() design.FCalc(weights=[0, 0.5, 0.25, 0.25]) des...
9448ca7cce21b2b3a14c32e793e3a2b029cfd0b9401ae2a13bb846ff80f7f2cc
Python
1,246
38
import os import pytest from chromadb.utils.embedding_functions.openai_embedding_function import ( OpenAIEmbeddingFunction, ) def test_with_embedding_dimensions() -> None: if os.environ.get("OPENAI_API_KEY") is None: pytest.skip("OPENAI_API_KEY not set") ef = OpenAIEmbeddingFunction( api...
5b5d7080cd1e998024beb36529559f1be6bbcf8ec3b3fec2012f45e559b94acd
Python
1,247
40
from typing import Any, Dict import os import yaml def set_log_file_path( log_config_path: str, new_filename: str = "chroma.log" ) -> Dict[str, Any]: """This works with the standard log_config.yml file. It will not work with custom log configs that may use different handlers""" with open(f"{log_confi...
bc544817938a640ed0be6952b718b46468f6cb66abfe1132fe5cd0abef3c0a80
Python
1,247
28
from keras.preprocessing.image import load_img, img_to_array import cv2.cv2 as cv2, numpy as np from keras.applications import DenseNet121 from keras.layers import Dense, GlobalAveragePooling2D from keras import Model IMG_PATH = ['./chest_xray_images/normal/15268.jpg', '0'] IMG_SHAPE = (320, 320, 3) test_img = load_...
747e632710d697edcbf9cbf9fbc86b20ba3b70e421502e25ab78b10b372de996
Python
1,249
37
#!/usr/bin/env python # coding: utf-8 import numpy as np import cortex import os from glob import glob data_dir = os.path.abspath('../../outputs/fmriprep') def get_subjects(): fns = sorted(glob(os.path.join(data_dir, 'sub-*/'))) fns = [fn.split('/')[-2] for fn in fns] return fns subjects = get_subjects(...
ee65b98d156b80468d7df0e363020de7698c7e4f8a0a2e10bc18736766d067f8
Python
1,251
39
import torch def rescale_adj(adj, dim='all'): if dim=='view': out_degree = adj.sum(dim=-1) out_degree_sqrt_inv = out_degree.pow(-1) out_degree_sqrt_inv[out_degree_sqrt_inv == float('inf')] = 0 adj_prime = out_degree_sqrt_inv.unsqueeze(-1) * adj elif dim=='all': ...
547950d36c0011324054991cbc315ef6bd86050bf6358ed1d1dbe92c7bcd3f3e
Python
1,252
54
from numpy import linalg as LA import numpy as np def generate_xyz(ds, batch): num_nodes = ds.shape[0] d_list = [] start = 0 for i in range(1, num_nodes): if batch[i] > batch[i-1] or i == num_nodes: end = i d_list.append(ds[start:end, start:end]) start = end...
071ac382dadc7348cd3fd5f7e78c08be88823012018727c5b7bed965c5786292
Python
1,254
31
from geomstats.test_cases.learning._base import BaseEstimatorTestCase class RiemannianMinimumDistanceToMeanTestCase(BaseEstimatorTestCase): def test_fit(self, X_train, y_train, expected, atol): mean_estimates = self.estimator.fit(X_train, y_train).mean_estimates_ self.assertAllClose(mean_estimates...
9f39f8f47ef2be44ee186a9418185a1a18b30a49562e7035dbaa8345857db56c
Python
1,254
32
import numpy as np import pandas as pd # hand keypoint extraction def finger_tapping_distance(InputDataframe: pd.DataFrame, kpt_method="2D"): if kpt_method == "2D": # 2D distances of (keypoint 4 and keypoint 8) # x: pd.Dataframe (index = timestep), (x_0~x_20) # y: pd.Dataframe (index = tim...
0dc0d96b553cd0168b79dcad721f1662b151f50c1a9ebf07086a53f3803b406e
Python
1,255
36
import numpy as np from numpy.testing import assert_raises from gemmr.model_selection import * def test_max_min_detector(): np.random.seed(0) n = 10000 signal = np.cos(np.arange(n)).reshape(-1, 1) X = np.c_[signal, signal, np.random.normal(size=(n, 2))] Y = np.c_[np.random.normal(size=(n, 1)), s...
764bdc83052334a7e45ce57c996cf14cb31fe9e94d7db569dcecb8a22c3084bf
Python
1,255
47
from scipy.linalg import eigh from numpy import zeros def get_LEiDA(syncConnAux): """Obtain leading eigenvector for synchronicity matrices. Args: syncConnAux (ndarray): Synchronicty matrices for all parcels/voxels in the format [N, N, Tmax]. Returns: leidaArrayAux : Leading eigenvector o...
debcfe0390c628a07190d639e753bb42fa9675a76861f47ee201047bd2bd9331
Python
1,255
40
import glob import sys import time import datetime import numpy as np from deeprank_gnn.GraphGenMP import GraphHDF5 from deeprank_gnn.NeuralNet import NeuralNet from deeprank_gnn.ginet import GINet ### Graph generation section #path to the docking models in pdb format pdb_path = '../tests/data/pdb/1ATN/' #path to...
e294aae03dcd57dcf2244309baebfb10681073d4ded90e33ae0374ee657c668d
Python
1,256
41
"""Interfaces for loading and saving (dumping) templates and circuits from/to file.""" from typing import Optional FILEIOMODES = ["pickle", "yaml"] def save(_obj: object, filename: str, filetype: str, **kwargs): """Save an object to file. Parameters ---------- _obj The object to ...
15adc82a297e385b8c31a8d9949a0b09e478da53fd4c18d3eee79a9cfbf778ba
Python
1,257
35
# 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 # # Unless required by appli...
28e9140d7cab07c3245952b0a215e46092868f91e08e0a7bdb3a8369a3c83216
Python
1,257
38
import pytest import numpy as np from reinvent_plugins.components.Lilly.comp_lilly_descriptors import Parameters from reinvent_plugins.components.Lilly.comp_lilly_descriptors import LillyDescriptors SMILIES = [ "Cc1ccc(-n2[nH]c(C)c(N=Nc3cccc(-c4cccc(C(=O)O)c4)c3O)c2=O)cc1C", "CC(=O)Oc1ccccc1C(=O)O", "Cc1...
364eb8928dd588801298ad779d9ec4a6a7f52b5753fe0167b77d965aca3531ac
Python
1,257
46
def benchmark_single_jr_circuit(n_runs=10): """This is a simple benchmark function that instantiates a basic JR circuit and compiles it. Parameters ---------- n_runs number of runs to execute benchmark for averaging """ import time from pyrates import CircuitTemplate from pyrat...
17e80cc19741b825ead7be82582b9dcd99ba50b17b8d05dba7050c3e4dd6e99b
Python
1,259
40
from scipy.io import savemat import numpy as np import glob import sys def main(path,filename): npzFiles = glob.glob(path + "/*.npy") for i,f in enumerate(npzFiles): d = np.load(f) if(i==0): Qx = d[range(1,d.shape[0],5),:] Qy = d[range(2,d.shape[0],5),:] Qz =...
c3e95f4c281050d7d1cb2660fab587f5d82e13a1b1290aa1f0295727e71d3cfe
Python
1,259
36
import argparse import numpy as np parser = argparse.ArgumentParser(description="Manual") parser.add_argument("-f", type=str , default="./example/expression.txt" , help="A path to 'gene expression matrix' file") parser.add_argument("-k", type=float , default=0.1 , help="balance parameter") parser.add_argument("-...
167cb32fa67155041235c8c9c788f2649fa4355fe1c5b5577092dfe30a642ee2
Python
1,262
45
"""Manifold for sets of landmarks that belong to any given manifold. Lead author: Nicolas Guigui. """ from geomstats.geometry.nfold_manifold import NFoldManifold, NFoldMetric class Landmarks(NFoldManifold): """Class for space of landmarks. The landmark space is a product manifold where all manifolds in the...
1b30b822152ea93879819159385c23b99aa8b399068f9f2975aae4341d8c6a2c
Python
1,262
48
"""Minkowski space. Lead author: Nina Miolane. """ import geomstats.backend as gs from geomstats.algebra_utils import from_vector_to_diagonal_matrix from geomstats.geometry.euclidean import Euclidean, EuclideanMetric class Minkowski(Euclidean): r"""Class for Minkowski space. This is the Euclidean space end...
268615a35a8593708921a92d36a63b2894f51cf57bd0a0cc8f8e0c8ee692045b
Python
1,262
40
from typing import List import numpy as np from chromadb.api import ServerAPI from chromadb.api.models.Collection import Collection from chromadb.test.conftest import multi_region_test @multi_region_test def test_many_collections(client: ServerAPI) -> None: """Test that we can create a large number of collection...
a7f12acad0d4d5f21bcb119f3922f28d637d91120ab933ca495318d606277935
Python
1,262
32
import pytest import unittest from reinvent.models import LibinventTransformerAdapter, SampledSequencesDTO from tests.models.unit_tests.libinvent.transformer.fixtures import mocked_libinvent_model from tests.test_data import ( SCAFFOLD_SINGLE_POINT, SCAFFOLD_DOUBLE_POINT, SCAFFOLD_TRIPLE_POINT, SCAFFOL...
dd02da3b14a75de6eb4425019002ff1d47e410b995cea8c64b4b8f781e769a69
Python
1,263
45
class TermColors: """ Colors class:reset all colors with colors.reset; two subclasses fg for foreground and bg for background; use as colors.subclass.colorname. i.e. colors.fg.red or colors.bg.greenalso, the generic bold, disable, underline, reverse, strike through, and invi...
e134c6d9f4bee3ef1bea5befc695f3cb5d517410b046c18c1111bf190960fb6d
Python
1,263
50
"""Base tools to handle datasets. Note: deeply inspired by sklearn. """ import logging import os from collections import namedtuple import requests DEFAULT_DATA_DIR = os.path.expanduser(os.path.join("~", ".geomstats_data")) FigshareMetadata = namedtuple("FigshareMetadata", ["filename", "article_id"]) def _get_d...
a7020fe8d06cf86690b277713714038ba1d4afbb43fbdc5d38734be4b9162bdc
Python
1,267
29
from reinvent.chemistry.library_design.reaction_filters.defined_selective_filter import ( DefinedSelectiveFilter, ) from reinvent.chemistry.library_design.reaction_filters.reaction_filter_enum import ( ReactionFiltersEnum, ) from reinvent.chemistry.library_design.reaction_filters.base_reaction_filter import ( ...
a06a7bd4cceb649b906ad021279eff61f06a35b5df8c1f1b253450d0679e5204
Python
1,268
52
"""Step functions""" __all__ = ["RightStep", "LeftStep", "Step"] from dataclasses import dataclass import numpy as np from .transform import Transform @dataclass class Parameters: type: str low: float = 0.0 high: float = 0.0 class RightStep(Transform, param_cls=Parameters): def __init__(self, par...
bf11522a7c8dcafcb42f77ecf69f55532821292e60921de5c4afe696adfb9ea5
Python
1,268
33
import pandas as pd import numpy as np import argparse import time import os if __name__ == "__main__": # search for all subjects who have an MRI scan. # root = '/home/hoang/data/ANDI/tadpole_challenge/' d12Df = pd.read_csv(os.path.join(root, 'TADPOLE_D1_D2.csv')) print(d12Df.loc[:,'IMAGEUID_UCS...
38cf8398a88c1f4df83ec3ef8ddb9116c341567bfcac3af540956c73b325fbb1
Python
1,270
40
import torch import torch.nn as nn class Discriminator(nn.Module): def __init__(self, n_h): super(Discriminator, self).__init__() self.f_k = nn.Bilinear(n_h, n_h, 1) for m in self.modules(): self.weights_init(m) @staticmethod def weights_init(m): if isinstance...
2e63631ae53c677ce1aea6a7e8128e833bf45d3c95e80f94688f337b7f7962c9
Python
1,271
25
from reinvent.datapipeline.filters import RDKitFilter from reinvent.datapipeline.validation import FilterSection SMILES = [ "CN1CCC23c4c5ccc(OC(=O)c6ccc7ccc(C(=O)Oc8ccc9c%10c8OC8C(O)C=CC%11C(C9)N(C)CCC%108%11)cc7c6)c4OC2C(O)C=CC3C1C5", "CC1(C)CCC(C)(C)c2cc(N3c4cc5c(cc4B4c6oc7ccc(C89CC%10CC%11CC(C8)C%119%10)cc7...
5b88acacccd68211610b6563d0bc6036edbe60d76130f41a8ea4e129f0e69015
Python
1,272
55
# helper functions from numbers import Number import numpy as np from src.constants import DISTANCE_LABEL, SECTION_LABEL def mut_name(frac): if frac == 1: return "C125Y" elif frac == 0: return "WT" return f"C125Y - {100*frac:.0f}%" def get_key(pv, frac, stim, dur): basename = mut_n...
8cd62c96ad7fc2fdcb0edf8a07b9c003078ea3f09856ca0b7fe9ddbfa5bca282
Python
1,272
38
import random from geomstats.test.data import TestData class InformationManifoldMixinTestData(TestData): N_SAMPLE_POINTS = [1] + random.sample(range(2, 5), 1) def generate_random_data_with_samples(self, marks=()): data = [] for n_points in self.N_RANDOM_POINTS: for n_samples in s...
fb9f38a6bf6e90664f5aa1c8f8bf9b55a9cd4d1ed83ba72a4886eb65e8bab2f8
Python
1,273
46
import torch import torch.nn as nn __author__ = "Zhijian Yang" __copyright__ = "Copyright 2019-2020 The CBICA & SBIA Lab" __credits__ = ["Zhijian Yang"] __license__ = "See LICENSE file" __version__ = "0.1.0" __maintainer__ = "Zhijian Yang" __email__ = "zhijianyang@outlook.com" __status__ = "Development" class TwoInpu...
b1d0d2081c5daa0275d22af5c5eb1614c4a85ee99d6f6bdf7f846b34f7b27cb2
Python
1,276
46
import cv2 import os import fastdeploy as fd def parse_arguments(): import argparse parser = argparse.ArgumentParser() parser.add_argument( "--model_dir", required=True, help="Path of PaddleDetection model.") parser.add_argument( "--image_file", type=str, required=True, help="Path of ...
92d39f0a7be8cd3ed0510965098f3659e1771b48c9f88e7b79e364b2abb4992d
Python
1,278
43
""" Test the TMalign wrapper """ import os import unittest from foldingdiff import tmalign class TestTMalign(unittest.TestCase): """ Test the TMalign wrapper """ def setUp(self) -> None: self.fname1 = os.path.join( os.path.dirname(os.path.dirname(__file__)), "data", "7PFL.pdb" ...
f1fa55503a8c83bf93a7c679cc583b04bd9321b201162c5dff627970e4ca144c
Python
1,278
45
import fastdeploy as fd import cv2 import os def parse_arguments(): import argparse parser = argparse.ArgumentParser() parser.add_argument( "--model_dir", required=True, help="Path of PaddleDetection model.") parser.add_argument( "--image_file", type=str, required=True, help="Path of t...
f701e117d51e3ad380b6724a03aafe52a61de317e5fe2339011e4ccf7efe8949
Python
1,282
28
import os name_script_old = "network_permutation_equivariant_shallow_new_lba.py" name_script_new = "network_perm_equivariant_modular_conv_new_lba.py" string = "#!/usr/bin/env bash \n\n#SBATCH --partition=batch_default\n#SBATCH --cpus-per-task=2\n#SBATCH --gres=gpu:1\n#SBATCH --time=48:00:00\n\nsource ~/.bashrc\nmod...
6ccd5e4042322bb270806b5a8bf0ed6c8c899f7a012d69b80a23c25f52952156
Python
1,284
40
import torch from typing import Optional, Union import cv2 import numpy as np def canny_processor(frame: np.ndarray, threshold_low: float, threshold_high: float) -> np.ndarray: return cv2.Canny(frame, threshold_low, threshold_high) def sobel_processor(frame: np.ndarray) -> np.ndarray: k...
1b0bc2ec04882d24f8490ee1b3f044742a95509390c88fca433af546f8ac1bb0
Python
1,287
46
from sleepy.processing.processor import Algorithm from sleepy.processing.parameter import Parameter class Massimi(Algorithm): def __init__(self): self.name = "Massimini (2004)" self.negativeHeight = Parameter( title = "Required height of negative peak (-μV)", ...
a3be5febba959af860f526b81a76214887867563ec7a3c303644b98e92b08bd5
Python
1,287
39
"""Adapter for LinkInvent""" from __future__ import annotations __all__ = ["LinkinventAdapter", "LinkinventTransformerAdapter"] from typing import List, TYPE_CHECKING from .sample_batch import SampleBatch from reinvent.models.linkinvent.dataset.paired_dataset import PairedDataset from reinvent.models.model_factory.m...
d22ca64384553f5d6a97caa6ffcbf035689ec2c325e5a31bd2cf5b6279407814
Python
1,288
41
import numpy as np import matplotlib.pyplot as plt #average_act = np.mean(np.array(e_ng['n.output'][0]), axis=1) def inhibition_excitation_scatter(inh, exc): inh = np.mean(inh, axis=0) exc = np.mean(exc, axis=0) plt.scatter(exc, inh) plt.xlabel('excitation') plt.ylabel('inhibition') plt.show(...
3d947048d293dc508c182abe80c0d920c709eff2399a10897c99318250882ec2
Python
1,289
41
# Author: Guoqing Bao # School of Computer Science, The University of Sydney # Date: 2019-12-12 # GitHub Project Link: https://github.com/guoqingbao/Pathofusion # Please cite our work if you found it is useful for your research or clinical practice from django.db import models # Create your models here. class imageli...
9902ac3764831c1488a0ca889f78a8e3b7c047ffc8f887242ed3622791449740
Python
1,289
33
import pytest import numpy as np from reinvent_plugins.components.NIBRSubstructureFilters.comp_nibr_substructure_filter import Parameters from reinvent_plugins.components.NIBRSubstructureFilters.comp_nibr_substructure_filter import NIBRSubstructureFilters SMILIES = [ "CC1=C(C=C(C=C1)N2C(=O)C(=C(N2)C)N=NC3=CC=CC(...
3c09f8d0947e6ced356c8423586ef447de2e7a063573ebd97cc72ce8f7b1e82d
Python
1,291
36
import unittest import torch.utils.data as tud from reinvent.models.transformer.core.dataset.paired_dataset import PairedDataset from reinvent.models.transformer.core.vocabulary import SMILESTokenizer from tests.test_data import ETHANE, HEXANE, PROPANE, BUTANE from tests.models.unit_tests.mol2mol.fixtures import mock...
7db963de027be7e040cff9f7bacb586eb5ed78c12d811da3756aab0dd66adfb6
Python
1,291
49
import setuptools with open("README.rst", "r") as fh: long_description = fh.read() setuptools.setup( name="corgie", version="0.1.1", author="Sergiy Popovych", author_email="sergiy.popovich@gmail.com", description="Connectomics Registration General Inference Engine", long_description=long_d...
a327eb8440fd0070f9e167444fcc901a906b2955189e665a7b2461b58599a268
Python
1,291
44
""" White Noise @author: Mathieu Scheltienne """ import numpy as np from ._sound import _Sound class WhiteNoise(_Sound): """ White noise stimuli. Parameters ---------- volume : list | int | float, optional If an int or a float is provided, the sound will use only one channel (m...
d24cb6ae3a43de7f91ae6f91b384d594e45da05a98dbd919772422228444d955
Python
1,292
41
# Copyright 2020-2024 Intel Corporation # SPDX-License-Identifier: Apache-2.0 """openfl common object types.""" from abc import ABCMeta from collections import namedtuple TensorKey = namedtuple("TensorKey", ["tensor_name", "origin", "round_number", "report", "tags"]) TaskResultKey = namedtuple("TaskResultKey", ["ta...
68aed40e0fa88e216539f6ffa52eb6bcbad22528c665e93e6b951f4bfce20038
Python
1,293
49
from PymoNNto import * #https://brian2.readthedocs.io/en/stable/examples/frompapers.Hindmarsh_Rose_1984.html def exp(x): return np.e**x def exprel(x): return (exp(x) - 1)/x class HR_main(Behavior): def initialize(self, n): self.set_parameters_as_variables(self) self.dt = 0.01# * ms ...
43a1d0af26a89abe42d25ac0fcd564b4a39fac665dcb5dd8c4a7a9ff7d642b70
Python
1,294
40
from PymoNNto.NetworkCore.Behavior import * from PymoNNto.NetworkBehavior.EulerEquationModules.Helper import * from sympy import symbols class Equation(Behavior): def initialize(self, neurons): n=neurons self.add_tag('EquationModule') self.step_size = self.parameter('step_size', '1*ms', n...
8ea04879b93fff79600edddc4d19253fb36a7689c03b88157eaeb3d30a69780c
Python
1,295
40
import torch.nn as nn # Create the model class ConvNet(nn.Module): def __init__(self): super(ConvNet, self).__init__() #CNN Block 1 self.layer1 = nn.Sequential( nn.Conv1d(246, 256, kernel_size=7, stride=1), nn.ReLU()) self.layer2 = nn.Sequential( ...
e458b304c0b829cf8c05c2a818461559b2f457b6ca2404fe744e54eb4b63f389
Python
1,295
50
# -*- coding: utf-8 -*- import os import argparse import logging import numpy as np # use this format to tell the parsers # where to insert certain parts of the script # ${imports} def parse_args(): # Argument Parser parser = argparse.ArgumentParser() # my args parser.add_argument("--verbose", actio...
1e01bfd7e33a694dca80eeab73fce0c060a27ff9c381c67c4285acbafd4c5b5d
Python
1,299
42
class NoamOpt: "Optim wrapper that implements rate." def __init__(self, model_size, factor, warmup, optimizer): self.optimizer = optimizer self._step = 0 self.warmup = warmup self.factor = factor self.model_size = model_size self._rate = 0 def step(self): ...
21d96c041f4862d4d3e1f3c80003f81dba0ff58247b8352217b2d109659db295
Python
1,301
46
"""The Reinvent sampling module""" __all__ = ["ReinventSampler"] import logging from rdkit import Chem from .sampler import Sampler, validate_smiles from .params import SAMPLE_BATCH_SIZE from ...models.model_factory.sample_batch import SampleBatch logger = logging.getLogger(__name__) class ReinventSampler(Sampler...
c3943d7268cd4a38dd94064539107ca0047917816eab777f10a6fd4d3b30bd6b
Python
1,301
44
"""Compute all the 1613 2D Mordred and extract the desired one NOTE: individual functions are available for these descriptors NOTE2: Mordred needs to be updated to replace np.float with the modern equivalent """ __all__ = ["MordredDescriptors"] from dataclasses import dataclass from typing import List import logging ...
a3b3912afd53deec12d7a1656bd238a77657b20fc3a51e03247ec5c852b49ce0
Python
1,302
38
import pytest import geomstats.backend as gs from geomstats.test.vectorization import generate_vectorization_data from geomstats.test_cases.geometry.base import VectorSpaceOpenSetTestCase from geomstats.test_cases.geometry.lie_group import MatrixLieGroupTestCase class GeneralLinearTestCase(MatrixLieGroupTestCase, Ve...
d8115b0f667591d5c04b47278d84ee4e0a93c96da83103d2dd3be0fa23a3c57b
Python
1,302
39
import sys from typing import Optional def ehfr_net_config_forward( dataset_name: str = 'food101', width_multiplier: float = 0.5, is_eval: Optional[bool] = False, is_test: Optional[bool] = False, task_name: str = None, ): num_classes = int(dataset_name[-3:]) sys.argv....
bd02ebe89e9623239c0922e006a00b44289f1f41ed3f85ec6f3a1f784766f6a3
Python
1,303
32
"""A missing QC report must not be presented as a clean submission.""" from pathlib import Path import pytest import yaml WORKFLOW = Path(__file__).parents[2] / '.github/workflows/chunk-check.yml' @pytest.mark.parametrize('report,selected', [(None, False), (None, True), ...
64c2e18d80dd7bcd80a9dbaa106120232bb09e83fbac7a498a13fa9ad774c4d8
Python
1,305
43
import random import pytest import geomstats.backend as gs from geomstats.numerics.interpolation import ( LinearInterpolator1D, UniformUnitIntervalLinearInterpolator, ) from geomstats.test.parametrizers import DataBasedParametrizer from geomstats.test_cases.numerics.interpolation import InterpolatorTestCase ...
6ad2301ccebe8233c24572447d2d68687c5c5d3c546d31eb2581070c86104273
Python
1,307
47
import pytest from sklearn.gaussian_process.kernels import RBF, ConstantKernel import geomstats.backend as gs from geomstats.geometry.hypersphere import Hypersphere from geomstats.learning.wrapped_gaussian_process import WrappedGaussianProcess from geomstats.test.parametrizers import DataBasedParametrizer from geomsta...
41b1d800e4695f421ccce1886e842cec038192a0b05e505443239345f4c87d1c
Python
1,308
45
import os import torch from torch.utils.cpp_extension import load compile_ok = False if torch.cuda.is_available(): this_dir = os.path.dirname(os.path.abspath(__file__)) peak_find = load( name="peak_find", sources=[ os.path.join(this_dir, "peak_find.cpp"), os.path.join(th...
ca06336dae8302cb7c9cfa42b3bba1e7df0c39f034f0eea102c51881c26c2d4f
Python
1,308
44
import sys, os, random import stdpopsim from contextlib import redirect_stdout Q=1000 speciesName = "DroMel" sampleSize=64 sampleSizes = [sampleSize*2,sampleSize*2] defaultModel = "const2pop" targetPops = [0,1] contigName = "chr3L" geneticMapName = "ComeronCrossoverV2_dm6" dfeName = "Gamma_H17" annotName = "FlyBase_BD...
f12ba857b20caa0a06de6e19987297ce94a5398795a2a1460d86201bf0ba1b2e
Python
1,308
45
import os import hashlib import wget sleepedf_url = "https://www.physionet.org/files/sleep-edfx/1.0.0" output_dir = os.path.join("./data", "sleepedf") record_file = os.path.join(output_dir, "sleepedf_records.txt") if not os.path.isdir(output_dir): os.makedirs(output_dir) if os.path.exists(record_file): os.re...
389a31939f8e125eaa0883e82ec0cf0152f511349dce9e928e18c70fdab45da5
Python
1,309
47
# This file is a part of the `nequip` package. Please see LICENSE and README at the root for information on using it. from .metrics import ( MeanAbsoluteError, MeanSquaredError, RootMeanSquaredError, MaximumAbsoluteError, HuberLoss, StratifiedHuberForceLoss, ) from .metrics_manager import ( ...
3adcfcb5e750b2c9346f65868f11d192dc10f4d20626b730d7812b83fe6bdba2
Python
1,309
42
import os import tempfile import unittest import numpy as np from biotite.structure.io.pdb import PDBFile from foldingdiff import angles_and_coords as ac def get_structure_coords(fname: str) -> np.ndarray: """ """ with open(fname, "rt") as f: structure = PDBFile.read(f) if structure.get_model_co...
ab799ff4184cee8d35eeb7c18bbfda379a2909676e0d8720c348d139f80a0b3e
Python
1,309
45
from collections import OrderedDict import torch import torch.nn as nn from model_angelo.models.common_modules import FcResBlock class TransitionLayer(nn.Module): def __init__(self, hidden_features: int, checkpoint: bool = True) -> None: super().__init__() self.hfz = hidden_features se...
31f3b618ff9491b274b16f20571a1da3d7891b974bbe5459ef33627c498ef4b1
Python
1,313
36
import sys winSize=int(sys.argv[1]) missingDataThreshold=0.25 line = sys.stdin.readline() first = True colsToDiv, colsToDivTwice = [], [] while line: line = line.strip().split() if first: for i in range(len(line)): if line[i] in "pi1,private1,ss1,thetaH1,H1,pi2,private2,ss2,thetaH2,H2,dxy_...
548583cae6f89a36e23e5e76cc9713281b73fa58f09ebafd2dc58e3e00b7e8f2
Python
1,313
36
import numpy as np import scipy.sparse as sp import torch def scipysp_to_pytorchsp(sp_mx): """ converts scipy sparse matrix to pytorch sparse matrix """ if not sp.isspmatrix_coo(sp_mx): sp_mx = sp_mx.tocoo() coords = np.vstack((sp_mx.row, sp_mx.col)).transpose() values = sp_mx.data shape = ...
8af7f3228a9e755e48074cd862812d5745884226793573653c85d1ff68b887f4
Python
1,315
54
import pytest from torch import nn from reinvent.models.transformer.core.network.encode_decode.model import EncoderDecoder from reinvent.models.transformer.core.vocabulary import build_vocabulary from reinvent.models.transformer.linkinvent.linkinvent import LinkinventModel from reinvent.models import meta_data from te...
331e421543e6dbb4a0590e2d21fbec63ffefcb88de10ca494e87c2d6208d3fef
Python
1,316
58
import unittest import pdb import numpy as np from unittest.mock import MagicMock, Mock, patch, PropertyMock from sleepy.gui.settings.core import Settings class SettingsTest(unittest.TestCase): def test_construct_attributes(self): settings = Settings() try: settings.sh...
ba4ddbd680a3c16f01e9324f2dd47b6c5ffdb9e1d0836fd6d214194288168e21
Python
1,318
34
from rdkit import Chem import os.path as osp from tqdm import tqdm import pickle def filter_sanitize_error(): with open('/mnt/dive/shared/kaleb/Datasets/PubChemQC/utils/list_of_valid_mol_dirs.pkl', 'rb') as f: mol_dirs = pickle.load(f) print(len(mol_dirs)) raw_dir = '/mnt/dive/shared/kaleb/Da...
7ec493cbdc47432e8f0926baef66456264638a2f7f47528747115863028cdd68
Python
1,319
32
import torch import torch.nn as nn from model_angelo.models.common_modules import FcResBlock from model_angelo.utils.affine_utils import affine_from_3_points, affine_mul_vecs class BackboneFrameNet(nn.Module): def __init__(self, in_features: int, activation_class=nn.ReLU) -> None: super().__init__() ...
f37abe191736623bcaf121caf7dc54a56867593ff2bfdcdc48358fd417109a8f
Python
1,319
59
from .GUI_main_base import GUIBase from .widgets_utils.canvas import Canvas, CanvasMouseEvent, CanvasPainter from .widgets_utils.custom_list import CustomList from .widgets_utils.id_labels import IdLabels from .widgets_utils.other_utils import ( AddBtn, LightPopUp, QHLine, RemoveBtn, TransparentDisa...
8e2f1821fda08a6f35fec89ffd2562e8b07df03f7e2c17c64c5c1e7298240085
Python
1,320
37
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_...
4442505727c2b5eeca4160157809761c4c5e48c25973eee75e5d20984bd8aa5f
Python
1,322
52
# pylint: disable=redefined-outer-name import tempfile from pathlib import Path from typing import Optional import bids.layout import pytest from pyfakefs.fake_filesystem import FakeFilesystem @pytest.fixture def fakefs( request: pytest.FixtureRequest, ): """fakefs wrapper that can be disabled using the mark...
f4ecd5d1e0fa922a0b77e57e702701df10d9a760f61a16df9bdfaee587a3755e
Python
1,322
41
import jax import jax.numpy as np @jax.custom_jvp def gr_than(x, thr): """ Thresholding function for spiking neurons. """ return (x > thr).astype(np.float32) @gr_than.defjvp def gr_jvp(primals, tangents): """ Surrogate gradient function for thresholding. """ x, thr = primals x_dot,...
f7c5ed2d8abde13e46a1f2bd4baa4c245e4d5d733dae68a49d8d48b3f8f63698
Python
1,323
43
# Generated by Django 4.1.1 on 2022-11-05 12:49 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('celsus', '0021_alter_differentialanalysisdata_gene_names_and_more'), ] operations = [ migrations.AddField( model_name='different...
ec822d31e4b285f91c20e1f6bbc57f551186851d7ab95d946ef6c1bbf40c2f69
Python
1,324
55
"""nltools: a Python toolbox for analyzing neuroimaging data. Focused on multivariate analyses and built on top of nilearn and scikit-learn, nltools provides high-level data classes — `BrainData`, `Adjacency`, and `DesignMatrix` — that wrap common neuroimaging workflows, alongside a functional core of statistics and a...
7d32990839481e11490f0c853f2fde33c2537a1209c9f528625f91470de04f1d
Python
1,325
35
import os import pickle import pandas as pd import numpy as np from tqdm import tqdm from common.adni.utils import INPUT_COLS, TARGET_COLS, NAME2DX, NUMERICAL_COLS, MRI_BIOMARKERS, ECOG_COLS, RAVLT_COLS def get_stats(df): stats = {} df.replace(r'^\s*$', np.nan, regex=True, inplace=True) for col in NUMERICA...
9e2259ccf4970fb62d7033255eea11e28b4606714b48a33d1eb4edb47afdccd0
Python
1,325
45
# # For licensing see accompanying LICENSE file. # Copyright (C) 2022 Apple Inc. All Rights Reserved. # from typing import Any import numpy as np def setup_size(size: Any, error_msg="Need a tuple of length 2"): if isinstance(size, int): return size, size if isinstance(size, (list, tuple)) and len(si...
c2a6d40720786742bfecd416e3a32ea5cb1c47a7f928608b74af8e46773f0d41
Python
1,325
40
# 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 app...
f1f2bef8a2fb3a89433aee0b42d8c96e27f74005c11d7a6f4dad914bdd60d766
Python
1,325
55
"""Create a grid image from molecules for Tensorboard.""" from __future__ import annotations __all__ = ["make_grid_image"] from typing import Tuple, List import logging import torch from torchvision import transforms from rdkit import Chem from rdkit.Chem.Draw import MolsToGridImage logger = logging.getLogger(__nam...
69c374bf66111cbcae3a3ed76fd139588cee19346dd1dbaaa3ea72c04a9bc6e4
Python
1,327
47
"""Shared fixtures for model tests.""" import numpy as np import pytest @pytest.fixture(scope="module") def glm_design(): """Small full-rank single-run design carrying an explicit intercept column.""" from nltools.data import DesignMatrix rng = np.random.RandomState(0) n_samples = 40 return Desi...
e76651dab7ff0fe1ec907db590c4f801b9fe8143649210393afa71e3ca194223
Python
1,327
50
import random import pytest from geomstats.geometry.hermitian_matrices import HermitianMatrices from geomstats.test.parametrizers import DataBasedParametrizer from geomstats.test_cases.geometry.base import ComplexMatrixVectorSpaceTestCase from geomstats.test_cases.geometry.hermitian import HermitianMetricTestCase fr...
21733e94c515a8eb621a8ae23842c36c214a533a6393926570362396b02fda17
Python
1,329
56
from PyQt5 import QtWidgets from sanpy.sanpyLogger import get_logger logger = get_logger(__name__) import sanpy from sanpy.interface.plugins import sanpyPlugin class sanpyLog(sanpyPlugin): """Plugin to display sanpy.log """ myHumanName = "SanPy Log" def __init__(self, **kwargs): """ ...
3285cae99fbcf1f259b250c0c2078bdba35c5f3495ab09a804f5d37be65a1757
Python
1,331
45
# Copyright (C) 2020-2024 Intel Corporation # SPDX-License-Identifier: Apache-2.0 from copy import deepcopy import torch import torchvision train_dataset = torchvision.datasets.MNIST( "./files/", train=True, download=True, transform=torchvision.transforms.Compose( [ torchvision.tr...
227efbe4aa66a04e3574232cd8cb637ddb6f042214b5892a261ceecc43f84c6e
Python
1,332
56
import random import pytest from geomstats.geometry.hermitian import Hermitian from geomstats.test.parametrizers import DataBasedParametrizer from geomstats.test.test_case import np_and_torch_only from geomstats.test_cases.geometry.hermitian import ( HermitianMetricTestCase, HermitianTestCase, ) from .data.h...
69f19b59bd0aac6088da42c44a39f72d1fe48d76af3116c4dae2b8f05603ef07
Python
1,332
45
# Copyright (C) 2020-2024 Intel Corporation # SPDX-License-Identifier: Apache-2.0 from copy import deepcopy import torch import torchvision train_dataset = torchvision.datasets.MNIST( "./files/", train=True, download=True, transform=torchvision.transforms.Compose( [ torchvision.tr...
273f9641c4d58bde23cbb9ecad60be45302572a5dacba6a83406a70a6f046952
Python
1,335
45
import os import numpy as np def read_PSSM_data(fname): """Read the PSSM data.""" f = open(fname,'r') data = f.readlines() f.close() filters = (lambda x: len(x.split())>0, lambda x: x.split()[0].isdigit()) return list(map(lambda x: x.split(),list(filter(lambda x: all(f(x) for f in filters), ...
63b3e1880cead03715cb2d0b135a1eac94eed48bbb18dd79d32438d103f8efc1
Python
1,335
37
# 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...
67a246cbf371f8181d992d6391e02599bbf56168662c0a19cfbd64196f57ab6d
Python
1,336
50
from termcolor import cprint import threading class Alert: alerts = { 'none': '*', 'info': '[INFO]', 'warn': '[WARNING]', 'error': '[ERROR]', 'success': '[INFO]' } colors = { 'none': 'white', 'info': 'yellow', 'warn': 'yellow', 'e...