sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
be42c032b936120be26846f27db95f0b85ec3bf653ecd3c0349a9f84ea3ac081
Python
2,329
46
# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this sof...
8d1338d12dcc34533bff52eca142734c790767925e0cf9cb8389ffd3b1743053
Python
2,330
69
# Copyright 2023 DeepMind Technologies Limited. # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
f77fd95c62e43badf1dd0b3a8c482e83ef8e2ee67bd1d298b24358617257db71
Python
2,334
52
"""Pinned source revisions and locations for locally compiled surface tools.""" import hashlib import json import os from pathlib import Path import platform ROOT = Path(__file__).resolve().parent FS_REVISION = '7eb846079b0dc0c92e8313205a3d2387b5c7a354' FS_URL = 'https://github.com/freesurfer/freesurfer.git' COMMANDS...
b6a378368d45481361dd8f0f5e0afcfd45b487cba4927c267a06382d2718029f
Python
2,335
68
from torch import nn, transpose def elu(): return nn.ELU(inplace=True) def instance_norm(filters, eps=1e-6, **kwargs): return nn.InstanceNorm2d(filters, affine=True, eps=eps, **kwargs) def conv2d(in_chan, out_chan, kernel_size, dilation=1, **kwargs): padding = dilation * (kernel_size - 1) // 2 ret...
a1731e30aee49dc529f9cf845f3a8ec0183fec1e17d9f84eacec94635bdeed1c
Python
2,336
65
import numpy as np import pytest import torch from neurovisfit.data.dataset import DataSplit from neurovisfit.data.dataset import ImageResponseDataset from neurovisfit.data.dataset import InputResponseSelector from neurovisfit.data.dataset import NamedDataSplit @pytest.fixture def mock_input_response_selector(): ...
df5366953b335db103d70553a38b9026d156b4e110ef6a2560267108a06d0738
Python
2,339
67
import os import h5py import numpy as np import scipy as sp import anndata as ad import pandas as pd import scanpy as sc import scvelo as scv import loompy as lp import cellrank as cr os.chdir('/home/jfleck/projects/cutntag/') #### Read h5ad #### rna = sc.read('data/RNA/RNA_all_v3.2cellrank.h5ad') rna_meta = pd.read...
4c8c5fef4b695c4345fcac1b1e041751c06dd759fc6318edde235f7fd1f0724f
Python
2,340
30
"""Writing audit of paper/main.tex prose: per-section sentence-length stats, sentences > 40 words, AI-vocabulary hits, first-person pronouns, em/en dashes, and non-ASCII/invisible characters.""" import re, os, statistics, unicodedata ROOT = os.path.join(os.path.dirname(__file__), "..") s = open(os.path.join(ROOT, "pape...
efbd62aa03ba70276bfd7273a2e9bdcfba23f6b9d13c49c603d6e8103ea49e05
Python
2,341
45
# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this sof...
b54e846dbf02c15aecb2a6f9b3e561bd128f191714e64ebc3d9622d88321fd7b
Python
2,342
61
# Copyright (c) MONAI Consortium # 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 applicable law or agreed to in writing, so...
0405ca7aaea78fa90f8fe437a0929d0351ddb97dcd853df39bfaa37dfee99b58
Python
2,345
69
""" ZephOD network uses all functions listed below as input channels to combine/select from. This file may be edited by a user to fit their particular use case, or to add new State-of-the-Art segmentation/detection algorithms, but each edit will require retraining of the weights. Each function needs to take only the vo...
533eb6efb1fc0de5932879544d881738600b56b99f4939e0205666de5a664671
Python
2,345
42
# Sconda conda activate abc; cd /mnt/BioAdHoc/Groups/RaoLab/Edahi/Projects/09.TimeCourse5hmC/ForFerhatGit/FCDNN/results/fcdnn_most_variable_genes; python # NOTE: Run /mnt/BioAdHoc/Groups/RaoLab/Edahi/Projects/09.TimeCourse5hmC/ForFerhatGit/FCDNN/results/fcdnn_most_variable_genes/fcdnn_most_variable_genes.sh before this...
5ba46c2402afa6a43b52bd50519e1567df12e65802f8fad8ae6c2ad875f672d5
Python
2,345
42
# Sconda conda activate abc; cd /mnt/BioAdHoc/Groups/RaoLab/Edahi/Projects/09.TimeCourse5hmC/ForFerhatGit/FCDNN/results/fcdnn_variable_genes; python # NOTE: Run /mnt/BioAdHoc/Groups/RaoLab/Edahi/Projects/09.TimeCourse5hmC/ForFerhatGit/FCDNN/results/fcdnn_variable_genes/fcdnn_variable_genes.sh before this code import pa...
73422f3bd24fafad0cbf545766a49ed922165b278f67ab782857b174e026455f
Python
2,345
75
from langchain_core.prompts.chat import ( ChatPromptTemplate, ) from langchain_core.prompts.prompt import PromptTemplate from langchain_classic.chains.prompt_selector import ( ConditionalPromptSelector, is_chat_model, ) DEFAULT_REFINE_PROMPT_TMPL = ( "The original question is as follows: {question}\n"...
0d56b71c64f4c35e4961f6d9b074fbfe0f167fec381692413c46307f26edd93d
Python
2,347
104
"""Module with generic useful functions such as to return main dir path, and writing hdf5 files.""" import os import deepdish as dd from pathlib import Path def get_file_path(filename): """Find filename in the relative directory `../data/` . Args: filename (str): file we're looking for in the ./dat...
e43cd03cf7b9044726d68d437de64b2e0fdfac1f9c1056f191e0ccedfcbe47e2
Python
2,347
70
#! /usr/local/bin/python #'################################################################################# #'################################################################################# #' Train TCGA network #'################################################################################# #'#################...
b0568d7567f3117b055a2e6ec6bddbe33c838dd18a56a59f67dd8cb2dcf0490e
Python
2,348
49
from NeuronModel.Integrate_and_Fire import integrate_and_fire import numpy as np import matplotlib.pyplot as plt hsv = plt.get_cmap('hsv') def colors(n): return hsv(np.linspace(0., 1.0, len(n)+1)) def R_func(x, params): return params['RI_slow'] + (params['RI_fast'] - params['RI_slow']) / \ (1. + n...
0cf4c1d194c9210154fc95fba2ef58193339421640945f5d22167acaff6203e7
Python
2,349
60
import argparse from pathlib import Path from tempfile import TemporaryDirectory from alpaca import ProvenanceGraph, AlpacaProvDocument def add_suffix_to_gexf_file(source, suffix): return source.parent / (source.stem + f"_{suffix}.gexf") def merge_graphs(merged_file, *source_files): doc = AlpacaProvDocumen...
30cdf9f0b45b20a106cff73bd4e5653c7c09cb6dd95265c969bb43750907393d
Python
2,350
70
import os import numpy as np from audio_utils import WaveProcessor from tqdm import tqdm import mne def create(wav_folder: str, tg_folder: str, out_folder: str, segments_list: list, config: dict) -> None: """ Create feature from audio snips. This function creates a feature from audio snips. The feature is a...
c752ed2bfe7b4472c591ea04a4a5f76d4c37d3de8db2ebe905642ad0a0994a8b
Python
2,351
71
# -- coding: utf-8 -- # @Time : 2022/10/15 16:11 # @Author : Biao Zhang # @Email : littlebiao@outlook.com # @File : heco_config.py from yacs.config import CfgNode as CN # -------------------------------------------------------------- # Config of model # -------------------------------------------------------------- _...
e33ed129dc8f4d41e2e3a8a5f6e38b0486900286b33d0a30de9111a0f8e4601a
Python
2,351
96
"""Example03.""" # pylint: skip-file import numpy as np import torch import compare_models import pandas as pd import argparse parser = argparse.ArgumentParser() parser.add_argument('--dtype', help='dtype', default='float64') args = parser.parse_args() keys = ['EMB1 (PyTorch)', 'EMB2 (PyTorch)', 'EMB3 (PyTorch)', 'E...
392ddcf14301b09c8df07852566781f03b1f03279f79a822cf0c67c05740198a
Python
2,353
48
#!/usr/bin/env python import os import tempfile from ..constants.constants import HUMAN_SOMATIC_CHROMOSOMES, PLINK_1000G_URL from ..utilities.utilities import untar class Plink: SUFFIXES = [ ".fam", ".bim", ".bed" ] @staticmethod def validateDirectory(directory, chromosomes = HUMAN_SOMATIC_CHROMOSOMES,...
2c4f8f3519ca01829a62ee762f2b8f6491f2b48905fb9c0f741268323185dea2
Python
2,354
65
from typing import Literal from langchain_core.documents import Document from langchain_core.indexing.api import _get_document_with_hash def test_hashed_document_hashing() -> None: document = Document( uid="123", page_content="Lorem ipsum dolor sit amet", metadata={"key": "value"} ) hashed_docume...
48547ad88224c0f1d85cd4049494253c66c38fa989c0faab0619a79e770c2f0e
Python
2,354
71
from collections import OrderedDict import copy import torch import torch.nn as nn from h3xsemble.utils.tensor_utils import tensor_tree_map class ExponentialMovingAverage: """ Maintains moving averages of parameters with exponential decay At each step, the stored copy `copy` of each parameter `param` is...
e5bb0310c3c886330cd8fe5b13c76a3b1cba35ea02004e6252914c01ed03c6a0
Python
2,355
59
import os from core.network import network_register, MIGA from utils.my_containers import deep_dict_get from ..head import get_head from ...loss import get_loss from utils.tensor_operator import tensor2array from ...loss.utils import merge_loss_dict os.environ["OMP_NUM_THREADS"] = "1" os.environ["MKL_NUM_THREADS"] = ...
1b518f025b5eb3cda04e51e6f7a60d0feb0a3158571b236b6dd475f71e69de7f
Python
2,357
71
from io import StringIO from cwas.core.categorization import parser from pandas import Series def test_parse_info_field(): csq_field_names = ["Test1", "Test2", "Test3"] info_field = ( f'##INFO=<ID=CSQ,Number=.,Type=String,Description="' f"Consequence annotations from Ensembl VEP. Format: " ...
b7c97ec6a9881d1bbbe8a3b6a4d3ad18086907214d6d77c0d964923de3a2b012
Python
2,357
76
# Adapted from OpenFold # Copyright 2021 AlQuraishi Laboratory # # 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 appl...
bb64f5edf7f9e41eb8fa7eeba76bcb3cebc7fa5d9538f5524b46a123bdaf66ca
Python
2,357
50
from stable_baselines3 import PPO from stable_baselines3.common.evaluation import evaluate_policy from stable_baselines3.common.callbacks import EvalCallback from animalai.envs.arena_config import ArenaConfig from src import utils from src.animalai import AAI_utils from src.models.actor_critic import NetActorCriticPol...
053d8df763e1d2669be9187a407435ebf18d01c39882867089da8a1df534a071
Python
2,358
65
import sys import torch.nn.functional as F import numpy as np import joblib from dt_utils import Timer from plastic import PlasticRecall from data_utils import generate_delayed_recall_data, recall_chance from neural_net_utils import random_weight_init, plot_train_perf #%% if len(sys.argv)>=4: R = int(...
14eaf4487cfb6438dabcd44e4b408ec89277bdc4c575fdf77ddfee4fcb816e65
Python
2,358
69
import torch import torch_geometric import hienet._keys as KEY import hienet.util # TODO: Now, I'm not sure why this class is required class AtomGraphData(torch_geometric.data.Data): """ Args: x (Tensor, optional): atomic numbers with shape :obj:`[num_nodes, atomic_numbers]`. (default: :o...
1a4dccb0413fe16a63fe0dcc0fdbaef17cd73b9b6d9b5cb48852a407c3bd3071
Python
2,358
96
try: import cPickle as pickle except: import pickle import ast import re import inspect import os import logging import numpy as np def cross_entropy_npy(a, b): return a * np.log(b + 1E-9) + (1 - a) * np.log(1 - b + 1E-9) def safe_eval(expr): if type(expr) is str: return ast.literal_eval(expr...
46c8e049feced88da1f9370afc2d53dbafe4e84a96586dffa18d692a00977226
Python
2,358
61
import torch from torch import nn from torch.optim import Adam, lr_scheduler from torch.utils.data import DataLoader from torch.utils.data.sampler import WeightedRandomSampler from processing.utils import make_weights_for_balanced_classes from processing.train_utils import supervised_training from typing import Tuple...
6b102ef792f727a23cd8fdce45d7367612e0abb9e6e9e439bbe51bc4075bc7fa
Python
2,358
59
"""Prompts for comparing the outputs of two models for a given question. This prompt is used to compare two responses and evaluate which one best follows the instructions and answers the question. The prompt is based on the paper from Zheng, et. al. https://arxiv.org/abs/2306.05685 """ # noqa: E501 from langchain_co...
bfa7ece0a00294f616a6c9497a4bd8da65ab0026bd19331ae3c91e6050da7ee4
Python
2,358
90
# -*- coding: utf-8 -*- import torch import numpy as np from PIL import Image from torchvision import models, transforms class ResNetDataset(torch.utils.data.Dataset): def __init__(self, dataset): super(ResNetDataset, self).__init__() self.dataset = dataset self.transform = transfor...
d50141f5d7e44632a586646d0b8c9a1638de0c3e9403f3543d7580b872479232
Python
2,358
67
import os import sys import adv import argparse import skimage.io import numpy as np def nrrd_details(f): nrrd = adv.nrrd_read(f) dtype = nrrd["type"] path = nrrd["path"] shape = nrrd["sizes"] offset = nrrd.get("byte skip", 0) dx, dy, dz = nrrd.get("spacings") ...
7eefc4d9ed19921c84fa27e80049bc1f7dff3bf0118ded33223a54fca5372de7
Python
2,359
64
import numpy as np import torch from medpy import metric from scipy.ndimage import zoom def calculate_metric_percase(pred, gt): pred[pred > 0] = 1 gt[gt > 0] = 1 if pred.sum() > 0: dice = metric.binary.dc(pred, gt) hd95 = metric.binary.hd95(pred, gt) return dice, hd95 else: ...
be5a8fc7598a4b429746c9a872978477d9d45e932d4163f23473ad85a03b8e6d
Python
2,361
65
import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt import pandas as pd import seaborn as sns from scipy.stats import mannwhitneyu from mantis_ml.config_class import Config best_real_clf = {'CKD': 'XGBoost', 'Epilepsy': 'XGBoost', 'ALS': 'ExtraTreesClassifier'} best_rand_clf = {'CKD':...
c9541e5f47c15b5c04dbd2c1ef530b7890f9f54a12971c2a2e7510f6168f7f4f
Python
2,363
56
""" Calls CellExplorer connectivity function from Python. The input format fits Yu's curated data format. 2/27/2023 jiaaoZ """ import os import re import shutil import subprocess import numpy as np from utils.mdaio import readmda, writemda64 def get_segment_index(segment_name: str) -> int: return int(re.search(...
7a83f0c8f73c50a72cd9663be6c6367e18b3971409fd9dddceff6961b23be739
Python
2,365
77
#!/usr/bin/env python3 import logging import os import numpy as np from enrichm.parser import ParseGenerate from enrichm.writer import Writer from enrichm.parser import Parser class Predict: predictions_output_file = 'predictions.tsv' predictions_header = ["Sample", "Prediction", "Probability"] def make_...
25843ce147cb86cfa0cb30c75686ff18d58d629d86e2d426816e1874bc5cf57e
Python
2,366
69
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # pylint: skip-file import sklearn.linear_model import scipy.io import matplotlib.pyplot as plt import numpy as np from embanded.embanded_numpy import EMBanded # Load data from the 'example02.mat' file data = scipy.io.loadmat('example02.mat') # Split the data into predi...
aedb02bf919aac64700655308b8a6cf26f7a66d075f5d5233b64abd968317d9d
Python
2,367
77
# coding=utf-8 import numpy as np import torch import torch.nn.functional as F from datautil.util import random_pairs_of_minibatches from alg.algs.ERM import ERM class Mixup(ERM): def __init__(self, args): super(Mixup, self).__init__(args) self.args = args def update(self, minibatches, opt, ...
8a06d77103e8d9e8d726b6df537d79db7d7df920f63a948e4a0459014ebc2264
Python
2,368
80
"""A unit test meant to catch accidental introduction of non-optional dependencies.""" from collections.abc import Mapping from pathlib import Path from typing import Any import pytest import toml from packaging.requirements import Requirement HERE = Path(__file__).parent PYPROJECT_TOML = HERE / "../../pyproject.to...
afbbb46f03c7c10e3cfefea15126410472760469e075d4a979604a5d18fc661d
Python
2,368
78
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Mar 10 15:41:54 2021 @author: shni2598 """ import numpy as np #from brian2.only import * #import matplotlib.pyplot as plt from connection import coordination #%% def get_adaptation(base_amp = 16, max_decrease = [13,13], rang = [6, 6], sharpness =[1,1],...
2787b7afffab30b80714b55756a956f33669c2327126a29f3cc6b3b4bd22efba
Python
2,370
86
"""Training diffusion model on rna inverse design with given split.""" import ml_collections import torch def get_config(): config = ml_collections.ConfigDict() # Misc config config.exp_type = 'vpsde' config.device = torch.device('cuda:0') if torch.cuda.is_available() else torch.device('cpu') con...
f2eeeed5e411486c53902a29890ce0d9962436b5be86cd1b5c81799944a15074
Python
2,370
62
""" openforcefields """ import sys from setuptools import setup import versioneer short_description = __doc__.split("\n") # from https://github.com/pytest-dev/pytest-runner#conditional-requirement needs_pytest = {'pytest', 'test', 'ptr'}.intersection(sys.argv) pytest_runner = ['pytest-runner'] if needs_pytest else []...
713412cb8568762a835a760edad5549c3d5ee65252a16a43967b88e31f9fc822
Python
2,371
85
'''test_style - test coding style confirmation of cgat code =========================================================== :Author: Andreas Heger :Release: $Id$ :Date: |today| :Tags: Python Purpose ------- This script runs pep8 on all scripts in the cgat code collection. This script is best run within nosetests:: ...
f9d31cb6e978a5cded3ba3bd3587944946f10518c33decde2f666dcbedd46ea0
Python
2,372
89
#!/usr/bin/env python3 """ Calculate probability-weighted label volumes given a 4D probabilistic atlas - assumes empirical probability is a good proxy for partial volume occupancy - can handle a list of 4D prob atlas files Authors ---- Mike Tyszka, Caltech Brain Imaging Center License ---- This file is part of atlask...
29c4d5a126471ed9889cbe097b97d9ad24a0d7c5542ce6b3002a90165bf48f8c
Python
2,373
71
# Copyright (c) DP Technology. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from hashlib import md5 def pad_1d_tokens( values, pad_idx, left_pad=False, pad_to_length=None, pad_to_multiple=1, ): """Convert a list...
09653c46b4602a5d2d0f2ff4d0fa6efb80958fc37cd268f58a29913c29cd10d3
Python
2,375
81
# The script plots the neural and behavioural data contained in a .h5 file of the Diomedi et al., 2023 dataset # in the form of a raster plot # authors: Stefano Diomedi # date: 10/2022 import numpy as np import matplotlib.pyplot as plt from supportFunctions import get_all_data_from_level_h5_rec import tkinter as tk fr...
0b87654fade601f69b0cb95c4fab02f88777128f991faa8b78946e9b534542e7
Python
2,375
66
# 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: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If wo...
6676d02e39c8e98f95a223b241109abb53d22fcabdfa45b14a9b3921b98de3b5
Python
2,375
77
import signal import sys import pytest from langchain_core.agents import AgentAction, AgentFinish from langchain_core.exceptions import OutputParserException from langchain_classic.agents.output_parsers.react_single_input import ( ReActSingleInputOutputParser, ) def test_action() -> None: """Test standard p...
248869dd392c83dd4d3ec39cd63da0bd1fb450bf44303671b9ac0d7489c0cf50
Python
2,380
66
from mimic3models.metrics import print_metrics_binary import sklearn.utils as sk_utils import numpy as np import pandas as pd import argparse import json import os def main(): parser = argparse.ArgumentParser() parser.add_argument('prediction', type=str) parser.add_argument('--test_listfile', type=str, ...
47e9a3ded06da695afdc0d613d88afd5fb1e228b7aeab743718d0e604022cb0c
Python
2,381
56
from torch.utils.data import Dataset import numpy as np from torchvision import transforms import torch from src.napari_svetlana.PredictionDataset import max_to_1, min_max_norm import cupy as cu from cucim.skimage.morphology import dilation, ball import matplotlib.pyplot as plt class Prediction3DDataset(Dataset): ...
7fd56f6444d4f33c6fd388e9f0d23191c1aa4fe325ec98a119d4582c4468c571
Python
2,382
65
"""**Document Transformers** are classes to transform Documents. **Document Transformers** usually used to transform a lot of Documents in a single run. """ from typing import TYPE_CHECKING, Any from langchain_classic._api import create_importer if TYPE_CHECKING: from langchain_community.document_transformers i...
852bea6088a718352f350799916a4c9dba0e4692b2a9af9b68402f23644c7472
Python
2,383
70
""" Post-processes deepsignal extract output: add high-confidence labels, removing sites w/o high confidence in methylation status. """ import sys import pandas as pd from utils.constants import METHYL_BED_COLS from utils.constants import DEEPSIGNAL_EXTRACT_COLS def label_extract(feat_filename, methyl_filename, wri...
f2bb6da30c074309fc472f096ee4013d757af349ee190f473fcb3346a2fafc8e
Python
2,386
39
from pydantic import BaseModel class Adaptor(BaseModel): fasta_file: str = "" # url that can use to download a FASTA file, choose fasta_url or fasta_file as input fasta_url: str = "" # fasta_file path, choose fasta_url or fasta_file as input specificity_url: str = "" # specifi...
29ac1b35db1ded0326173c50bd4aff7cce386b59733bcacb1a87c8c7331da8a1
Python
2,387
76
import pandas as pd import numpy as np import sys import os def get_start_index(df, cnv_start): if cnv_start <= df.iloc[0].start: return 0 else: start_index = df.index[df["start"] <= cnv_start].tolist()[-1] if df.iloc[start_index].end <= cnv_start: start_index += 1 ...
c1694f3310884e86ad3a541396ad33603e2d2bc3cc92009a6e5b4b71f152dfb2
Python
2,387
99
#pip install pyarrow #pip install fastparquet import pandas as pd import numpy as np import pyarrow.parquet as pq import copy as cp import pickle as pk import functions_paths as fpt def normalize_vec(vec): x = len(vec) new_vec = np.zeros(x) mi = min(vec) ma = max(vec) for i in range(0,x): ...
bd78b145ac749c3ec6a1bbac1af160a145cb471bc83c14bfd4a4a2ff950faf01
Python
2,389
61
import argparse from pathlib import Path from tempfile import TemporaryDirectory from alpaca import ProvenanceGraph, AlpacaProvDocument def add_suffix_to_gexf_file(source, suffix): return source.parent / (source.stem + f"_{suffix}.gexf") def merge_graphs(merged_file, *source_files): doc = AlpacaProvDocumen...
284fa2a81e48f71f4cf7645242959dbaff001a50473b21b215b4220c27094e0b
Python
2,390
82
from typing import Any from unittest.mock import Mock, patch from langchain_core.prompts import ChatPromptTemplate from langchain_core.runnables import ConfigurableField from langchain_classic.runnables.hub import HubRunnable @patch("langchain_classic.hub.pull") def test_hub_runnable(mock_pull: Mock) -> None: m...
6f6d0c8ace70ac71ea8c42f99fd54af5d0183428ee29788063efa146ce7f8755
Python
2,390
82
""" Write TIP3P-FB parameters into a SMIRNOFF force field. Based on https://github.com/pandegroup/tip3p-tip4p-fb/blob/master/OpenMM/tip3p-fb/tip3p-fb.xml """ from openff.toolkit.typing.engines.smirnoff.forcefield import ForceField from openff.toolkit.typing.engines.smirnoff.parameters import ( ConstraintHandler, ...
dd207c66bc9231361b93fc51d6f6495fb893b02b2e7b324cfb431fc30fdbc359
Python
2,390
61
import os import pandas as pd from src.PID import extract, k_order, full_order, batch from src.PID import PID_utils def get_performance_info(model_PID, activations, args): model_PID['avg_reward'] = activations['avg_reward'] model_PID['accuracy'] = activations['accuracy'] if args.discrete_PID: mod...
0e986ea93ec33eeefb495a8d1b9da52d52e3f5bc69a8ba21d9e2ea08defd6e2f
Python
2,391
62
import os import time d='/jukebox/griffiths/bert-brains/' jobs_per_sub=10 numbers=list(range(0,1001,jobs_per_sub)) with open("joblist.txt","w") as f: for dataset in ['slumlordreach','black']: #Slumlordreach if dataset=='slumlordreach': subs=['sub-145', 'sub-143', 'sub-016', 'sub-142', 'sub-141', 'sub...
702a4fb7b18090216695fe5aca3ef73b194a3a9e439bc436c34e6134932ed1c1
Python
2,392
72
import argparse import numpy as np from oset.ecg.peak_detection.peak_det_local_search import ( peak_det_local_search, ) from scipy.signal import lfilter def peak_det_matched_filter_robust(ref, fs, h, fmax, itr=1): """ peak_det_matched_filter_robust: R-peak detector based on a matched filter Syntax: ...
54475e9ff55cb26affddf8bae26caed773f01988fef01af6ddcffc9616e0bd24
Python
2,393
56
import torch from bindsnet.encoding import * class TestEncodings: """ Tests all stable encoding functions and generators. """ def test_bernoulli(self): for n in [1, 100]: # number of nodes in layer for t in [1, 100]: # number of timesteps for m in [0.1, 1.0]: #...
85427416016947e38f75fc29b905aa03ca8aab1f99c1aae969ba80e82328a6fa
Python
2,393
86
from __future__ import print_function import pandas import numpy as np from torchvision import transforms from sklearn.metrics import balanced_accuracy_score def obtain_transform(args : dict): if 'eff' in args.model_name: if 'b0' in args.model_name: size = 224 elif 'b1' in args.mode...
89c4f42c3759947a68d3340da0c66556ddf4a28efb7d4019703eb33d030028f1
Python
2,397
73
#!/bin/env python3 import voxcell as vc import numpy as np import sys fmap = vc.VoxelData.load_nrrd(sys.argv[1]) x = fmap.raw[:,:,:,0] # x coordinate in flatland y = fmap.raw[:,:,:,1] # y coordinate in flatland wx = np.array(np.where(x >= 0)).T wy = np.array(np.where(y >= 0)).T chk = np.equal(wx,wy).all() if not c...
bd97bf5cba0c552348d75b38bb530b29fd86cb94fc218d3759ef0b697bb29649
Python
2,397
67
# main file for CNN classifier evaluation # Updated: 2/27/2021 # Status: OK # CUBLAS_WORKSPACE_CONFIG=:4096:8 python cnn_eval.py import sys, os import torch import numpy as np from networks import CNN_Wrapper from utils import read_json from tabulate import tabulate def CNN_eval(model_name, config, Wrapper, num_exp...
ce7b601d9c2b41c0c57ada5087df6a19e2463a8e77c0a3e60ba7bc3fab2a1e5e
Python
2,397
65
#!/usr/bin/env python # ====================================================================== # MODULE DOCSTRING # ====================================================================== """ Test that the examples in the repo run without errors. """ # =================================================================...
d9748b8822b98ad931c63be9bf938e53b11d48fbab28889d2fa4ea50e6b60cc6
Python
2,398
69
from collections.abc import Hashable from math import log from pgmpy.structure_score.log_likelihood import LogLikelihood class BIC(LogLikelihood): r""" BIC structure score for discrete Bayesian networks. BIC, also known as the MDL score, balances discrete log-likelihood against model complexity. The loc...
df1b67d800cba38bb3e66fdee2f8c3d0e7e145a7872d10103fb83b5458d1abad
Python
2,399
81
import numpy as np import pytest from pgmpy.inference.mplp import Mplp from pgmpy.readwrite import UAIReader @pytest.fixture def mplp_instance(): reader_file = UAIReader("pgmpy/tests/test_readwrite/testdata/grid4x4_with_triplets.uai") markov_model = reader_file.read() for factor in markov_model.factors:...
9070029034a36d8ae2e317ff8ca822df1b362d6bf338da5dec2f3d5647a50e2c
Python
2,401
80
conf = {} conf_data = {} conf_data['prop_name'] = 'heat_ref' conf_data['graph_method'] = 'crystalnn' conf_model = {} conf_enc_backbone = {} conf_enc_backbone['cutoff'] = 5.0 conf_enc_backbone['num_layers'] = 4 conf_enc_backbone['hidden_channels'] = 128 conf_enc_backbone['out_channels'] = 256 conf_enc_backbone['int_e...
aaa73106e6fa5d8c88eaa7769eb2cb0b46209687b2eb7df661790e06f78d864c
Python
2,403
69
#################################################################################### # # STEPS - STochastic Engine for Pathway Simulation # Copyright (C) 2007-2023 Okinawa Institute of Science and Technology, Japan. # Copyright (C) 2003-2006 University of Antwerp, Belgium. # # See the file AUTHORS for d...
374dd537365211191d226dd702a0e32f4e65f4f614b1a38fe8e0e77243dfab78
Python
2,404
69
#################################################################################### # # STEPS - STochastic Engine for Pathway Simulation # Copyright (C) 2007-2026 Okinawa Institute of Science and Technology, Japan. # Copyright (C) 2003-2006 University of Antwerp, Belgium. # # See the file AUTHORS for detai...
b6261a4acff7e41a24f0bb5d403967a6011eeba29dd7803fde0fb710ce6fde4c
Python
2,404
58
#!/usr/bin/env python """ Cross-check energies of molecules from AlkEthOH set using SMIRNOFF xml file versus energies from AMBER .prmtop and .crd files (parm@frosst params). """ import os import glob # datapath = './AlkEthOH_tripos/AlkEthOH_chain_filt1' # datapath = './AlkEthOH_tripos/AlkEthOH_rings_filt1' datapath ...
1089783c0fabbc13b85e83e5757231604a11e34a8378ec5a57bc601e401cc958
Python
2,405
84
import math import torch import torch.nn.functional as F def log_standard_categorical(p): """ Calculates the cross entropy between a (one-hot) categorical vector and a standard (uniform) categorical distribution. :param p: one-hot categorical distribution :return: H(p, u) """ # Uniform pr...
82a639760b8face110a11b71d6c4199943e6d0ed28fac17920defd7bb42c2ae7
Python
2,405
66
# preprocess the settings for simulation class preprocess(): def __init__(self): pass def begin_of_program(self, settings): # int parameter list int_parameter_list = ["number_of_atoms", "dimensions_start_line", "dimensions...
bb9d13d95c4b2f27c604229c56d59f4a266bb4ab9af2c3921f04921d12ad727a
Python
2,405
78
"""**Embeddings** interface.""" from abc import ABC, abstractmethod from langchain_core.runnables.config import run_in_executor class Embeddings(ABC): """Interface for embedding models. This is an interface meant for implementing text embedding models. Text embedding models are used to map text to a v...
1d3b0a2a0527b9a1f883ab95f35143f37c2b3a75f3761da7191add67fe32d730
Python
2,406
66
"""Verify _release.yml dropdown options match actual package directories. Dropdown options are short names (e.g. `openai`, `core`). The workflow's `EFFECTIVE_WORKING_DIR` expression re-adds the `libs/` prefix for top-level packages and `libs/partners/` for everything else. This test reconstructs the full path for each...
ca3612df0a84ad054b79bbf50cb4246bcc14e46c05d2c9045759a0675e9c1066
Python
2,406
87
from __future__ import annotations from typing import TYPE_CHECKING, Any from langchain_core.callbacks import Callbacks from langchain_core.callbacks.manager import ( AsyncCallbackManager, AsyncCallbackManagerForChainGroup, AsyncCallbackManagerForChainRun, AsyncCallbackManagerForLLMRun, AsyncCallb...
ba2df63d6cb1c81ec5448024db52f727ec5d095c4d9b7698ab2d4703a662d92b
Python
2,408
80
conf = {} conf_data = {} conf_data['prop_name'] = 'energy_per_atom' conf_data['graph_method'] = 'crystalnn' conf_model = {} conf_enc_backbone = {} conf_enc_backbone['cutoff'] = 5.0 conf_enc_backbone['num_layers'] = 4 conf_enc_backbone['hidden_channels'] = 128 conf_enc_backbone['out_channels'] = 256 conf_enc_backbone...
4f562e32d64e7ffebdd5933e710049700b6f5aafdaa5ff927a0a2604baeff461
Python
2,410
52
import numpy as np import pandas as pd from mantis_ml.config_class import Config class HGNCtoEnsemblIDMapper: def __init__(self, cfg): self.cfg = cfg def run(self): hgnc_to_ens_gids_df = pd.read_csv('../../../../data/ensembl/hgnc_to_ens_gids.txt', sep='\t', header=None) ...
777d0930d8a7b964bf8bb747a1a20191936a0987871b151ff3b9742cb2190f34
Python
2,410
76
""" In this file the testing for the MLP for the 123 bus network is performed """ import numpy as np import gym from stable_baselines3 import PPO import torch from stable_baselines3 import A2C, PPO from stable_baselines3.common.callbacks import CheckpointCallback, BaseCallback from stable_baselines3.common...
7b968f4ff98d0011ec2f14ae18b93b7651bc8df63133d4962ec8beab9e01632e
Python
2,411
54
from pandas.core.frame import DataFrame from torch.utils.data import DataLoader, Dataset from transformers.file_utils import TensorType import torch class VirHostNetData(Dataset): def __init__(self, df: DataFrame, tokenizer, max_len, seq_col_a, seq_col_b, target_col, return_mock_data=False): super().__init...
acbbb08dab9cef57f3dd40dbd5d64d01670f7cc5329b0db80e174f14d36ea194
Python
2,411
64
# Geometric substructure mmd evaluation; More advanced MMD metric could be used here. import torch def compute_mmd(source, target, batch_size=1000, kernel_mul=2.0, kernel_num=5, fix_sigma=None): """ From DIG. Calculate the `maximum mean discrepancy distance <https://jmlr.csail.mit.edu/papers/v13/gretton1...
b002c746a2b03c17b62f5223a08ca4d4ba7fce7af0735dc0b67b6311cae55343
Python
2,411
79
import logging import os import matplotlib.pyplot as plt import numpy as np import scipy.stats import seaborn as sns # from sklearn.linear_model import LinearRegression # from sklearn.metrics import r2_score # import statsmodels.api as sm def plot_lengthscale_window_length_relation( config_dict: dict, kernel...
12ed1cf5df5a79c5233e09a4bad5ea6468a34deec9bf152989f61781a880e398
Python
2,412
64
# third party packages import numpy as np # pnabind packages from .get_residue_id import getResidueID from .get_atom_kdtree import getAtomKDTree from .data import data def getCV(structure, radius, residue_ids=None, ns=None, feature_name="cv", impute_hydrogens=False, bonds=None): """get CV values for every residue...
2c0de53312cce771a9cb50ea26154bb6bbb212ef4c4ff76b1e104f57ca83db3b
Python
2,412
75
from typing import Iterable, Iterator, Optional, Union import torch from bindsnet.encoding.encodings import bernoulli, poisson, rank_order def bernoulli_loader( data: Union[torch.Tensor, Iterable[torch.Tensor]], time: Optional[int] = None, dt: float = 1.0, **kwargs, ) -> Iterator[torch.Tensor]: ...
243087238b38872e4574f2e9766b90d10b35c8664f03f60144fda28e19aa009c
Python
2,415
44
import numpy as np def reconstruct_contour(mode, tp, rec_type='EFA', first_mode=0, last_mode=2): N_modes = len(mode.locoL.values) # timepoint -= cell->contour[cellnumber][cell->contourlength[cellnumber]].t*cell->locoefa[cellnumber][1].tau/(2.*M_PI) if mode.r[1]<0.: tp = -tp x = [ 0. for i in ...
c6593a4aac778a3231fe7a67c13e474e178c5fc3e3ea4122c7eca734bff71b21
Python
2,418
80
conf = {} conf_data = {} conf_data['prop_name'] = 'formation_energy_per_atom' conf_data['graph_method'] = 'crystalnn' conf_model = {} conf_enc_backbone = {} conf_enc_backbone['cutoff'] = 5.0 conf_enc_backbone['num_layers'] = 4 conf_enc_backbone['hidden_channels'] = 128 conf_enc_backbone['out_channels'] = 256 conf_en...
add2e46506c9b5792dab8c87ef16aa5a56bd22ee9a9c9f978c71cc39e9caef07
Python
2,421
86
import glob import logging import os import random from pathlib import Path from typing import Dict, List, Tuple import hydra.utils import numpy as np import pytorch_lightning as pl import torch import wandb from dotenv import load_dotenv from omegaconf import DictConfig, OmegaConf, open_dict from pytorch_lightning.ut...
f8946fd869aa829bad892c92b0090f2aba2e71eca90b77934f84ac3b7487f5b7
Python
2,421
79
import uncertainpy as un import numpy as np import matplotlib.pyplot as plt from prettyplot import * import os ### FIGURE7 ### data = un.Data() data.load(filename='../data/simulation_outputs/UQSA_pathological/phi_msn_5/phi_msn.h5') sobol_1_sdp = data['start_depolarization_block']['sobol_first'] sobol_tot_sdp = data['...
b5dace8f2479c607c7d0a1e9c9aa23032d993dc367b84b986d5dedb46205b19e
Python
2,422
100
import pathlib import mne study_name = "age-prediction-benchmark" bids_root = pathlib.Path( "/storage/store3/data/CHBMP_EEG_and_MRI/ds_bids_chbmp") deriv_root = pathlib.Path("/storage/store3/derivatives/CHBMP_EEG_and_MRI/") # "/storage/store2/derivatives/eeg-pred-modeling-summer-school/") subjects_dir = pathlib...
7970604aa4e211ac81bdcbf21437267839d25c2d63226b9d80c99748d2c7e06e
Python
2,424
71
from bindsnet.datasets.alov300 import ALOV300 from bindsnet.datasets.collate import time_aware_collate from bindsnet.datasets.dataloader import DataLoader from bindsnet.datasets.davis import Davis from bindsnet.datasets.spoken_mnist import SpokenMNIST from bindsnet.datasets.torchvision_wrapper import create_torchvision...
50b2668bdd923c22159bb4a1ab95823628d9accf1e847ca2c525f321d0814751
Python
2,427
80
import pytest from langchain_classic.evaluation.parsing.json_schema import JsonSchemaEvaluator @pytest.fixture def json_schema_evaluator() -> JsonSchemaEvaluator: return JsonSchemaEvaluator() @pytest.mark.requires("jsonschema") def test_json_schema_evaluator_requires_input( json_schema_evaluator: JsonSchem...
927a278b62ba142bedad15515b1b3dcad5622dca4f086a479e4e464cf0f59f9d
Python
2,427
77
import torch import torch.nn as nn class GCN(nn.Module): def __init__(self, in_ft, out_ft, bias=True): super(GCN, self).__init__() self.fc = nn.Linear(in_ft, out_ft, bias=False) self.act = nn.PReLU() if bias: self.bias = nn.Parameter(torch.FloatTensor(out_ft)) ...
f1ec3bf7b6ad2112e1a758ff067f514ce905851b5e7815da520710a48587fc41
Python
2,430
56
# Copyright (c) MONAI Consortium # 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 applicable law or agreed to in writing, so...
6351ce46b291eb4fe52e1f09a474ae9de902783b1b89730152fc07eb34ec976d
Python
2,431
77
"""Test in memory docstore.""" from typing import Any from langchain_classic.output_parsers.combining import CombiningOutputParser from langchain_classic.output_parsers.regex import RegexParser from langchain_classic.output_parsers.structured import ( ResponseSchema, StructuredOutputParser, ) DEF_EXPECTED_RE...
ccf29656a455d5a6d1052401b5fb0931b8ca7e0638a8c2cb5bb3a944eb154406
Python
2,432
71
from langchain_core.agents import AgentAction, AgentFinish from langchain_core.messages import BaseMessage from langchain_core.outputs import ChatGeneration, Generation from typing_extensions import override from langchain_classic.agents.agent import MultiActionAgentOutputParser from langchain_classic.agents.output_pa...
b7023711463aa218a9c1d66a0946f1b7df2c6b8e0405b447cdbf82347ec69903
Python
2,433
77
from omegaconf import OmegaConf from pathlib import Path import matplotlib.pyplot as plt import mlflow.pytorch import mlflow import nibabel as nib import numpy as np import torch from monai.config import print_config from monai.utils import set_determinism def main(args): set_determinism(seed=args.seed) prin...
e18e88452017dbd5398a87f0e62d4959f28173f0c3dc96185c98fc1df5a175de
Python
2,434
67
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # pylint: skip-file import sklearn.linear_model import scipy.io import matplotlib.pyplot as plt import numpy as np import torch from embanded.embanded_torch import EMBanded # Load data from the 'example01.mat' file data = scipy.io.loadmat('example01.mat') device = torch...