sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
a8a2f2bfd6f8f92653b6cb2ed480baf37b667a51c3b217e3dc7fecd0a899b670
Python
1,713
52
import numpy as np def hard_sigmoid(x: np.ndarray, k: float) -> np.ndarray: return (k * x > 0).astype(np.float32) def stable_sigmoid(x: np.ndarray, k: float, base_10: bool = True) -> np.ndarray: h = k * x if base_10: h = h * np.log(10) hp_idx = h >= 0 y = np.zeros_like(x) y[hp_idx] =...
275499a692a7b8d8b713722bd466ea614b6e7f08004725ea834fc68937b2ac10
Python
1,714
41
"""`ruff` over the tree, so `uv run pytest -q` predicts CI. CI's `check` job runs `ruff check .` and the test suite did not, so a lint error was discoverable only from a pull request: the `harmonise_vocabulary` import went in unsorted and an `E731` lambda with it, both green locally across 1,149 tests and both red on ...
646572a48103875f827431ea14592ceafb61a3d88faa68eea5c959c037fae152
Python
1,714
73
"""Column declarations. Everything is a projection of :mod:`vdjdb.schema.fields`.""" from .fields import ( AIRR_MAP, ALL_COLUMNS, CHAIN_COLUMNS, CHUNK_COLUMNS, CHUNK_DEDUP_KEY, CLUSTER_MEMBERS_COLUMNS, COMPLEX_COLUMNS, EPITOPE_ASSESSMENT_COLUMNS, EPITOPE_COLUMNS, EVIDENCE_COLUMNS...
aba758d0178efb915d98db42b26d2fa7756b18afc54f06335b45292c4ac8a239
Python
1,714
44
import os import warnings warnings.simplefilter(action='ignore', category=FutureWarning) import pandas as pd from activation_models.generators import counterexample_models from custom_model_tools.eigenspectrum import EigenspectrumImageNet from utils import timed from scripts.fit_encoding_models import fit_encoder, get_...
dbeace8ab04017d4d8e407f125070dda4f455e5a682540ca8a0841ea2228e3ad
Python
1,714
55
"""Input check functions.""" # Authors: Nick Tolley <nicholas_tolley@brown.edu> from .params import _long_name from .externals.mne import _validate_type, _check_option def _check_gids(gids, gid_ranges, valid_cells, arg_name, same_type=True): """Format different gid specifications into list of gids""" _valid...
f8bbb2f9e80855ece7cf999aa4126fa8515de8cfaeb9b0fa8bed714d78944c1b
Python
1,715
54
"""Module containing viz utils""" import numpy as np import matplotlib.pyplot as plt def make_mosaic(data): """Reshape data into a mosaic plot Parameters --------- data : array of shape (dim1, dim2, dim3) input volume Returns ------ mosaic : array mosaic matrix that c...
8a4d6909d7fc485d265bb5a84092b8429d9e9abc89d1cc80adeb9c097aab4563
Python
1,716
48
# 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...
28cbbca23d1b4d06d4e60d2ec84c6c180f6a55d7971d222ed80cea23b510bc46
Python
1,718
48
import os import copy import torch.distributed as dist from urllib import request from common import TMP_CACHE_LOC from utils.ddp_utils import is_start_rank_node try: from utils_internal.blobby_utils import get_local_path_blobby def get_local_path(opts, path, recursive=False, *args, **kwargs): """ ...
b94c2567c623e57a339452601127389beeaa15779a3d5bcf59fbb10f2d2cfdb2
Python
1,718
66
"""Evaluate functions for TB""" from __future__ import annotations __all__ = [ "mutual_similarities", "internal_diversity", "compute_similarity_from_sample", ] from typing import List, Iterable from rdkit import DataStructs import numpy as np def mutual_similarities(fps: Iterable[float]) -> np.ndarray:...
91acd51ec7eb43d9bf92c6727afcf217c6188184818896a0acc53e6e00040023
Python
1,719
54
from __future__ import annotations import os import logging from reinvent.models import ModelAdapter from reinvent.runmodes.RL import memories from reinvent.runmodes.RL.validation import SectionInception from reinvent.utils import get_tokens_from_vocabulary, config_parse logger = logging.getLogger(__name__) def se...
939b0a93c6b408c5a853aee0e931157ef6a232a7aa2f2f7f701a061739b6c7af
Python
1,721
53
import geomstats.backend as gs from geomstats.test.data import TestData from .dirichlet import DirichletDistributionsTestData, DirichletMetricTestData class BetaDistributionsTestData(DirichletDistributionsTestData): def point_to_pdf_against_scipy_test_data(self): return self.generate_random_data_with_sam...
27c63e09ac3b9370a23374494bcc23fbab14809d2115ee8282e6f67d4fcdd9e5
Python
1,724
48
import unittest import pytest import torch import torch.utils.data as tud from reinvent.models import TransformerAdapter, Mol2MolModel from reinvent.models.reinvent.models.vocabulary import SMILESTokenizer from reinvent.models.transformer.core.dataset.paired_dataset import PairedDataset from reinvent.runmodes.utils.h...
ffeb404ca158a5aea7f5ac4772f6aa8f80c85fd250ee9a2281143d3767f121d7
Python
1,724
68
"""Group count Allow groups of atoms defined by SMARTS only a certain number of times in a molecules. """ from __future__ import annotations __all__ = ["GroupCount"] from typing import List from rdkit import Chem import numpy as np from pydantic.dataclasses import dataclass from ..component_results import Compone...
8b2ef8a14d6ec046ec2a0fbbebe70234738e977cad1f7dcae510f427ed0ed2e1
Python
1,725
58
import numpy as np from . import descriptive as descr class AggCluster1D(object): """ Performs a simple agglomerative clustering of angular data. :param numclust: number of clusters desired, default: 2 """ def __init__(self, numclust=2): self.numclust = numclust def train(self, alp...
2e5cc9e95b21bbced9caec96f9c14a64cb15d125b28dc0e42768a974c5a27495
Python
1,727
52
""" Calculate the time from the first to the last trigger in each wave. """ import numpy as np import argparse from pathlib import Path import pandas as pd from utils.io_utils import load_neo, save_plot from utils.parse import none_or_path CLI = argparse.ArgumentParser() CLI.add_argument("--data", nargs='?', type=Pat...
a5c3dccdc0519f7b20e882f2a25191c302678804b27bb9a10c286f54a6b3204a
Python
1,727
71
# -*- coding: utf-8 -*- import os import argparse import logging import h5py import pickle import numpy as np import random # 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 ...
4d6b9821e6ce6d4bf6593f6bc7c6a21d1d9551efffc96ae6041cc29923657850
Python
1,730
61
from pathlib import Path import click import SimpleITK as sitk from tqdm import tqdm @click.command() @click.option( "-i", "--input", "input_path", required=True, type=click.Path(exists=True, file_okay=False, readable=True, path_type=Path), ) @click.option( "-o", "--output", "output_p...
8c43dbb23bf3eac1805478072cc15c9b1e642f78e965c6d41e1a5b6ea6c08ec8
Python
1,730
48
# This file is a part of the `nequip` package. Please see LICENSE and README at the root for information on using it. import torch import packaging.version from .version_utils import get_version_safe _TORCH_VERSION = packaging.version.parse(get_version_safe(torch.__name__)) _TORCH_GE_2_4 = packaging.version.parse( ...
39a873193487f482a92835edc7cbfe78be8e52d2e8c9363668e64483eaa08458
Python
1,731
58
import unittest import numpy as np from deeprank_gnn.tools.pssm_3dcons_to_deeprank import pssm_3dcons_to_deeprank from deeprank_gnn.tools.hdf5_to_csv import hdf5_to_csv from deeprank_gnn.tools.CustomizeGraph import add_target from deeprank_gnn.tools.embedding import manifold_embedding import os CWD = os.path.dirname(o...
644feb68399b1e0e0bfee85fee1f4d79e51a36277cfb7db29413dac6e451a774
Python
1,731
40
import shutil from dig.sslgraph.evaluation import NodeUnsupervised from dig.sslgraph.dataset import get_node_dataset from dig.sslgraph.utils import Encoder from dig.sslgraph.method import GRACE, GraphCL, NodeMVGRL def test_NodeUnsupervised(): root = './dataset' dataset = get_node_dataset('cora', root...
037e4377cdae3973ee92510e0e8bf671a659a53ea547e028022b68ae96e29654
Python
1,732
55
import os import re import openpyxl import csv import codecs import sys import argparse import subprocess from ontoutils.core import * from ontoutils import RobotTemplateWrapper from ontoutils.lucid_chart import * from logging_conf import setup_logging setup_logging() ## PROGRAM EXECUTION --- required arguments: in...
3a056dc706c28a5e3c31b60476268601d38aa25c0e80d47b4b6551f6322ec657
Python
1,732
54
# # For licensing see accompanying LICENSE file. # Copyright (C) 2022 Apple Inc. All Rights Reserved. # import torch from typing import Optional, Union, List from torch.utils.data import DataLoader from ..sampler.base_sampler import BaseSamplerDP, BaseSamplerDDP from ..datasets.dataset_base import BaseImageDataset ...
0b94df8c93b6b0ef25a740baaacc9751e57c0f149cd52d220d28896be0df3d91
Python
1,733
55
class Generator(): r""" The method base class for graph generation. To write a new graph generation method, create a new class inheriting from this class and implement the functions. """ def train_rand_gen(self, loader, *args, **kwargs): r""" Running training for random generation...
31acc350c3a66b7a0ecc64c7d8d7cee63e32b7dd87c0341336dc3e23af74eee9
Python
1,733
54
# Author: Youzhi Luo (yzluo@tamu.edu) # Updated by: Anmol Anand (aanand@tamu.edu) import copy from dig.auggraph.method.GraphAug.constants import * base_generator_conf = { BATCH_SIZE: 32, INITIAL_LR: 1e-4, GENERATOR_STEPS: 1, TEST_INTERVAL: 1, MAX_NUM_EPOCHS: 200, REWARD_GEN_STATE_PATH: None, ...
82c3517837c7ce5778c6296d2f8889b72a60aee8fb89f6e3d47832a50b101234
Python
1,733
57
from numpy import zeros, arange from .get_LEiDA import get_LEiDA from .phDiff import phDiff def dPL(N, Tmax, phases): """Dynamic Phase-Locking. This fuction returns the dynamic Phase-Locking for all parcels/voxels of the input. Args: N (int): Number of parcels/voxels of the input array. ...
bf748b081637d8869374e8719acd8c70ca39cf68a2caadd447cf24d02ae329c8
Python
1,733
56
"""Tests for nltools.plotting.prediction — the drawing internals behind Roc.plot and BrainData.predict(plot=True).""" import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import numpy as np import pytest from nltools.plotting.prediction import ( _plot_class_probability, _plot_decision_mar...
fea51a669a58957814dc387057c8f34fb7e72b14634fc5cf8f8af6ac4c13e41a
Python
1,733
56
import numpy as np import pytest from ase.build import fcc111 from mace.calculators import mace_mp pytestmark = [pytest.mark.network] @pytest.fixture(name="setup_calculator_") def setup_calculator(): calc = mace_mp( model="medium", dispersion=False, default_dtype="float64", device="cpu" ) return...
10398f82ca6b1c0088dcc3c8ab9b5b89bc7a7931f9d5a7a6e43ec843b41b4ed2
Python
1,735
57
import unittest from tests.common import get_svcall class TestGaps(unittest.TestCase): def test_Gaps(self): from sniffles.util import UnresolvedReferenceRegions unresolved = UnresolvedReferenceRegions('chr1', [(0, 10_000), (20_000, 30_000)]) with self.subTest('Outside gap region/normal ...
90b4fbc3df4a3235b1a66ce8264194d6e76267991442b4f4ee63c460d29f7e4b
Python
1,736
60
"""NIBR substructure filter Simple implementation using a cutoff to delineate between "good" and "bad" molecules. Could be implemented as a normal scoring component using a transform. This is a demonstration on how one could build a filter catalog with the help of RDKit. The actual code was taken from RDKit commit 4...
109ffa7a8bf2c3d8a9e52b05663642a5f288a56ad554a8b3f7dcf10ef058e209
Python
1,737
44
import numpy as np import xarray as xr from numpy.testing import assert_raises from gemmr.plot import * from gemmr.plot import hv hv.extension('matplotlib') def test_mean_metric_curve(): rs = np.asarray((.1, .2)) n_per_ftrs=np.asarray((1,2,3)) n_req = xr.DataArray(np.arange(6).reshape(2, 3), dims=('r',...
8d6b0b2af8801f5cffd6cb03ae299fdb224570323b9da80ea0e9dd2f92cdcb77
Python
1,739
50
import pandas as pd from typing import List, Dict def combined_datasets_dataframes( queries: pd.DataFrame, corpus: pd.DataFrame, qrels: pd.DataFrame ) -> pd.DataFrame: qrels = qrels.merge(queries, left_on="query-id", right_on="_id", how="left") qrels.rename(columns={"text": "query-text"}, inplace...
de6de12d313a70e82b8788482b9c8e1c0439af03ff5eb79b522b090af11b2471
Python
1,742
56
from sklearn.metrics import auc, precision_recall_curve, roc_auc_score, mean_absolute_error, mean_squared_error import numpy as np def prc_auc(targets, preds): precision, recall, _ = precision_recall_curve(targets, preds) return auc(recall, precision) def compute_cla_metric(targets, preds, num_tasks): ...
3cff34d0198b60473c5458fdddf1ff712411ee7bf9e2faa5de040767418b4876
Python
1,744
74
import json from scipy.spatial import distance import sys from Bio import SeqIO def calc_tetra(seqs_record): tetramers = {} for a in ['A', 'C', 'G', 'T']: for b in ['A', 'C', 'G', 'T']: for c in ['A', 'C', 'G', 'T']: for d in ['A', 'C', 'G', 'T']: tetramers[a+b+c+d] = 0 for seqs in seqs_record: st...
10e36ac12d220b0bf64742e7adfb4dbe8b43a93cf9992d7167d8a775cfce21cf
Python
1,745
50
import warnings from typing import Tuple import numpy as np import torch from . import MoleculeGraph def collate_graph( batch: Tuple[np.ndarray, list[MoleculeGraph], list[np.ndarray]] ) -> Tuple[torch.Tensor, list[torch.Tensor], list[torch.Tensor], list[torch.Tensor], list[MoleculeGraph], list[np.ndarray]]: ...
f28ceac71279194717a28ff2ab14d1fd3e9a5927903ee61c51b640ddd0d25a60
Python
1,745
55
"""Visualization for Geometric Statistics.""" import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # NOQA import geomstats.backend as gs AX_SCALE = 1.2 class PoincarePolyDisk: """Class used to plot points in the Poincare polydisk.""" def __init__(self, points=None, coords_type="ball", ...
581db139b08e22d6a9c61b7029a8a59ef04b725d42b885cc958692ed77c9115e
Python
1,746
57
"""Compute scores with RDKit's QED""" __all__ = ["CustomAlerts"] from typing import List import numpy as np from rdkit import Chem from pydantic.dataclasses import dataclass import logging from .component_results import ComponentResults from reinvent_plugins.mol_cache import molcache from .add_tag import add_tag lo...
73070df7be55bbbb61191eb0a2022cd51dbf424e837959becf382674a67bbe95
Python
1,746
53
import torch from molx.dataset import Molecule3DProps from molx.model import SchNet2D from molx.mol3d import TransformGT3D from molx.proppred import RegTrainer, eval_reg conf = {} conf['epochs'] = 100 conf['early_stopping'] = 200 conf['lr'] = 0.0001 conf['lr_decay_factor'] = 0.8 conf['lr_decay_step_size'] = 10 conf['...
dc99f0cf4f462f3e29382fc99ccc4bc8bb05a555a05c461230d626da6623ff04
Python
1,749
50
import pytest import numpy as np from reinvent_plugins.components.RDKit.comp_rdkit_descriptors import Parameters, RDKitDescriptors def test_comp_rdkit_descriptors(): input_smiles = ["c1ccccc1", "CCC#CCC"] component_result = { "qed": np.array([0.44262837, 0.39083325]), "MolWt": np.array([78.11...
242cc1c05dca4dc1f6105cc2f6a360bd915828d8bd6837574d9ec52a95bc8dac
Python
1,750
68
# 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 app...
82e18c7b701e6c909df86cb8489554dac250eb48c7703912cc231509f8c688e0
Python
1,751
53
import sys import time import numpy as np from matplotlib.backends.qt_compat import QtCore, QtWidgets, is_pyqt5 if is_pyqt5(): from matplotlib.backends.backend_qt5agg import ( FigureCanvas, NavigationToolbar2QT as NavigationToolbar) else: from matplotlib.backends.backend_qt4agg import ( Figure...
ee65e8d2e317eb6f1a4b526118f0a27623064d2b719fcb39789a68f67a577068
Python
1,752
61
""" Dynamic loading of python modules and classes Author: Tal Eisenberg, 2021 """ import importlib from pathlib import Path import inspect def instantiate_class(class_name, mod, *args, **kwargs): module_name, class_name = class_name.rsplit(".", 1) mod = importlib.import_module(module_name) ClassObject = ...
79a4df23f6e1bee86b02da26d3a2404528bbf1611ca94dc9fc902cfb1131aaa7
Python
1,754
72
""" Holds a reference to the application config module. Author: Tal Eisenberg, 2022 """ import importlib import sys import traceback from types import ModuleType _default_config_name = "config" _config = None def add_defaults(config, defaults): for (k, v) in defaults.items(): if k not in config.__dict...
3379ff4959247843e98a506b5780174d69609c98c44eb20b51299e892122df2e
Python
1,755
57
from setuptools import setup, find_packages # read the contents of your README file from os import path this_directory = path.abspath(path.dirname(__file__)) with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name="deepd3", long_description=long_de...
44197a3946755809c0401dd4721ef082f73ce86c1e4ccd92e16996b37f8f73f0
Python
1,755
43
# # For licensing see accompanying LICENSE file. # Copyright (C) 2022 Apple Inc. All Rights Reserved. # import torch from torch import nn, Tensor from typing import Optional, Tuple, Union class UpSample(nn.Upsample): """ This layer upsamples a given input tensor. Args: size (Optional[Union[int, ...
78d97f10036033cde1526b3909915ca145092a1b4a7b68803a318e68e1d139ae
Python
1,755
58
from sklearn.manifold import TSNE from matplotlib.backends.backend_pdf import PdfPages import pandas as pd import matplotlib.pyplot as plt data_141 = pd.read_csv('Feature_random_forest.csv', sep='\t') data_150 = pd.read_csv('Feature_mutual_info_classif_SelectKBest_150.csv', sep='\t') data_40 = pd.read_csv('Feature_Seq...
441af7e0b1ac655b0c9251862e9130c3ff68c7721425e66f7264bd235a7e2e91
Python
1,756
59
""" Baseline: pre-trained Densenet 161 with adapted head and custom final layer """ import torch import torch.nn as nn class Dense161_model(nn.Module): def __init__(self): super().__init__() back_bone = torch.hub.load("pytorch/vision:v0.10.0", "densenet161", pretrained=True) input_layer ...
decd2f000dea1de1c6e10f5d8574fda5b5f4b1a50e4f24670f66f055720bffd3
Python
1,756
63
from __future__ import absolute_import, division import numpy as np from numpy.testing import assert_allclose from nose.tools import assert_equal, assert_true from pycircstat.regression import CL1stOrderRegression, CCTrigonometricPolynomialRegression def test_circlinregression(): alpha = np.random.rand(200)*np....
02d09c8d8ad21d59805bbb00c6229a0c71f6f4827a17cc9d6bd647478f6e18b7
Python
1,760
69
""" Script to make the inputs for alphafold to run on sherlock Copy fasta files and rename them to a3m files (this skips MSA) """ import os import shutil import logging import argparse from pathlib import Path import numpy as np def build_parser(): """ Build a CLI parser """ parser = argparse.Argume...
ae39d1228b5662c17faa7e49ef85c9fa817310031aa8b01743cc5fa9d1e54fe0
Python
1,760
48
from numpy.random import default_rng from safe_msmt.annotations import make_annotation_text_files from safe_msmt.data_helper import identify_classes_to_use from safe_msmt.feature_partition import make_tfrecords # seed_value = 68103 seed_value = 0 clip_length = 3 # threshold: to find species that appeared in at least ...
90e11d8b21551bd276376d4a6dd2d8b02342ec8e32442918db96f200fa63d5ee
Python
1,763
49
from e3nn.util.test import assert_auto_jitable from nequip.utils.test import assert_AtomicData_equivariant from nequip.nn import SequentialGraphNetwork, GraphModel from nequip.nn.embedding import ( PolynomialCutoff, SphericalHarmonicEdgeAttrs, EdgeLengthNormalizer, BesselEdgeLengthEncoding, ) from nequ...
6a1b1022563a60837217cba73ef89322fa738b3c228a0ae40e05527ac3b2e930
Python
1,767
64
#!/usr/bin/env python """ ModelAngelo: Automated Cryo-EM model building toolkit """ def main(): import argparse import warnings import model_angelo parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawTextHelpFormatter, ) parser.add_argument( "-...
91e7dc6d93929960ed6b256f84ec92cd6188333d6ef983516458fd844f5317a8
Python
1,769
56
import glob import matplotlib from geomstats.test.parametrizers import ExamplesParametrizer from geomstats.test.test_case import TestCase ALL_BACKENDS = ["numpy", "autograd", "pytorch"] AUTODIFF_BACKENDS = ALL_BACKENDS[1:] NP_LIKE_BACKENDS = ALL_BACKENDS[:2] EXAMPLES_DIR = "examples" matplotlib.use("Agg") class...
edeef24b1832703c0bde3880d9726988ae314a446357e218d261ba8579e8121f
Python
1,770
56
import numpy as np from datetime import timedelta as t def get_firing_power(prediction, times, SOP, window_size): firing_power = [] for i in range(len(prediction)): begin_time = times[i] - t(minutes = SOP) end_time = times[i] window_values = prediction[(times>beg...
1d1030fda8b92c8ee0351387a0b5d0e0c86e913791c38fb26b50db3cf62b1ef2
Python
1,772
58
"""Config Validation""" from typing import Optional from pydantic import Field from reinvent.validation import GlobalConfig class SectionParameters(GlobalConfig): num_epochs: int = Field(ge=1) batch_size: int = Field(ge=1) input_model_file: str output_model_file: str # FIXME: consider for removal ...
7f8c3c3d4d404dbbfe00a37a9a511b747a60690c2d17c094029da4b51b94e6c4
Python
1,773
50
from chromadb.api.client import Client from chromadb.config import System from chromadb.test.property import invariants def test_log_purge(sqlite_persistent: System) -> None: client = Client.from_system(sqlite_persistent) first_collection = client.create_collection( "first_collection", metadata={"hns...
fee8fd75ecaaaeb871d9445a00e00fe2853e1a5040bb1a926f93aa9e0e08db49
Python
1,775
47
from setuptools import setup def readme(): with open('README.md') as f: return f.read() setup(name='neuroHarmonize', version='2.5.2', description='Harmonization tools for multi-center neuroimaging studies.', long_description=readme(), long_description_content_type='text/markdown', ...
b1ca9befa59145f48dfa87e47a6de42291b2a962b34bed334fe352452dbff5aa
Python
1,778
40
# Figure 5 of https://www.biorxiv.org/content/10.1101/2021.03.21.436284v1.full.pdf # Original code found in https://github.com/bsorsch/geometry_fewshot_learning/blob/master/ResNet_macaque_stimuli.ipynb # # Parameters: # - Dataset: majaj_2015 (brainscore IT object dataset) # - Number of objects: 64 # - Numbe...
b6fd69412b865fc14c1fd338a1a3178b327936846edf10090d5d250d422841cd
Python
1,778
57
import numpy as np def simple_bootstrap(data, iterations): """ Generator to perform iterations bootstrap iterations along the first axis. :param data: data :param iterations: iterations """ m = data.shape[0] for _ in range(iterations): yield data[np.random.randint(0,m,m)] def inde...
2263a0ae17de60a94d1743fbb6566d80fcce5726a2790d034b6fc513a838a594
Python
1,781
49
import random import pytest import geomstats.backend as gs from geomstats.geometry.poincare_ball import PoincareBall from geomstats.numerics.path import UniformlySampledPathEnergy from geomstats.test.parametrizers import DataBasedParametrizer from geomstats.test.random import RandomDataGenerator from geomstats.test.t...
7f5cc88ff695b77f2acb915e3a47da3e93ed277c9a896480872ba2e948d6f274
Python
1,781
60
"""Perform tangent PCA at the mean on SO(3).""" import logging import matplotlib.pyplot as plt import numpy as np import geomstats.visualization as visualization from geomstats.geometry.special_orthogonal import SpecialOrthogonal from geomstats.learning.frechet_mean import FrechetMean from geomstats.learning.pca imp...
a6ca30e220f9935098a20792505ad467690c1afe3efd754bd8c95223b7781385
Python
1,781
56
"""Mesh-related data structures.""" import geomstats.backend as gs class Surface: """A surface mesh. Mesh info (face centroids, normals and areas) is cached for greater performance. Parameters ---------- vertices : array-like, shape=[n_vertices, 3] Mesh vertices. faces : array-l...
a743eb62e9046dacff2f52d1353fd958f65aade31cbd986eb47c7534a046b54a
Python
1,781
75
from .arg_parser import build_default_arg_parser, build_preprocess_arg_parser from .arg_parser_tools import check_args from .cg import U_matrix_real from .checkpoint import CheckpointHandler, CheckpointIO, CheckpointState from .default_keys import DefaultKeys from .finetuning_utils import load_foundations, load_foundat...
d71bcd8b0c641039d22ff337ebd6161c055e43932d394cde41fee43e3a145090
Python
1,781
47
# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. # # This work is licensed under the Creative Commons Attribution-NonCommercial # 4.0 International License. To view a copy of this license, visit # http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to # Creative Commons, PO Box 1866, Mountain ...
3e49e081c176799747f6f88b0e2e9604db18b571e7f349988033d37f162ece51
Python
1,782
50
import random import pytest from geomstats.geometry.general_linear import GeneralLinear from geomstats.geometry.group_action import SpecialOrthogonalComposeAction from geomstats.geometry.matrices import MatricesMetric from geomstats.geometry.quotient_metric import QuotientMetric from geomstats.geometry.spd_matrices i...
582a2c38f0f1e23a4343427e53f5f8ed681fe622e6f0d078e4738be240729cf3
Python
1,782
50
import pandas as pd import numpy as np import pickle import yaml if __name__ == "__main__": meta_fullname = "/home/hoang/workspace/OAPOP/adni/Metadata/cv_split_10folds_DXTARGET_fdg_12345.pkl" config_fullname = "/home/hoang/workspace/OAPOP/adni/configs/data/img:1_fdg_meta:all.yaml" with open(meta_fullname,...
69968bd084ea82c9f7d8a827e4901be71a77c1a83fe554da6f6c8ff9247bf6b8
Python
1,782
68
# -*- coding: utf-8 -*- import os import argparse import logging import itertools # 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", action =...
aeb92be8a1bde95fc11346acc8be875c55352f4feb8db33bf69ef1f5695b0921
Python
1,783
33
""" This script combines all the necessary files and organizes them as needed by preprocess_features.py """ import pandas as pd ss_prot = './step3/prot_seq_ss.txt' ss_peptide = './step3/peptide_seq_ss.txt' # Format the peptide-protein data like # seq, pep, label, pep_ss, seq_ss prot_df = pd.read_csv(ss_prot, sep='\t'...
e6de096a2c9080481e99d5abfa4cc8d7fb9cb0e534233fa1287f186d21ddd05b
Python
1,783
37
import sys import argparse import os def path(string): if os.path.exists(string): return string else: sys.exit(f'File not found: {string}') def main(): parser = argparse.ArgumentParser() parser.add_argument('input', metavar='input', type=path, help='Path to the input image, should be ....
b027f943b75f09e4be7081d9b920ec0c5058aa5e9cfd0644456024c8ef2e5246
Python
1,784
56
"""isort:skip_file""" import multiprocessing import os import sys from contextlib import suppress from importlib import metadata if "forkserver" in multiprocessing.get_all_start_methods() and sys.platform != "darwin": # In macOS (sys.platform == "darwin"), "forkserver" is broken in Python 3.13.8 # and 3.13.9,...
e6b8077407b3c537ec4ee49c282991c76794ef8443a37c91270878d0a2e0fe11
Python
1,784
47
# 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...
32b45023cca9654f541b850dc69e91d7d33787ae32e21b2da33bfede48d427fd
Python
1,785
40
import json import argparse from rdkit import RDLogger from torch_geometric.loader import DenseDataLoader from dig.ggraph.method import GraphAF from dig.ggraph.evaluation import ConstPropOptEvaluator from dig.ggraph.dataset import ZINC800 RDLogger.DisableLog('rdApp.*') parser = argparse.ArgumentParser() parser.add_...
55408f6aefdfd01955d9c7342bccb27bc79667a86b0014ba23d91db2a50c71ff
Python
1,786
49
from torch_geometric.utils import degree import torch class NormalizedDegree(object): def __init__(self, mean, std): self.mean = mean self.std = std def __call__(self, data): deg = degree(data.edge_index[0], dtype=torch.float) deg = (deg - self.mean) / self.std data.x =...
589e3b5dbc4a7338f7f33c757b4c4f511e251eb7f916ccf96f6e14c32f79c139
Python
1,786
77
from numba import jit import numpy as np import math import cv2 import json def stack_from_polygon_file(path, pol_i=0, imshape=(200, 610)): """Make a binary array from polygon masks :param path: :param pol_i: :param imshape: :return: """ rawpolygons = json.load(open(path, "r")) cb_pol...
a3e86230c25095b6461b098c6ae9d37028842c3fd4426e41d8d4718594612ee3
Python
1,786
88
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Mar 8 22:48:08 2023 @author: rob """ import scipy.io import matplotlib.pyplot as plt import numpy as np import pandas from scipy.optimize import curve_fit mat = scipy.io.loadmat('psfData.mat') def sigmoid(x, a, b, c, d): y = a + (b - a) / (1 ...
b554e2dcbc70997a8c9860fec1bc194ae9fabde39875541fe38c1ca1c7c0d918
Python
1,788
55
import argparse from torch.optim import SGD from . import register_optimizer from .base_optim import BaseOptim @register_optimizer("sgd") class SGDOptimizer(BaseOptim, SGD): """ `SGD <http://www.cs.toronto.edu/%7Ehinton/absps/momentum.pdf>`_ optimizer """ def __init__(self, opts, model_params) -> No...
fc9bcfa4e8b4ec147c41f45fd19a58f6c516c968657bbab241a737babf2de13b
Python
1,788
59
from .dipole import ( simulate_dipole, read_dipole, average_dipoles, Dipole, _read_dipole_txt, ) from .params import Params, read_params, convert_to_json from .network import Network, pick_connection from .network_models import ( neymotin_2020_model, jones_2009_model, law_2021_model, ...
2f54bc9cc91d7eacb85c1c29508c8acd4360a9c7672f6b9be37be83fdbc1ab64
Python
1,789
56
import os import numpy as np def readDadiResultsFromDir(dadiResDir, minRuns): res = [] for resFileName in os.listdir(dadiResDir): currRes = {} mode = 0 with open(dadiResDir + "/" + resFileName, 'rt') as f: for line in f: if mode == 0: if ...
99227e10d4effc2b14f706577a9589d2ba6be71a09905a0585a61560fdc35325
Python
1,790
43
import matplotlib.pyplot as plt import cortex import numpy as np from glob import glob # Run this code to download fsaverage surface for pycortex, labeled by Mark Lescroart cortex.utils.download_subject(subject_id='fsaverage', download_again=False) # We are going to compute median tSNR across all runs. # We already p...
d4fdf75422c2bb33c2d2ee39c6d5416b1ce85b20a0261bb70c67b29de96a4198
Python
1,790
61
"""Compute a desired list of RDKit descriptors up to a total of 210""" __all__ = ["RDKitDescriptors"] from typing import List import logging from rdkit import Chem from rdkit.Chem import Descriptors from rdkit.ML.Descriptors.MoleculeDescriptors import MolecularDescriptorCalculator import numpy as np from pydantic.dat...
e3c7b480359ae4c5af0f52c98230580843e0b85b300accabd119daa16a19ec3e
Python
1,790
54
# ============================================================================== # Copyright 2025 Technical University of Denmark # Author: Nikolas Borrel-Jensen # # All Rights Reserved. # # Licensed under the MIT License. # ============================================================================== import jax.nump...
0822182aaa164abf4ae066ba5648e7fe2b3d90e2f6ab089c8adf653055648c93
Python
1,791
44
import pytest import geomstats.backend as gs from geomstats.test_cases.geometry.base import VectorSpaceOpenSetTestCase from geomstats.test_cases.geometry.riemannian_metric import RiemannianMetricTestCase from geomstats.test_cases.information_geometry.base import ( InformationManifoldMixinTestCase, ) class Dirich...
3e647ceff98ed4609e4e4dff035fc006e928272c1489758b9fb94b33c7f7beac
Python
1,796
68
# === Utility functions adapted from torch geometric (https://pytorch-geometric.readthedocs.io/en/latest/) === import ssl import os import os.path as osp import urllib import zipfile import tarfile from pathlib import Path from typing import Optional import logging logger = logging.getLogger(__name__) def download...
545664d73526a2f284a7c26b9ce8a6863e45dfa2856b38b34d15cd736a773c8d
Python
1,797
66
# Copyright 2020-2024 Intel Corporation # SPDX-License-Identifier: Apache-2.0 """Task module.""" from dataclasses import dataclass, field @dataclass class Task: """Task base dataclass. Args: name (str): Name of the task. function_name (str): Name of the function to be executed for the task...
2dfef1e5577dd6acfaa4443860d95fc54c0af2a82e4e67409195f7c5ed678d66
Python
1,798
73
from .tar import Tar, DumpTar from .meta import Meta from .vocab import Vocab from .pq import PQ from .record import Record META = 'meta.json' VOCAB = 'vocab.bin' PQ_ = 'pq.bin' class Navec(Record): __attributes__ = ['meta', 'vocab', 'pq'] def __init__(self, meta, vocab, pq): self.meta = meta ...
9b16386627830ca487b6172ba0c4d445b202a43ffc6c73376c496d264f8ffd7e
Python
1,803
54
"""LibInvent transfer learning Train a given model with new data. The data comes from a file with SMILES strings. The file is assumed to be in multi-column format separated by commas (CSV) or spaces. The SMILES strings are taken from the first two columns. The two SMILES in each row correspond to a single SMILES (...
e1b8de81cc8cfec41625a0a73a08de1a1834f915d1d8778e291f76d3ad657238
Python
1,804
33
import json import argparse from torch.utils.data import DataLoader from dig.ggraph3D.method import G_SphereNet from dig.ggraph3D.evaluation import PropOptEvaluator from dig.ggraph3D.dataset import QM93DGEN, collate_fn parser = argparse.ArgumentParser() parser.add_argument('--prop', type=str, default='gap', choices=['...
ef24ea292804e1a6bc5a07ac17c2ab0af818ad16eb6e68bde692e1e1741e0e37
Python
1,804
57
import numpy as np def find_event_channel(inst=None, ch_names=None): """ Find the event channel using heuristics. Disclaimer: Not 100% guaranteed to find it. If raw is None, ch_names must be given. Parameters ---------- inst : mne.io.Raw | numpy.ndarray (n_channels x n_samples) T...
e0038cfaa6898d5ea9ee323b0b5546a7559ee426bcd7172a90c0ffcec880e568
Python
1,805
58
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 #####################...
0cfe363c863d4f82adfeaf5427bb17f6bca5c3556c9513155d560d1439bbe7d8
Python
1,808
28
import matplotlib.pyplot as plt name_list = ['Asthma', 'Systemic lupus erythematosus', 'Rheumatoid arthritis', 'Crohn', 'Multiple sclerosis', 'Type 1 diabetes', \ 'Psoriasis', 'Ulcerative colitis', 'Ankylosing spondylitis', 'Osteoarthritis', 'Immunoglobulin', \ 'Primary sclerosing cholangitis'...
aebf5b718cafd125d5be977c4fb896dc858736ac4acd778fd782d74976650a5f
Python
1,810
59
import torch def test_conv_block(): from mlspm.modules import Conv2dBlock, Conv3dBlock torch.manual_seed(0) x = torch.rand(10, 8, 12, 12) with torch.no_grad(): a = Conv2dBlock(8, 4, kernel_size=3, depth=1, res_connection=False, activation=torch.nn.ReLU(), last_activation=True)(x) as...
dac055bb694149a2d635151ffc09d182f8176bfe2a296c52161f99bb86e53e18
Python
1,810
64
import pytest from torch.utils.data import SubsetRandomSampler, DataLoader, Subset from nequip.data import AtomicDataDict class TestDataset: def test_subset(self, dataset): Subset(dataset, [1, 3]) class TestDataLoader: def test_whole(self, dataset): dloader = DataLoader( datase...
d305ce2ab689311ffb1d7a40516bc9d71fd9f0a1fb82fdea6bd0eb49f3282863
Python
1,812
61
from PymoNNto import * #https://brian2.readthedocs.io/en/stable/examples/frompapers.Wang_Buszaki_1996.html def exp(x): return np.e**x def exprel(x): return (exp(x) - 1)/x class Wang_Buzaki_main(Behavior): def initialize(self, n): self.set_parameters_as_variables(self) self.dt = 0.01# * ...
464a6595c878612474a919b2974a4bba5401c90ba80032cb644ca0fc26a91609
Python
1,814
56
# # For licensing see accompanying LICENSE file. # Copyright (C) 2022 Apple Inc. All Rights Reserved. # from torch import nn, Tensor from typing import Optional, Tuple class Dropout(nn.Dropout): """ This layer, during training, randomly zeroes some of the elements of the input tensor with probability `p` ...
46d41e787ce1be22555ff7e6c6d0618586614d4df0f37f4e0968de903fc6fad0
Python
1,814
55
import torch.nn as nn from reinvent.models.model_mode_enum import ModelModeEnum from reinvent.models.model_parameter_enum import ModelParametersEnum from reinvent.models.libinvent.models.decorator import Decorator from reinvent.models.libinvent.models.model import DecoratorModel from reinvent.models.libinvent.models.v...
2f655577cb1f3a7e6812380b6a05f5ceab336fea9d2d26ad5604a736e726c68f
Python
1,816
68
import random import pytest from geomstats.geometry.siegel import Siegel, SiegelMetric from geomstats.test.parametrizers import DataBasedParametrizer from geomstats.test_cases.geometry.base import ComplexVectorSpaceOpenSetTestCase from geomstats.test_cases.geometry.siegel import SiegelMetricTestCase from .data.base ...
aefb5a56666e2a20f6fa68d237a42b646c1700810188e6e0e9238467bf11bf96
Python
1,816
92
from rich import print import neurodesign from neurodesign import generate # define experimental setup exp = neurodesign.Experiment( TR=2, n_trials=20, P=[0.3, 0.3, 0.4], C=[[1, -1, 0], [0, 1, -1]], n_stimuli=3, rho=0.3, stim_duration=1, t_pre=0.5, t_post=2, ITImodel="exponent...
00bb916ef53ff09a1213ba0f4c7cc066e76443bd23f71c1b5dfa6ac2e323a837
Python
1,817
47
import os # Define a list of file names file_names = [ "CD16p_Mono_conditional_eQTL_FDR0.05.txt", "CL_Mono_conditional_eQTL_FDR0.05.txt", "CM_CD8_conditional_eQTL_FDR0.05.txt", "DN_B_conditional_eQTL_FDR0.05.txt", "EM_CD8_conditional_eQTL_FDR0.05.txt", "Fr_I_nTreg_conditional_eQTL_FDR0.05.txt",...
2b3f8fe2910ff79b5bb848e58237eb725544b2fa67a0aeb4f82b24d681c498b0
Python
1,817
62
"""Script to generate a Snakebids project.""" import argparse from pathlib import Path from cookiecutter.main import cookiecutter import snakebids from snakebids.app import SnakeBidsApp from snakebids.cli import add_dynamic_args def create_app(args): cookiecutter( str(Path(snakebids.__path__[0]) / "pro...
45d4b1baaf0696bf4c2a62ca6781df3be26c3c9f6ac5d9bac55a0fc4c20a6e5c
Python
1,817
71
from abc import abstractmethod from enum import Enum from typing import Dict, Any, Optional from uuid import UUID from chromadb.api.types import ( Embeddings, Metadatas, Documents, URIs, IDs, CollectionMetadata, Where, WhereDocument, ) from chromadb.config import Component, System cla...
6d306a520f95e76a545a324164c00046050ad46df15af06cbf551b114711acd4
Python
1,817
59
import pysam import argparse from tqdm import tqdm from collections import defaultdict def pipesplit(col): return lambda input: input.split("|")[col] def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("snps", help="SNP BED file") parser.add_argument("reads", help="Mapped reads ...