sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
84b3bd14fd2fc4849ac4999d4731bc03354734823d86e51bb8fbf6813799167c
Python
1,696
44
import numpy as np import torch class EarlyStopping: """Early stops the training if validation loss doesn't improve after a given patience.""" def __init__(self, patience=1, verbose=False, delta=0): """ Args: patience (int): How long to wait after last time validation loss improved...
acce3ffd3396688da9380a0bdffe736e4e257cfafdb6956c842121e7a5b9b1ff
Python
1,697
61
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. _base_ = [ '../_base_/models/upernet_convnext.py', '../_base_/datasets/ade20k.py', '../_base_/default_runtime.py...
b8314a248b6b39504b06067db4b6550670266bb305967c790058708f09fb7994
Python
1,697
52
import os import sys import re import types import itertools import PeakcallingReport import Annotations from cgatReport.Tracker import * ########################################################################## ########################################################################## ##############################...
1b35050762186fa1df2716f56147c35f6c2a9d5770505f19673612f26df41ece
Python
1,699
53
import os import sys import socket import pandas as pd from configs.configs import get_config_dict from helpers.kernel_analysis import plot_lengthscale_window_length_relation if __name__ == "__main__": model_name = sys.argv[1] # 'VWP_joint' or 'SVWP_joint' data_split = 'all' kernel_param = 'kernel_le...
e19d6cb4a357eb0f466ada589c0569a8a636ae9711025259f68c5390a6cf202c
Python
1,700
73
from pathlib import Path import mne study_name = "age-prediction-benchmark" # On drago N_JOBS = 80 bids_root = Path("/storage/store3/data/LEMON_EEG_BIDS") # deriv_root = Path("/storage/store3/derivatives/LEMON_EEG_BIDS/") deriv_root = Path("/storage/store3/derivatives/LEMON_EEG_BIDS_2/") subjects_dir = Path('/storage...
acb4c848c04b46b2d9553f730f3eb571e00fc6cf2233e2fd9328698e7581293d
Python
1,701
42
from dataset import CrossDocked2020_SBDD, collate_mols from torch.utils.data import DataLoader from rdkit import Chem dataset = CrossDocked2020_SBDD() atomic_num_to_type = {} atomic_element_to_type = {} for i in range(len(dataset)-1, -1, -1): if i%1000 == 0: print(i) print(atomic_num_to_type) ...
475fa3c6aa4d8bf5e343b85bd35a4b83fa3c088ba38d1090607dc9215a150283
Python
1,703
50
import torch from torch.optim import SGD # Additional Scripts from utils.transunet import TransUNet from utils.utils import dice_loss from config import cfg class TransUNetSeg: def __init__(self, device): self.device = device self.model = TransUNet(img_dim=cfg.transunet.img_dim, ...
814768f8109881aa761f9df45a5cab7f25a383a8ab05f17b4af71b30bf56ea91
Python
1,703
62
import numpy as np import steps.interface from steps.geom import * from steps.model import * from steps.rng import * from steps.saving import * from steps.sim import * from . import DiffPoint ######################################################################## # Inject species in the whole mesh and let them degra...
e950775d50abf066396ab00a92ddd467cb196b72af9f2eb143600769398a849b
Python
1,703
61
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. _base_ = [ '../_base_/models/upernet_convnext.py', '../_base_/datasets/ade20k.py', '../_base_/default_runtime.py...
0f3b72861ffe451fd1f77c09ddeda5b39ff15e079247ccb0c3f5edff46d346e3
Python
1,704
58
import torch.nn as nn import torch.nn.functional as F from torch import Tensor from torch.nn import LayerNorm, ReLU, Linear from torch_geometric.nn import GATConv, DeepGCNLayer from sklearn.metrics import f1_score class SMNetEncoder(nn.Module): def __init__(self, in_channels, hidden_channels, num_layers, edge_vec...
199a84956d90e2b24a2821b5485ac38b31919b5534d55cbe9d6ea604b95811d7
Python
1,704
58
import torch.nn as nn import torch.nn.functional as F from torch import Tensor from torch.nn import LayerNorm, ReLU, Linear from torch_geometric.nn import GCNConv, DeepGCNLayer from sklearn.metrics import f1_score class SMNetEncoder(nn.Module): def __init__(self, in_channels, hidden_channels, num_layers, edge_vec...
e103444cecb55250dd79bb5d04bb6b6e8f33d8fd186d175b98a372480fbc401a
Python
1,704
68
import os import numpy as np import scipy import scipy.spatial def append_feature(raw, data, flaten=False): data = np.array(data) if flaten: data = data.reshape(-1, 1) if raw is None: raw = np.array(data) else: raw = np.vstack((raw, data)) return raw def calculate_map(fts...
d408d1e8b94abef0d40f9fe5d12fa8f719cce4e2ba95b49de58ef4262c9f1ca8
Python
1,705
40
import unittest from scripts import extract_workflow_connections from scripts import prepare_data class TestRecommendationSystemData(unittest.TestCase): def test_recommendation_system_data(self): workflow_file_path = "scripts/tests/test_data/worflow-connection-subset-20-04_test.tsv" tool_usage_f...
cd140d97e8592a590e8960502a4ddb80f5adeddbe1971f2d314489e1f8d534b7
Python
1,706
49
import runpy import sys from pathlib import Path import pytest from pgmpy.base import PDAG from pgmpy.utils import _warnings @pytest.mark.parametrize("category", [UserWarning, FutureWarning]) def test_warn_external_reports_test_caller(category): with pytest.warns(category, match="Check this result") as recorded...
e11d21969320e6d09bb98b4e6bafc8ff6b1b7d5bf9a678147be6849251936746
Python
1,706
56
from bmtk.builder.networks import NetworkBuilder import cell_functions net = NetworkBuilder('single_neuron') net.add_nodes(cell_name='Cell_569998790', potental='exc', model_type='biophysical', model_template='ctdb:Biophys1.hoc', model_processing='aibs_allactive_a...
6bd283ddde458d73792af9e88bd11ee3c63769ef728cadf195b6d30a08fa37aa
Python
1,707
56
from bmtk.builder.networks import NetworkBuilder import cell_functions net = NetworkBuilder('single_neuron') net.add_nodes(cell_name='Cell_471077857', potental='exc', model_type='biophysical', model_template='ctdb:Biophys1.hoc', model_processing='aibs_allactive_a...
ba9a1b46408d1b4b119080026181a9d36b66fd91d1c6bc9387b220eb92faf8c4
Python
1,707
56
from bmtk.builder.networks import NetworkBuilder import cell_functions net = NetworkBuilder('single_neuron') net.add_nodes(cell_name='Cell_471077857', potental='exc', model_type='biophysical', model_template='ctdb:Biophys1.hoc', model_processing='aibs_allactive_a...
bdfa602c2b4da4be6b73f42b7573010eb55344c18a48487e062f56309e73d8aa
Python
1,707
56
from bmtk.builder.networks import NetworkBuilder import cell_functions net = NetworkBuilder('single_neuron') net.add_nodes(cell_name='Cell_488698341', potental='exc', model_type='biophysical', model_template='ctdb:Biophys1.hoc', model_processing='aibs_allactive_a...
f207cd32ac09b04e5ea1aed02e270d95829d30b79630498555c59439dc60c09c
Python
1,707
56
from bmtk.builder.networks import NetworkBuilder import cell_functions net = NetworkBuilder('single_neuron') net.add_nodes(cell_name='Cell_354190013', potental='exc', model_type='biophysical', model_template='ctdb:Biophys1.hoc', model_processing='aibs_allactive_a...
0d868a87d8553931784df35644dd8b6fc9d11822dca5aebecdad18d86a6cf9c7
Python
1,708
56
from bmtk.builder.networks import NetworkBuilder import cell_functions net = NetworkBuilder('single_neuron') net.add_nodes(cell_name='Cell_354190013', potental='exc', model_type='biophysical', model_template='ctdb:Biophys1.hoc', model_processing='aibs_allactive_a...
48711ec99c76d595b15bbe24bfb7763433dc21dfb60e787a6a495d6f02dfa9c2
Python
1,708
56
from bmtk.builder.networks import NetworkBuilder import cell_functions net = NetworkBuilder('single_neuron') net.add_nodes(cell_name='Cell_488698341', potental='exc', model_type='biophysical', model_template='ctdb:Biophys1.hoc', model_processing='aibs_allactive_a...
5e796aa5a435ca37f3a1a2877783e67a1ba98a289921c779355e3f9a029bbab7
Python
1,708
57
from bmtk.builder.networks import NetworkBuilder import cell_functions net = NetworkBuilder('single_neuron') net.add_nodes(cell_name='Cell_569998790', potental='exc', model_type='biophysical', model_template='ctdb:Biophys1.hoc', model_processing='aibs_allactive_a...
b130d5e75b6e7023b1552cf8452709015b9ccd3cd0e860ab5c5653c80c6159ed
Python
1,708
41
r"""A logger related utils file: tqdm style, logger loader. """ import os from datetime import datetime from cilog import create_logger from torch.utils.tensorboard import SummaryWriter pbar_setting = {'colour': '#a48fff', 'bar_format': '{l_bar}{bar:20}{r_bar}', 'dynamic_ncols': True, 'ascii': '░▒█'} ...
ffb7fbdeb5c9f7311c1dff5080959dcc6ae86e1f953cbf22233d8ddd2cc9cf5c
Python
1,708
49
""" This module is an example of a barebones function plugin for napari It implements the ``napari_experimental_provide_function`` hook specification. see: https://napari.org/docs/dev/plugins/hook_specifications.html Replace code below according to your needs. """ from typing import TYPE_CHECKING from enum import En...
58566f14aca14699a54e090d44f774763fd119b616803767aeea4ad9c1ff4d8c
Python
1,709
51
import argparse from dival import DataPairs from dliplib.reconstructors import get_reconstructor from dliplib.utils.helper import load_standard_dataset from dliplib.utils.plot import plot_reconstructors_tests from dliplib.utils.helper import set_use_latex set_use_latex() def get_parser(): """Adds arguments to ...
f8bbfca6a12bbfead3492ac60d154af79f6519bb85ce36063ae71bdc3a249e52
Python
1,709
44
"""Test for CombinedMemory class.""" import re import pytest from langchain_classic.memory import CombinedMemory, ConversationBufferMemory @pytest.fixture def example_memory() -> list[ConversationBufferMemory]: example_1 = ConversationBufferMemory(memory_key="foo") example_2 = ConversationBufferMemory(memo...
3038e5eeb128a6d16ced561a6d324ce039755a6ae1d9927282c80cf73b440dbb
Python
1,710
54
import os import sys import re import types import itertools import matplotlib.pyplot as plt import numpy import numpy.ma from ChipseqReport import * import Annotations ########################################################################## ##########################################################################...
cdaaaa13cc4cd167a8c0ff8c56e7699dcc54b962f6253accd00917b0dbf481d8
Python
1,710
50
from typing import Any from langchain_core._api.deprecation import deprecated from langchain_core.runnables.base import RunnableBindingBase from langchain_core.runnables.utils import Input, Output @deprecated( since="1.0.7", removal="2.0.0", message=( "langchain_classic.hub.pull is deprecated. Us...
bf089bb8637daa6cb891b1a9008d3a1cbff003e025c42f051f6125f3e9e31b2f
Python
1,711
61
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. _base_ = [ '../_base_/models/upernet_convnext.py', '../_base_/datasets/ade20k_640x640.py', '../_base_/default_ru...
faeb0df07cff1feac431680465474a1c131baded980b52e5f90ff34c24c79e38
Python
1,711
37
from django.shortcuts import render from django.contrib import messages from django.views.generic.edit import FormView from django.core.exceptions import ValidationError from .forms import PsthAnalysisForm from .models import Analysis from .psth_analysis import psth class IndexView(FormView): model = Analysis ...
23b46dc227c318481d683722fb5204cf42441e7fe333c1bfb5cb106064f78d1b
Python
1,712
55
""" To ease the pain of ensuring compatibility with new data structures or datasets, this file collects key IO functions for data, metadata, and annotations that may be edited by a user to fit their particular use case. """ import h5py import json import numpy as np import os import pandas as pd from pathlib import Pa...
6eee9855d66a2955f2163b2c21b41e5f234d18146ba82a009b1ee38369430ea7
Python
1,712
61
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. _base_ = [ '../_base_/models/upernet_convnext.py', '../_base_/datasets/ade20k_640x640.py', '../_base_/default_ru...
f5e4658ff4c280d9300049ba91ba916add26b85e7aaa41226c82160359e0d2ae
Python
1,712
42
import argparse from pathlib import Path from alpaca import ProvenanceGraph def main(source, output): source_path = Path(source).expanduser().absolute() output_path = Path(output).expanduser().absolute() prov_graph = ProvenanceGraph(source_path, attributes=('dtype', 'sha...
38f1ae03b3b7fbc23ec070a505ced856c06969c8741bc141b40048307b0e5788
Python
1,713
47
#%% import libs import pandas as pd import numpy as np import tangram as tg import scanpy as sc import time dt_dir = "benchmark/" #%% import ref sc data sc_data_ref = pd.read_csv(dt_dir+"hippo_t1_t4/sc_ref/sc_ref_hippo.csv",index_col=0) sc_data_labels = pd.read_csv(dt_dir+"hippo_t1_t4/sc_ref/sc_label_hippo.csv",index_...
48c3aec00c34148bf636737d2a8b266563e15a6488ffe79c921bc3a93149637a
Python
1,713
61
import subprocess import re # The name of your test executable TEST_BINARY = "../build/bin/debug/rayx-core-tst" def list_tests(): """Run the test binary with --gtest_list_tests to get a list of all tests.""" result = subprocess.run([TEST_BINARY, '--gtest_list_tests'], stdout=subprocess.PIPE, text=True) ...
1c9466e9de9e661353fc3876752e118eae540dc2fe6ed1a4285daee3dff0140e
Python
1,716
61
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. _base_ = [ '../_base_/models/upernet_convnext.py', '../_base_/datasets/ade20k_640x640.py', '../_base_/default_ru...
52d1aada56c043d958e127ab4775cc7818f71f7db7b5d35d9119aad0104df688
Python
1,716
54
#################################################################################### # # 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...
ba4261f49acb87e5a3e01b81c4b3db05df4026b172663693da88cb542d4be309
Python
1,716
54
from copy import deepcopy import random import numpy as np from torch_geometric.data import Batch class BalancedDataLoader(object): def __init__(self, data_list, nc, batch_size, shuffle=True): self.data_list = data_list self.nc = nc self.batch_size = max(batch_size, nc-1) ...
856f434d47fe71d16ba42f5e840b1d3e7f512003272f0487da209b1d1610fb3b
Python
1,717
64
import MDAnalysis as mda import pyemma import numpy as np import os import requests # -- Functions to download from online repositories def download_from_gpcrmd(filename, folder): """ Downloads a file from GPCRmd. Parameters ---------- filename : str Name of the file to down...
983498149b18b99ba1d6137d52e2563cfccfbb3fa94b461448353eb6192cd503
Python
1,718
58
import torch.nn as nn import torch.nn.functional as F from torch import Tensor from torch.nn import LayerNorm, ReLU, Linear from torch_geometric.nn import SAGEConv, DeepGCNLayer from sklearn.metrics import f1_score class SMNetEncoder(nn.Module): def __init__(self, in_channels, hidden_channels, num_layers, edge_ve...
facec29810da04024b18b1abaa1f4d8f05936488888b90f1165824e0300e2386
Python
1,718
32
""" Script to regenerate all videos related to experimental data analysis. This script also generates the plots shown in Figure 2a. Running this script requires raw data that is ~1 TB large and can be requested from the Authors of the manuscript. Author: jonas.braun@epfl.ch """ from vid_functional import make_function...
4c4e9a95c0a036ed9a317d63feb1d530cb72418c175855c5551e71d918d329d1
Python
1,719
44
#!/usr/bin/python2.7 #dbsnp_hash_table_maker.py #uses pandas commands to take in downloaded BED files and make hash tables with rs numbers as keys and GRCh38 chromosome positions as values #designed to take bed_chr_#.bed.gz files and output json hash table files in same directory import pandas as pd import json def ...
86a6085aa06d508a3a42653489498592e5ce6a02974be615d582b71a5510202b
Python
1,719
90
#!/usr/bin/env python # coding: utf-8 # In[1]: import numpy as np import pandas as pd import numpy as np from numpy.random import randn import pandas as pd import math import pingouin as pg from scipy.cluster.hierarchy import linkage, dendrogram, leaves_list from scipy.spatial.distance import pdist from sklearn.dec...
18affaecfb7f8d7acf9e6917e1d46044b4e74c7dc06ecd395411ff6c6258b91b
Python
1,720
56
import numpy as np import os import torch from torch.autograd import Variable import torch.nn as nn import torch.utils.data as data from config import get_test_config from data import ModelNet40 from models import MeshNet from utils.retrival import append_feature, calculate_map cfg = get_test_config() os.environ['CUD...
22e0ef2381e50928301f5d1c2f67a0f622b22ff2fc88ef6ea1fa6be2ba459aa4
Python
1,720
90
from langchain_classic import llms EXPECT_ALL = [ "AI21", "AlephAlpha", "AmazonAPIGateway", "Anthropic", "Anyscale", "Arcee", "Aviary", "AzureMLOnlineEndpoint", "AzureOpenAI", "Banana", "Baseten", "Beam", "Bedrock", "CTransformers", "CTranslate2", "Cerebr...
40047b1927c9404109bf51035f6454ca361b47ff5a6f4e26119a4f4d5fe64ea8
Python
1,720
50
import numpy as np import torch from torch_geometric.data import Batch from . import dataset_register from .utils.load_data import process_graph from .utils.collate_fn import BatchDenseMatrix def process_data(smiles, model_name='gin'): graphs = process_graph(smiles) if model_name == 'gin': loader = Ba...
4d181582d75593b3ecf699ebb2408a9642ba0065a0e8faf1379af6539d0f9afc
Python
1,720
59
import torch import numpy as np def distance(p, eps=1e-10): # [*, 2, 3] return (eps + torch.sum((p[..., 0, :] - p[..., 1, :]) ** 2, dim=-1)) ** 0.5 def dihedral(p, eps=1e-10): # p: [*, 4, 3] # [*, 3] u1 = p[..., 1, :] - p[..., 0, :] u2 = p[..., 2, :] - p[..., 1, :] u3 = p[..., 3, :] - p[...
7e6954372e68acc3d04cdd9f0089fc73a5f3d2009f924323a64a566646637d5d
Python
1,720
28
from misc.positions import PositionList """This example demonstrates how to generate new imaging positions from a set of positions after the sample has been picked up and likely shifted or rotated. This method relies on measuring a set of reference positions (at least 3) before and after moving the dish. You can then ...
5f401b62bcb401c568ae7b861c498a35dce91f286471a832b9435d950af0b9f1
Python
1,724
59
from __future__ import annotations import numpy as np from libs.common.graph import Graph from libs.common.metrics import Metrics from libs.common.position import Position from libs.common.weight import Weight class Connection(Graph): def __init__(self, client: int, weight: Weight, position: Position, strongly:...
73a6adec9664e1e21c0edf0d2910ad4243a6ca51fe7ee0730a6e4219aeafd340
Python
1,724
67
import logging class Register: """ This code is extracted from delta (https://github.com/Delta-ML/delta). """ def __init__(self, registry_name): self._dict = {} self._name = registry_name def __setitem__(self, key, value): if not callable(value): r...
226520a883f4632b57ffe525fb46b7cc94bcf5b9d286d380b549900ec03eb65d
Python
1,725
52
"""Joint birefringence + phase reconstruction using the waveorder API. NOTE: Work in progress. The simulate/reconstruct pipeline runs end-to-end but the simulation physics and reconstruction quality are still being validated. """ from waveorder.api import birefringence, birefringence_and_phase, phase biref_settings ...
80ac8a8c4b167cc47ee8cb4e1942b4ae0459704acc2a6d2f756ab33d071a97ee
Python
1,725
51
#Code from https://github.com/aravindsiv/dan_qa from keras.layers import Layer from keras import backend as K import tensorflow as tf class AverageWords(Layer): def __init__(self): super(AverageWords,self).__init__() self.supports_masking = True def call(self, x, mask=None): axis = K....
4a79d4226c541fc869c8b0c2ef478bc7e4745149ebaeda8d0dc3786bee71377b
Python
1,726
44
"""Augmentation policy for pseudo-images, deliberately minimal. Pseudo-images are simpler and far less variable than natural photos, and the feature->pixel layout is *fixed and meaningful* (pixel (i,j) is always feature g). So the photo-vision augmentation toolbox is actively harmful here: * flips / rotations / cro...
080f5e09c3eeabf336df9db5a53a505be8fbfa7b7dc37bbaedac253c269e2d8d
Python
1,727
47
#! /usr/local/bin/python #'################################################################################# #'################################################################################# #' Run random search on tcga data #'################################################################################# #'######...
3fb8f89ccdd3fbd81d17116daa08a86595dedaf0b5034ce7248e5e05af2dd1fd
Python
1,727
67
"""Small utility functions""" import logging import os import platform import re from typing import Tuple import psutil import torch logger = logging.getLogger("casanovo") def n_workers() -> int: """ Get the number of workers to use for data loading. This is the maximum number of CPUs allowed for the ...
86f33a738149a56bb6ff313888b03b8eada5cf2311987994943c43c8c26d34c6
Python
1,727
63
from __future__ import annotations import numpy as np from libs.function.function import Tanh from libs.model.neurons import ( LI, LinearSelectDecoder, LinearSelectEncoder, RandomNeurons, ) class Network: def __init__( self, input_dim: int, hidden_dim: int, output...
05c27f51d6a31fce7e878e436a2068843d79d192fe27b298d73e9a57064f6f77
Python
1,731
46
from fcest.helpers.filtering import _compute_lower_frequency_cutoff import numpy as np from scipy.signal import butter, filtfilt, lfilter def bandpass_filter_data( y_observed: np.array, window_length: int, repetition_time: float, freq_high: float = 0.08 ): """ We want to remove frequencies bet...
1d304b8367ac5ea757c795293a9c646e9318e127eb3517a9df7b9034e4a8082a
Python
1,731
53
import jax.numpy as jnp import flax.linen as nn from typing import Sequence, Any from projectlib.models.layerwise import LayerwiseModule from projectlib.utils import flatten Dtype = Any class MLP(LayerwiseModule): """A simple MLP model.""" features: Sequence[int] nclasses: int dtype: Dtype = jnp.floa...
4c6c08d684c089fd034adbbdd54da54d166b1f2fd064ebda0bf1a3f4255380f7
Python
1,732
54
#################################################################################### # # 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...
a8bf5a07c62cc8d8cb1bd26342ed82de6c2226bc230eb2a3660e5e3476f621b3
Python
1,732
55
""" Implementation of the command line interface. """ from argparse import ArgumentParser from t5chem.__version__ import __version__ from t5chem.run_prediction import add_args as pred_args from t5chem.run_prediction import predict from t5chem.run_trainer import add_args as train_args from t5chem.run_trainer import tra...
756db231fcf61f4c53e29e50c56a58f50ba0b33b1cbf731950b56130af8a7072
Python
1,733
50
import pickle import csv import numpy as np import glob path_files = "pickle" path_output = "derived_files/CSV/Data" # find all pickle files: pickle_files = glob.glob(path_files + "/*.pickle") for file in pickle_files: with open(file, 'rb') as f: data = pickle.load(f, encoding='latin1') # Create csv...
0ffd4a0382f0bb828658d05df02153ffed2dfdc82ecdf66cc1c3c9bdefe36627
Python
1,734
52
try: from napari.qt import thread_worker except: raise Exception('Napari must be installed to use these features') import numpy as np import time def start_napari_signalling(viewer, dataset): """ Start up a threadworker, which will check for new images arrived in the dataset and then signal to nap...
7342b1f8875e272378bdbaddd3655027f060b0993bc881a2d92947a2b68d6bcf
Python
1,735
58
import pandas as pd import seaborn as sns def get_color_col(meta=None, color=None, verbose=False): """ Determine color column """ color = 'milestone_id' if color is None else color if color not in meta.columns: raise ValueError(f'Color column {color} is not in metadata.') return color ...
38383f0265f67126e49b9facd74e4924130d94ded5852e2b76a6d7b713c0f9e7
Python
1,737
47
import torch from src.logic import logic_utils, train_logic, test_logic, lesion from src.models.feedforward import FFNetwork from src.PID import runner from src import utils from src.parsers import logic_parser if __name__ == "__main__": """ ***************************************************************** ...
9ecbaa4d4b8bac36d1e715b06eb1e72a0588a5cab66418333deb72691283ff46
Python
1,737
46
#%% import import scanpy as sc import numpy as np import pandas as pd from GraphST import GraphST import polars as pl from sklearn.metrics import mean_squared_error,roc_auc_score,normalized_mutual_info_score,adjusted_rand_score import time #%% reading st data dataset_dir = "" libd_data_dir = dataset_dir+"benchmark/spa...
d90ed79fdb947fe25afe03d912cf463cf24f20469ebc4609a65fe10e5818a9b4
Python
1,737
65
""" 2023.08.30 author: femke.hurtak@epfl.ch Comparison of the clustering results with a shuffled control. """ import os import pandas as pd from scipy import stats import plot_params def get_cluster_stats(working_folder): # Open clustering_stats.csv as pd.DataFrame df_data = pd.read_csv( os.path.joi...
9a13c43ca87626a89c82c014fc1f0e52ec2737835c2a1867508fbfdfebed6eac
Python
1,738
49
from typing import TYPE_CHECKING, Any from langchain_classic._api import create_importer if TYPE_CHECKING: from langchain_community.chains.ernie_functions.base import ( convert_python_function_to_ernie_function, convert_to_ernie_function, create_ernie_fn_chain, create_ernie_fn_runn...
17a393bca5fb4b73dea0ed17af7751b94ce80a01bdb9683e99f9ae30f5498424
Python
1,740
37
from builtins import range from src.data import get_sim_data import numpy as np import os from sklearn.linear_model import Ridge from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score seeds = [15] # 37, 98, 137, 245] results = {'mse_train': list(), 'mae_train': list(), 'r2_train': list()} for ...
2e86e18493d93782f567f2589610bbd65817bc8609e4ca9d8d17bba5956c9b66
Python
1,740
72
"""BERNN: Batch Effect Removal Neural Networks for Tandem Mass Spectrometry. This package provides tools for removing batch effects from mass spectrometry data using deep learning approaches. """ try: from importlib.metadata import version as _meta_version __version__ = _meta_version("bernn") except Exception...
5d7b3916cd0fa068180e0a0839978ee4cb81d0bc66aa52daa5ceea80d6e7b89a
Python
1,741
53
import struct def imagej_metadata_tags(metadata, byteorder): """Return IJMetadata and IJMetadataByteCounts tags from metadata dict. The tags can be passed to the TiffWriter.save function as extratags. """ header = [{'>': b'IJIJ', '<': b'JIJI'}[byteorder]] bytecounts = [0] body = [] def w...
ba5db33f1af1331d30b19ac6bf2f7767f123b7ef984b30acae510f688d65b75a
Python
1,741
47
import os import numpy as np import pandas as pd import shutil def read_npy_files_and_csv(npy_folder_path, csv_file_path, output_folder_path): # 创建输出文件夹 if not os.path.exists(output_folder_path): os.makedirs(output_folder_path) # 获取所有npy文件 npy_files = [file for file in os.listdir(np...
4fc3ca289ab165c18ea4fad23cf2643c9085c817e865282d78ced9770e421629
Python
1,742
47
import hashlib from collections import OrderedDict from collections.abc import Iterable from collections.abc import Mapping from typing import Any def make_hash(obj: Any) -> str: """ Given a Python object, returns a 32 character hash string to uniquely identify the content of the object. The object can be...
bec058d424e11bdce2ddb04871d8a67acf3539ab8de3b43424edff6e04ecc8a4
Python
1,742
48
from torch.optim.lr_scheduler import MultiStepLR, ExponentialLR, CosineAnnealingLR, ReduceLROnPlateau from core.scheduler.schedulers import get_warm_up_lr, ConstantLR, PolynomialLR from utils.loggers import LoggerManager key2scheduler = { "constant_lr": ConstantLR, "poly_lr": PolynomialLR, "multi_step": M...
5e8a8715c6f5ad190efb18b3371d66aace65bb46ac33c708a9ef52bade9804da
Python
1,743
59
from dliplib.utils.data import generate_dataset_cache from dliplib.utils.helper import load_standard_dataset ellipses_cache_file_names = { 'train': ['cache_train_ellipses_gts.npy', 'cache_train_ellipses_obs.npy', 'cache_train_ellipses_fbp.npy'], 'validation': ['cache_validation_ell...
8b0f33c8ccbfacc2960cd715eae18422d6b7664fce1c6ab16f3c8a5a8151145e
Python
1,743
54
#!/usr/bin/env python3 """ Extracts PDB files from zip archives for all entries in provided index file """ import csv from pathlib import Path from zipfile import ZipFile import click # for info CS_ZIP_DIR = '/SAN/bioinf/afdb_domain/zipfiles' @click.command() @click.option('--index_file', '-i', requir...
e2bb25110aa8e792a78387dc7c862d599e87c9cb170074aee6ca83434e0c7466
Python
1,743
44
import numpy as np def oversample_shortterm(train_dict:None, n_dupl: None): """specify the number of short-term survivors to oversample/duplicate in training dictionary""" count_samples = len(train_dict) count_long = 0 count_short = 0 short_samples = [] # count the number of short-term and lo...
5fa99225a4b1e54d5f842ddb1b7546d7c2e8da046cf3486b5d6a11f069cfb35f
Python
1,745
38
from nowcasting.config import cfg import os import numpy as np import matplotlib.pyplot as plt base_dir = "flows" prefixs = ["ebrnn1_0", "ebrnn2_0", "ebrnn3_0", "fbrnn1_0", "fbrnn2_0", "fbrnn3_0"] forecaster_block_prefix = [] flow_num = 13 lengths = [10, 10, 10, 10, 10, 10] heights = [64, 32, 16, 64, 32, 16] widths = [...
147df21204df2d8cf1116cf0aebaecd7269b5f30d0aae3e92c79f9c87ec02b78
Python
1,749
61
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. _base_ = [ '../_base_/models/upernet_convnext.py', '../_base_/datasets/ade20k.py', '../_base_/default_runtime.py...
91108b89c7a4ff582cc1b75b2e11a8107c1e6d0c4fd8c86c8b2998d334ee3b13
Python
1,750
60
"""Interface for selecting examples to include in prompts.""" from abc import ABC, abstractmethod from typing import Any from langchain_core.runnables import run_in_executor class BaseExampleSelector(ABC): """Interface for selecting examples to include in prompts.""" @abstractmethod def add_example(sel...
175d674c5f6d06dafa43cd9a6338e0f5b66c49fbbeea3a871a7a5eabf911115c
Python
1,751
42
"""Regression checks for stage-independent file utilities.""" import hashlib import json from pathlib import Path import tempfile import unittest from preprocessing.inputs import fingerprint from utils.files import atomic_json, sha256_file class FileTests(unittest.TestCase): def test_checksum_matches_binary_payl...
85fff80d345ec6bc5cd72b01d21f554cda1054b6ec35968c5d057574f9c4962f
Python
1,751
62
import os import sys import re import types import itertools import math import numpy import iotools from cgatReport.Tracker import * from cpgReport import * ########################################################################## ########################################################################## ##########...
07ec59c9c7de6cb966cb4295d3e73c9abdd5c97dadba92d89b36529b30af8ae5
Python
1,752
51
# coding=utf-8 import torch import torch.nn as nn import torch.nn.functional as F from alg.modelopera import get_fea from network import Adver_network, common_network from alg.algs.base import Algorithm class DANN(Algorithm): def __init__(self, args): super(DANN, self).__init__(args) self.feat...
9cfaf19fbacb21776d8601e9c78bd33fac0e1b64c8ad98317a30ad012b8b265b
Python
1,752
50
import pandas as pd import numpy as np from numba import jit def get_feature(input_path,save_path): data=pd.read_csv(input_path+'/promoter_rowdata_TPM.txt',sep='\t') data=data.fillna(0) sample=list(data.columns[1:]) data['gene_id']=data['promoter_id'].map(lambda x:x.split('|')[0]) data[data==0]=np...
0bb55937f7f73f444611521e192b2dca39769a3de402da90e073e631d4663871
Python
1,753
54
from typing import TYPE_CHECKING, Any from langchain_classic._api import create_importer if TYPE_CHECKING: from langchain_community.vectorstores.redis.schema import ( FlatVectorField, HNSWVectorField, NumericFieldSchema, RedisDistanceMetric, RedisField, RedisModel, ...
7188884ab36d81fd63252a0f6d7aeea40167615d965f9d4e840280d697eeb8ef
Python
1,753
66
import numpy as np from pensa import * import random import math def get_txt_features_ala2(filename, num_frames, cossin=False): """ Parses features for ala2 from a text file. The text file must be formatted with "phi", followed by all phi angles, a blank line, followed by "psi" and all psi angles, ...
e87ca9daca8b84a8243e9cd166cc60fae833ddbb5813efe9b5fab5e665c3b57b
Python
1,754
39
import cv2 from miga_emblaze.emblaze import EmbeddingSet, Embedding, Field import os import numpy as np def to_EmbeddingSet(embeddings, colors): emb_set = EmbeddingSet([Embedding({Field.POSITION: embeddings, Field.COLOR: colors})]) return emb_set def to_Embedding(embeddings, colors): return Embedding({...
5ec83d3250ce819e6f7725481a266b1ee7f6721ab7d29516c5ba6bbe554891e9
Python
1,755
50
import torch import torch.nn as nn import torch.nn.parallel import torch.utils.data import torch.nn.functional as F from pointnet_utils import PointNetEncoder, feature_transform_reguliarzer class get_model(nn.Module): def __init__(self, num_class): super(get_model, self).__init__() self.k = num_cl...
0742e1a2d8828c21f6dab925cbcf25fc64aa6afc0589149ad65c9749074475c2
Python
1,759
52
import torch.nn as nn import torch.nn.functional as F from .mp_encoder import Mp_encoder from .sc_encoder import Sc_encoder from .contrast import Contrast class HeCo(nn.Module): def __init__(self, hidden_dim, feats_dim_list, feat_drop, attn_drop, P, sample_rate, nei_num, tau, lam): super(...
2201a227bd95fdada3112cee30945bd41bb4df10d3bd0718e58bbc3a31258b1b
Python
1,760
75
r"""A kernel module that contains a global register for unified model, dataset, and OOD algorithms access. """ class Register(object): r""" Global register for unified model, dataset, and OOD algorithms access. """ def __init__(self): self.launchers = dict() self.models = dict() ...
78d565edc686846283fc738476069b68de59c4d0fcc3312645a65e74fb05adae
Python
1,760
59
import torch.nn as nn import torch.nn.functional as F from torch import Tensor from torch.nn import LayerNorm, Linear from torch_geometric.nn import MLP, GINEConv from sklearn.metrics import f1_score class SMNetEncoder(nn.Module): def __init__(self, in_channels, hidden_channels, num_layers, edge_vec_dim): ...
10a481e5a885b5d2767aa6d3a3238f110835f925bae2ae81d87389b593c61706
Python
1,762
71
import numpy as np from voxcell import VoxelData from sys import argv, exit, stderr from os import cpu_count from tqdm import tqdm from collections import defaultdict import scipy.ndimage as nd import flatmap_util as fmutil argc = len(argv) if argc < 6: print('Usage: {} <flatmap> <flat xlen> <data> <bkgval> <ou...
867a142799bc0e8b3a54732b52092246b2b4fbdebdf08047cedac21ca34a70ab
Python
1,762
48
import numpy as np from scipy.stats import entropy from scipy.spatial.distance import jensenshannon def validate_input(a, b): if a.shape[0] > a.shape[1] or b.shape[0] > b.shape[1]: raise AssertionError("0-axis must be the wavelength and 1-axis must be the samples") if len(a) != len(b): raise ...
9425e4e425a518d694b333922b137d961a5aec10d61d4db671f1d90dff7cecb8
Python
1,762
40
import matplotlib.pyplot as plt import os import sys from glob import glob from perses.analysis import utils if __name__ == '__main__': directory = sys.argv[1] files = sorted(glob(os.path.join(os.getcwd(), directory, '*.nc'))) files = [x for x in files if 'checkpoint' not in x] f, axarr = plt.subplots(...
0dcb4abf0de8455505bb645e4598f7762517abce0e5eed8c4397c88fe323edd5
Python
1,763
71
import torch from torch import nn from genie.model.single_feature_net import SingleFeatureNet from genie.model.pair_feature_net import PairFeatureNet from genie.model.pair_transform_net import PairTransformNet from genie.model.structure_net import StructureNet class Denoiser(nn.Module): def __init__(self, c_s, c...
3bf6432406caa0a95ed3b0aa9a77483b142cd256da69d0c40b69301b9a94db6d
Python
1,763
48
import shlex import subprocess import importlib.resources as pkg_resources from typing import Union, List def get_executable_path(executable_name: str) -> str: # Use pkg_resources to find the binary within the package with pkg_resources.path('rhe', executable_name) as p: return str(p) ...
894945fa08dc4b1f3744c0eff301f927b14bde1ade16d34bee093d648c502b29
Python
1,763
57
#!/usr/bin/env python """Developer notes - Prepare for pypi: python setup.py sdist - Upload to pypi test server to check: twine upload --repository-url https://test.pypi.org/legacy/ dist/* - Use testpypi with pip: pip install --index-url https://test.pypi.org/simple/ pydeface - Upload to pypi twine upload dist/* ""...
8cf54d396d692daad09323472128a16707797e0de47b5d86b74c762f704a47d1
Python
1,763
70
import pandas as pd import numpy as np def write_csv_features(feature_names, feature_data, csv_file): """ Write features to a CSV file. Parameters ---------- feature_names : list of str Names of the features. features_data : numpy array Data for the features. Format: [frames, ...
a79eb0ff1665e889c6332c745b97ae99dff0aaa1d4ea6c01c398a6f3480e363a
Python
1,763
65
"""Test pydantic SerDe. A set of tests that verifies that Union discrimination works correctly with the various pydantic base models. These tests can uncover issues that will also arise during regular instantiation of the models (i.e., not necessarily from loading or dumping JSON). """ import pytest from pydantic im...
f0554d0634de53e37e32aac7f18d949e9a0290e18983709fa88ef62ba5f3bc81
Python
1,763
54
import re from langchain_core.output_parsers import BaseOutputParser class BooleanOutputParser(BaseOutputParser[bool]): """Parse the output of an LLM call to a boolean.""" true_val: str = "YES" """The string value that should be parsed as True.""" false_val: str = "NO" """The string value that s...
5be4df3ab4427f36a01e20961de14d95fc68df09a38478ebff7b10a5b6a18b8b
Python
1,766
56
from langchain_core.agents import AgentAction, AgentFinish from langchain_classic.agents.output_parsers.self_ask import SelfAskOutputParser def test_follow_up() -> None: """Test follow up parsing.""" parser = SelfAskOutputParser() _input = "Follow up: what is two + 2" output = parser.invoke(_input) ...