sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
59dfc3f027dec9244e6a0e6a744653005d29de458b6351fa5dabb732643872b2
Python
4,201
121
# coding=utf-8 # Copyright 2023 HuggingFace Inc. # # 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 ag...
b8630a426704c34fa607eff362b01b875024d143fb74b8c88a1fe04f98ad5c64
Python
4,202
130
# -*- coding: utf-8 -*- # (C) Copyright 2026 IBM. All Rights Reserved. # # Licensed under the MIT license. See LICENSE file in the project root for details. """Defines an analog matrix""" from typing import Any, Union, Tuple from scipy.sparse.linalg import LinearOperator from numpy import ndarray, dtype # Imports ...
efc35e67a3f6a76c5334a6b091ce6984cd922a60c535d361375204cc1fb5ea05
Python
4,204
130
#!/usr/bin/env python # -*- coding: utf-8 -*- # """ """ import argparse import os import firecloud.api as fapi from firecloud import fccore from google.cloud import storage fcconfig = fccore.config_parse() def get_bucket_name(namespace, workspace): response = fapi.get_workspace(namespace, workspace) fapi...
06c9b42414d8fe4688a252ca13a741a4b2aea2b110906bc4440f5884341fe15a
Python
4,205
105
import requests from .__config import base_url from .__aux_funcs import process_response def get_all_genes(alias=None, direction="ASC", keyword=None, pageNumber=0, pageSize=10000000, projection="SUMMARY", sortBy="hugoGeneSymbol"): """ Get all genes based on filter criteria (alias or keyword). \n :param ali...
364a53c458cbab3d88e1b2537d2d3431a648e1b3c0d47282de3bfc28121074fc
Python
4,205
83
# Copyright 2021 Division of Medical Image Computing, German Cancer Research Center (DKFZ) # and Applied Computer Vision Lab, Helmholtz Imaging Platform # # 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 L...
5a0fadec6092078007c14bb1ed3282eac3c4869fc29b9b6d908d4f9769b9068b
Python
4,205
123
import argparse import pandas as pd import pickle import time from queue import PriorityQueue from collections import defaultdict def read_pickle(f): with open(f, 'rb') as inFile: return pickle.load(inFile) def tuple2interval(t): return f'{t[0]}:{t[1]}-{t[2]}' def split_interval(iv): chrom = iv....
65da5df5a07841900401464ce128af9f8dbf8580c6053cc2782e989d7e11dd12
Python
4,205
105
#################################################################################################### # Copyright (c) 2016 - 2024, EPFL / Blue Brain Project # Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch> # # This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis> # # This program is fre...
321feded5aa4c9ae783cd1cda0f7b26d0560d9d6d7a6eb7ec459259bb3634b5a
Python
4,206
94
import torch from math import sqrt class GnTredo(object): """ Generate-and-Test algorithm for feed forward neural networks, based on ReDo """ def __init__( self, net, hidden_activation, threshold=0.01, init='kaiming', device="cpu"...
6559d9d247612ec824c12ba4cd3bbde1802c006873073809648a7964b3952b68
Python
4,210
84
# 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 __future__ import absolute_import, division, print_function import numpy as np from .datareader import MolDataReader from .datascaler import TargetScaler from ...
a600490b518f26659aa4cac795e6901dd00e3de60eae7ee68bc5ea1e155bff34
Python
4,211
125
# 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 exte...
2316a11540eed6444ecba18574b21b9c15677a60c5336b6fbf14eb6e3706d850
Python
4,212
119
#!/usr/bin/env python from __future__ import print_function import argparse import glob import json import sys import numpy as np import os LEARNED_PARAM_KEY = "readErrorModel" MIN_DIST_OFF = .00000001 def parse_args(): parser = argparse.ArgumentParser("Consolidates output learned parameters for chunked marginPha...
16f70164f2ac13cf5c3f61d023073f5fcf50b6bdd55ac3470088b1ae0eb40efc
Python
4,213
78
from keras.layers import Dense, Flatten, Conv2D, MaxPool2D, Dropout from common import SEED from keras.models import Sequential from keras.optimizers import Adam from keras import initializers def create_cnn_keras(lr=0.0004, image_shape=[64,64]): model = Sequential() initializer = initializers.he_normal(seed=...
5d37136abd0a15d9139ef13dd82b0f4c7f2ce7907b9d2320c964c648fd7ed57a
Python
4,213
113
import torch import esm import numpy as np import h5py, argparse parser = argparse.ArgumentParser() parser.add_argument("--PDB_coords_seq_hdf5", type=str, default="./", help="path for train hdf5 file for coordinates") parser.add_argument("--gpu_esm", type=int, default=[3], nargs="+", help="the IDs of GPU to be used fo...
e30e4ecc70aa389affbcf1941ddedb4d1ad71a0fa07e852919f08170200e4cf3
Python
4,213
106
#CHM height module. Given a x,y location and a pool of CHM images, find the matching location and extract the crown level CHM measurement import glob import numpy as np from src import neon_paths import rasterstats import geopandas as gpd import pandas as pd def non_zero_99_quantile(x): """Get height quantile of ...
8e553548bcae8f4a25bda4050105b190bc057b0631133998286fb4ad28d7fbae
Python
4,216
147
import numpy as np import sklearn.metrics import torch import math def calc_binary_metrics(pred, target): mat = sklearn.metrics.confusion_matrix(target, pred) tn, fp, fn, tp = mat.ravel() se = (tp) / (tp + fn) sp = (tn) / (tn + fp) ppv = tp / (tp + fp) return se, sp, ppv def prepare_roc_plot(...
41cf7830017e1a827f89aaad81b898b0ec41ecb0d79103975e3bd62421a95ad8
Python
4,218
83
"""Compare an actual MATLAB-exported fixture with the imported PyTorch model.""" import argparse import json import sys import numpy as np from scipy import sparse from scipy.io import loadmat import torch from palmnet import PalmPCAGabor from palmnet.ops import ridge_orientation def error_report(actual, expected, at...
4a101f6bd48aafdeb6bcf6e156a8ed6e5cf41e1a8dc99998fb31c528ca2bb646
Python
4,220
101
from enum import Enum from typing import Callable, Dict, List from ray._private.ray_constants import RAY_METRIC_CARDINALITY_LEVEL from ray._private.telemetry.metric_types import MetricType # Keep in sync with the WorkerIdKey in src/ray/stats/tag_defs.cc WORKER_ID_TAG_KEY = "WorkerId" # Keep in sync with the NameKey i...
4b98cc3360812cf7b8ec1ad007f15dc69241e1e342d9ad3f76ac45a32b021ef7
Python
4,220
107
from utils import * if __name__ == "__main__": SHOW = 0 # Declare the datadir and paramfile datadir = "/cfs/klemming/scratch/n/nbrav/logs/test-mnist1k/" # "/cfs/klemming/scratch/n/nbrav/logs/sparsespk-full/2024-04-21_14:40:38:083781" paramfilename = "apps/hidassospk/hidassospk.par" #f"{datadi...
9f596179ada8bd966ec430ce981b26bd561fdf3d028f12d24fbdfb40906201a5
Python
4,220
121
# -*- coding: utf-8 -*- # (C) Copyright 2026 IBM. All Rights Reserved. # # Licensed under the MIT license. See LICENSE file in the project root for details. """Base class for an Experiment Runner.""" from typing import Any, Dict, List, Optional from aihwkit.cloud.client.entities import CloudExperiment from aihwkit....
e3595a588394ce6bc73f93c4d6e918853d462162d8118722c574632eaae18301
Python
4,220
140
import logging import tempfile import numpy as np import pytest import torch from torch import nn import pfrl from pfrl.envs.abc import ABC from pfrl.experiments.evaluator import run_evaluation_episodes from pfrl.policies import ( GaussianHeadWithStateIndependentCovariance, SoftmaxCategoricalHead, ) @pytest...
ff1bf2574edd885b6636bd43fc430a8c3f7afaed8030660e37c8a85c08527b70
Python
4,220
119
# # CEBRA: Consistent EmBeddings of high-dimensional Recordings using Auxiliary variables # © Mackenzie W. Mathis & Steffen Schneider (v0.4.0+) # Source code: # https://github.com/AdaptiveMotorControlLab/CEBRA # # Please see LICENSE.md for the full license document: # https://github.com/AdaptiveMotorControlLab/CEBRA/bl...
4469f53dc750b0e425366b60db1818b81c8761bdea41338b2ee4e95e0ccf3056
Python
4,221
97
import matplotlib.pyplot as plt import numpy as np import pandas as pd from Bio import SeqIO from autogluon.text import TextPredictor from sklearn.metrics import confusion_matrix def plot_confusion_matrix(y_true, y_pred, classes, normalize=False, title=None...
c16a6c3c0e5a88b220854588c300d14480c0a525bad03635735ca5d9c6b90b24
Python
4,221
102
import pathlib path = pathlib.Path.cwd() if path.stem == 'tmb_survival': cwd = path else: cwd = list(path.parents)[::-1][path.parts.index('tmb_survival')] import sys sys.path.append(str(cwd)) import numpy as np from lifelines import CoxPHFitter from lifelines.utils import concordance_index import pandas as pd i...
8892065072f9480bc9097fdfd2993f61dab97f0e9549f7b5600ffaefa2e574e4
Python
4,222
92
import json from pathlib import Path import keras import sys sys.path.insert(0,str(Path(__file__).resolve().parents[1])) from mothra_runtime import CompatibleGRU, set_model_mode #from keras.models import load_model def prepare_data(smiles,all_smile): all_smile_index=[] for i in range(len(all_smile)): ...
8a33c96011b9669532d46362a31a43940296cb3a0b4c90c82329479fb5bb6c79
Python
4,222
119
from __future__ import annotations """ Build a new skill from a single link to cover functionality OmicVerse does not yet provide. This scaffolds a SKILL.md and scrapes the provided URL (same-domain crawl) to populate reference markdown files. Security: validates output paths and sanitizes generated filenames. """ ...
590097b4fa8c4df1d4919e57293905689be43e4c43000faaef97bb4be1b7ff40
Python
4,223
125
import os from urllib.request import urlretrieve import tarfile from dstoolbox.transformers import Padder2d from dstoolbox.transformers import TextFeaturizer import numpy as np from sklearn.datasets import load_files from sklearn.pipeline import Pipeline from skorch import NeuralNetClassifier import torch from torch i...
c92ba0a37dbb3494a27cfbeb6fcc0f888262a8973823c9f086288ec27e0f5aec
Python
4,223
159
from __future__ import print_function, unicode_literals, absolute_import, division from six.moves import range, zip, map, reduce, filter from six import string_types import numpy as np from .utils import normalize def plot_history(history,*keys,**kwargs): """Plot (Keras) training history returned by :func:`CAR...
9bed055e920444332c996be08541f5f4312127d1a00498c59fd494c9e84c9e9a
Python
4,224
118
# -*- coding: utf-8 -*- # (C) Copyright 2020, 2021, 2022, 2023, 2024 IBM. All Rights Reserved. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. #...
778cec5a6bd8842ff8414196d549238ccbe73b11da813e8d68b144c2fe502114
Python
4,225
109
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Oct 3 14:23:29 2022 @author: S_Barnett """ from glob import glob import os import pandas as pd from tkinter import filedialog as fd from docx import Document from docx.shared import Inches def retrieve_settings(input_folder: str, settings_key: str) -...
a9e1f30609e66429c1ec4f34d9adb1c32411f75c9dc0624208ea5026ccea42f1
Python
4,226
136
""" Copy from scVI (https://github.com/scverse/scvi-tools/blob/main/scvi/data/_built_in_data/_synthetic.py) """ import logging from typing import Optional import numpy as np import pandas as pd import scipy from anndata import AnnData #from scanpy import read import scanpy as sc from .._anndata_compat import as_dtyp...
b407b32bd4e9b1a3eb21fc0c40cf6f90708f19c0998942d16c4f9f1788c57806
Python
4,226
143
from absl.testing import absltest from absl.testing import flagsaver from absl.testing import parameterized import numpy as np import pandas as pd import xarray as xr import xarray_beam from . import compute_quantiles class ComputeQuantileTest(parameterized.TestCase): def _dict_to_str(self, a_dict): return ',...
c31eb77f5694d3484a57293ad2de96d7c120eb485e40eb54e622d8c10be8b11d
Python
4,226
92
#################################################################################################### # Copyright (c) 2023, EPFL / Blue Brain Project # Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch> # # This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis> # # This program is free softw...
3a9ec663614feb1b0fa6c981504b8d0faf7e9ed335b634faa520282a12b2ef57
Python
4,228
124
#!/usr/bin/env python # -*- coding: utf-8 -*- # from functools import reduce import math # Caches genotype carrier status for _is_non_ref() _carrier_map = {} def choose_best_genotype(sample, records): """ Return record where sample has best non-reference genotype, if available Parameters ----------...
ea4f9115ef2e80da60930675956c56c5b05ee722e6b4d633f54d9b8f56da46ca
Python
4,228
140
import pathlib import zipfile import numpy as np import pytest from stl import mesh _RELS = """<?xml version="1.0" encoding="UTF-8"?> <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"> <Relationship Target="/3D/3dmodel.model" Id="rel0" Type="http://schemas.microsoft.com/3dmanufa...
93487132c0400b23d95c9c480c229d9c94fca3638f9f267193cbf17c43d6213c
Python
4,230
141
from torch.nn import Linear, ReLU, Sequential, Conv2d, MaxPool2d, Module, Dropout from torch import softmax from torch.nn.init import kaiming_normal_ class CNN(Module): def __init__(self, n_dim, linear_dim): super(CNN, self).__init__() self.n_dim = n_dim self.linear_dim = linear_dim ...
215aa94e89419729ad3f5b164a9c706c9ba57ac7f28bcea4b70cedd4c8447c5a
Python
4,234
86
import os import numpy as np import matplotlib.pyplot as plt import ivim root = '/path/to/root' input_root = os.path.join(root,'data') results_root = os.path.join(root,'results') subs = [sub for sub in os.listdir(results_root) if sub.startswith('sub')] runs = ['run-{}'.format(r+1) for r in range(2)] scans = ['sIVIM'...
be7be1ef7dd86852fb41c33c8669dbf9390903a80e2436699b22546084c91a35
Python
4,234
82
#!/bin/python import argparse import logging def process_bed_file(input_bed, n_per_split, bca=True, digits=9): SVTYPE_FIELD = 5 END_FIELD = 2 START_FIELD = 1 # Conditions for each category of variants condition_prefixes = { 'gt5kb': {'condition': lambda line: (line[SVTYPE_FIELD] == 'DEL' ...
f38c076634e35f9ba4403e3301b41b926eb94403605eade1fefd94958467812c
Python
4,236
147
import struct import numpy as np import pytest from stl import mesh _STL_FILE = """ solid test.stl facet normal -0.014565 0.073223 -0.002897 outer loop vertex 0.399344 0.461940 1.044090 vertex 0.500000 0.500000 1.500000 vertex 0.576120 0.500000 1.117320 endloop endfacet endsolid test.stl """.lstrip()...
303518ee61fd153c0d5d79813358eccee054002b36c6901331270d0ed66d1886
Python
4,239
145
'''infer the underlying context by using knn with prediction error ''' import matplotlib.pyplot as plt import seaborn as sns import numpy as np from task import CSW from utils import compute_smth_mean, to_sqnp from sklearn.decomposition import PCA from scipy.spatial import distance_matrix sns.set(style='white', palet...
378499552e536a0b5bd05a7bb38f6478b1a226fec510bb73974e5b245fa59889
Python
4,239
121
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon May 27 15:36:17 2019 @author: gary """ import numpy as np import skvideo.io def intensityTimeseries(vidName, nFrames, ROI, channel=0): intense=[] videogen = skvideo.io.vreader(vidName) for i, frame in enumerate(videogen): if i%100...
104eb8f4c373b9cfe2a5285f0e691ab7bdf14a2cc311b8705dbc6d898831fb9b
Python
4,240
133
import time import numpy as np import torch import torch.nn as nn import torch.optim as optim from config import args from models import GNN, Discriminator from torch_geometric.data import DataLoader from torch_geometric.nn import global_mean_pool from util import cycle_index from datasets import MoleculeDataset de...
62119539ee69fae4ed91ac31566124bc77d7dc611da1c265a4be1ca680d127cc
Python
4,240
141
import json import numpy as np import matplotlib.pyplot as plt from spinnaker2 import snn, hardware from spinnaker2.neuron_models.spikes_from_array_latency_code import SpikesFromArrayLatencyCodeApplication from spinnaker2.helpers import read_log SpikesFromArrayLatencyCodeApplication.profiling = True rng = np.random.de...
123e6d58304b2c45c4d35c6e581913c5380064727a9324f564dc64d49faf5e05
Python
4,242
104
import os import pandas as pd import numpy as np from src.commons.process_dataframe import keep_valid_columns, change_col_value_type, insert_new_col_from_two_cols, \ get_sub_df_according2col_value, get_std, get_mean from src.commons.process_number import get_percent_change, get_deviation from src.constants.ms2_mi...
827ae3f2884bede82763864152ce0b19f9ac876bbbb2af0c96f1e94bda663c37
Python
4,242
141
import numpy as np from constants import CA_C_DIST, N_CA_DIST, N_CA_C_ANGLE def rotation_matrix(angle, axis): """ Args: angle: (n,) axis: 0=x, 1=y, 2=z Returns: (n, 3, 3) """ n = len(angle) R = np.eye(3)[None, :, :].repeat(n, axis=0) axis = 2 - axis start = ax...
8ddb36669321cb9b281b3aa9e2d5c69be30da964c992840d62fffee194a5df7f
Python
4,243
109
""" Created on: 03/18/2014 Updated on: 05/19/2017 @author: Dorjee Gyaltsen @brief: antibody epitope prediction - the main class """ import os import sys import pickle from collections import OrderedDict,namedtuple from .method_calculation import MethodScores from .util import get_sequence SequenceInfo = namedtuple(...
317e46201fda034383507bb3bb47245c30427061ea314dd6878696e7b0ee7d8f
Python
4,246
100
import pathlib path = pathlib.Path.cwd() if path.stem == 'tmb_survival': cwd = path else: cwd = list(path.parents)[::-1][path.parts.index('tmb_survival')] import sys sys.path.append(str(cwd)) import pickle import pandas as pd import numpy as np from model.model import Encoders, NN from model.layers import Losse...
b9a14cf4d9c9dbdaf4b6267e774ad54427536d691e3d3f5fe7d5f5e7692e9503
Python
4,246
125
# Copyright (c) 2017-present, Facebook, Inc. # # 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...
f462b9159488eccdb8e213c1da199ecf114ea8143f9a328189c3b144492dc37f
Python
4,246
192
# flake8: noqa # fmt: off # __dag_tasks_begin__ import ray ray.init() @ray.remote def func(src, inc=1): return src + inc a_ref = func.bind(1, inc=2) assert ray.get(a_ref.execute()) == 3 # 1 + 2 = 3 b_ref = func.bind(a_ref, inc=3) assert ray.get(b_ref.execute()) == 6 # (1 + 2) + 3 = 6 c_ref = func.bind(b_ref, in...
33847a06ee0e08753e55c8023deed06c1229cf34ffc95f3cfab26cf7ecc49c5d
Python
4,247
108
from typing import List from lqit.edit.models.base_models import BaseGenerator from lqit.edit.structures import BatchPixelData from lqit.registry import MODELS from lqit.utils import ConfigType, OptConfigType, OptMultiConfig @MODELS.register_module() class TIENetGenerator(BaseGenerator): """The generator of TIEN...
ba3a94acf9db63cac19f446cd9199cb41da8f902e9c6cf0f445c74fd0795b804
Python
4,248
128
# -*- coding: utf-8 -*- # (C) Copyright 2026 IBM. All Rights Reserved. # # Licensed under the MIT license. See LICENSE file in the project root for details. """Tests for quant conversion.""" import torch from pytest import mark from torch.nn import Linear, Sequential from aihwkit.nn.low_precision_conversion import ...
44f28067f4473276bf6d56917c3090350084b8a5d832acdce84c3d8df2fc66c8
Python
4,249
119
import unittest from math import isclose import torch from rising.transforms.functional import ( add_noise, add_value, gamma_correction, norm_mean_std, norm_min_max, norm_range, norm_zero_mean_unit_std, scale_by_value, ) class TestIntensityFunctional(unittest.TestCase): def setUp...
1bea31a31a6f12b4f3e7eca27c15e8cbb095879bd7cc321d99e16f47e082bdf3
Python
4,250
121
# -*- coding: utf-8 -*- """ Created on Mon Sep 21 15:14:00 2020 @author: ju-bar Linear search function. This code is part of the 'emilys' repository https://github.com/ju-bar/emilys published under the GNU General Publishing License, version 3 """ import numpy as np def linsrch_minloc1(data, subpix = True): '''...
f202aba982c1a06e18df85e15d69ef66ca1d919e26b3486ae81784f8fbcf76b4
Python
4,250
111
# Copyright (c) 2017-present, Facebook, Inc. # # 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...
22e0c633d9392d39b775984c2c0f791b56532baf321008173db9b004e21c94b7
Python
4,252
161
from os.path import exists, isdir, join, dirname import os import pkg_resources import argparse import sys import yaml import ngs_mapper # Raised when invalid config is loaded class InvalidConfigError(Exception): pass class Config(object): ''' Wrapper around config yaml that raises better exception messages...
e9653e9ae041d2b4eb1f3942e29c6b13a4f0347666a481af37dd8d439bc5511c
Python
4,253
95
import torch from torch.nn import Parameter # https://github.com/mourga/variational-lstm/blob/master/weight_drop.py class WeightDrop(torch.nn.Module): def __init__(self, module, weights, dropout=0, variational=True): """ Dropout class that is paired with a torch module to make sure that the SAME m...
2bdeea24f3ce7a15b4f2fc035226c1e6ba37614b3dd9cdb6f697b9cc875a2fb7
Python
4,257
90
import os import h5py import logging import argparse import traceback from collections import Counter from ml4h.defines import TENSOR_EXT, HD5_GROUP_CHAR """ This script copies all the hd5 datasets from all hd5 files within the 'sources' directories to the same-named files within the 'destination' directory. If the ...
97e4c2dfaa9613161e8e8340157562072e8c31bad562058cf61eb0687e29e8ad
Python
4,257
166
import pdb import numpy as np import matplotlib.pyplot as plt import ray from data_assimilation.particle_filter.base import BaseForwardModel from data_assimilation.test_cases.single_phase_pipeflow_with_leak.PDE_model import PipeflowEquations def compute_forward_model_PDE( forward_model, state: np.ndarray, ...
08c520e282f8becfb8990734a7a76ddc0fb502bd777a9ad2813beb53103f701d
Python
4,259
150
""" Copyright (c) Meta Platforms, Inc. and affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ from __future__ import annotations import numpy as np from scipy.optimize import curve_fit def get_she(voltage): u_she, u_rhe = fullc...
4118e2583081689164e09ed144c824b4c68b0b237ac445c02af0bd06efcf2025
Python
4,259
142
from typing import Callable, Optional import torch def lif_forward_single( input_data: torch.Tensor, alpha_mem: float, alpha_syn: float, state: dict, spike_threshold: float, spike_fn: Callable, reset_fn: Callable, surrogate_grad_fn: Callable, min_v_mem: Optional[float], norm_i...
59c6918697a4baed90272a1a9acf85ac772d5f9efbea6022c835e072a0e3363c
Python
4,259
98
import numpy as np import pytest import torch from lqit.utils import AvoidOOM from lqit.utils.memory import cast_tensor_type def test_avoidoom(): tensor = torch.from_numpy(np.random.random((20, 20))) if torch.cuda.is_available(): tensor = tensor.cuda() # get default result default_res...
0a39a560ef9637a6ea9b98f286c120846ea1c3f3faf466ea848929e6ca213fc4
Python
4,260
148
import numpy as np import tonic import torch import torch.nn as nn from sinabs import from_model, layers, set_batch_size from sinabs.backend.dynapcnn import DynapcnnNetwork from sinabs.nir import from_nir, to_nir import nir ann = nn.Sequential( nn.Conv2d( 2, 16, kernel_size=(5, 5), stride=(2, 2), padding=...
4e83252dc59606bd47620c5ec4b49e364b27adc543fd60bd4a0c58bf96ab715b
Python
4,261
145
import ipywidgets import exputils as eu #TODO: Feature - events for change of values class TextSelectionAccordionWidget(ipywidgets.Accordion): @staticmethod def default_config(): dc = eu.AttrDict() dc.title = '<selection>' dc.main_accordion = eu.AttrDict( #layout=eu.Attr...
5e6faf74169535dac89bceb61b7e5f6ed6fd93e7fb3f101aa5ffc97d842136d6
Python
4,261
128
import numpy as np from utils import random_ortho_mat class SimpleContext(): def __init__(self, context_dim, concentration, loss_q_size=10, pseudo_count=10, stickiness=10): self.context_dim = context_dim self.loss_q_size = loss_q_size self.pseudo_count = pseudo_count self.stickin...
61a5868cb8fa69a0f3eb846dfa1b6d6fcf6fd10750c4bb00f3a7928d9d6bee09
Python
4,261
166
import pdb import numpy as np import matplotlib.pyplot as plt import ray from data_assimilation.particle_filter.base import BaseForwardModel from data_assimilation.test_cases.multi_phase_pipeflow_with_leak.PDE_model import PipeflowEquations def compute_forward_model_PDE( forward_model, state: np.ndarray, ...
875dbc0396210d42bb7891a53928fca710705c492b83042ae15656fc7a0e682a
Python
4,261
136
""" Copyright (c) Meta Platforms, Inc. and affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ from __future__ import annotations import numpy as np import pytest from ase import build from ase.calculators.singlepoint import SinglePo...
0058a223b7d36028a21022d97a07d5c0a4abd903199615fe54d3851d73c8fd09
Python
4,262
89
__author__ = "Simon Andermatt" __copyright__ = "Copyright (C) 2017 Simon Andermatt" from copy import copy, deepcopy import torch as th from mdgru.helper import compile_arguments, harmonize_filter_size, generate_defaults_info from ..crnn.cgru import CGRUCell class MDRNN(th.nn.Module): """MDRNN class originally ...
0d60b2c7b97ebfab7d9c13336d67cc917f893dbdfa1e586192e3eefb17dbc99c
Python
4,262
123
import torch from diffusers import KDPM2AncestralDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class KDPM2AncestralDiscreteSchedulerTest(SchedulerCommonTest): scheduler_classes = (KDPM2AncestralDiscreteScheduler,) num_inference_steps = 10 de...
f8278ac6ded108b6a8ebf804d77448527043e227dedc157294f35ce7d08d1417
Python
4,262
106
import numpy as np import torch from torch.utils.data import TensorDataset from torch.utils.data import DataLoader class EAVDataSplit: def __init__(self, x, y, batch_size=32): self.x = np.array(x) self.y = np.array(y) self.batch_size = batch_size def _split_features_labels(self): ...
02053cacd35ce56e47f97a4740a56122c096619b955121b3a2a45b6a3ff72d4d
Python
4,263
125
# Modified from https://github.com/open-mmlab/mmediting/tree/1.x/ import functools from typing import Optional import torch.nn.functional as F from torch import Tensor def reduce_loss(loss: Tensor, reduction: str) -> Tensor: """Reduce loss as specified. Args: loss (Tensor): Elementwise loss tensor. ...
3c0530b3058c2fcca17f544a051c6f598af7899bdbe5946d3a29790a62c66ef3
Python
4,264
75
proj_dir = "/path/to/main_project_folder/" # edit this line import numpy as np import pandas as pd import xarray as xr import dask.array as da import glob as glob from functools import partial import os import sys sys.path.append(proj_dir) from project_fxns import load_region from project_fxns import fxns import impor...
5a7398a873e3983cc1864936e02c2416bb72d46173259ba6b5f75b18dbb7c786
Python
4,265
124
# Copyright 2023 Google LLC # # 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 to in writing, ...
ad014c433521f84bd3e28186d39516f17612f177000f271db4b6f40f86362df1
Python
4,265
73
import numpy as np # #significant social # lypd1 = np.array([4,8,17]) # pro neutral anti 13.7 % 27.5% 58.8% # etv1 = np.array([40,10,17]) # 59.7% 15% 25.3 # rspo2 = np.array([9,16,11]) #25 44.4 30.6 # ##significant food # lypd1 = np.array([29,7,6]) # pro neutral anti 69.1 16.7 14.2 23.8 19.0 ...
441922348a2d8926cdce1b763f3f60b423df1882ea76799eb175d1ef5b435190
Python
4,266
119
#################################################################################################### # Copyright (c) 2016 - 2024, EPFL / Blue Brain Project # Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch> # # This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis> # # This program is fre...
0d86eeec67dfd602d44a97e8c8fada733242ce725417e4d7b965ae735c0d314b
Python
4,270
117
# -*- coding: utf-8 -*- # (C) Copyright 2020, 2021, 2022, 2023, 2024 IBM. All Rights Reserved. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. #...
8eafa32c4c58ab0c104bb465f60b683e6fde280b09775ecbc69043683d5ccc46
Python
4,270
124
# built-in dependencies import sqlite3 # 3rd party dependencies import numpy as np import pytest # project dependencies from deepface.modules import datastore from deepface.modules.database.sqlite import SqliteClient from deepface.modules.exceptions import DuplicateEntryError def _record(seed: int, model_name: str ...
59f8d5e962ae9fc05df54c62eff962a4692f0ee9671371e57fd2800fc083b98c
Python
4,271
111
"""Base class for building internal Ray events. This module provides the base class for creating event builders that can emit events to dashboard-agents aggregator agent service. """ from abc import ABC, abstractmethod from typing import Optional from ray._raylet import RayEvent from ray.core.generated.events_base_e...
6b53135f69fcf09fe7c544d6e425551f17158ae4cd3fbe1a867a762af2f21c44
Python
4,271
132
#!/usr/bin/env python """ Useful utilities for intervals and interval trees. """ from intervaltree import IntervalTree, Interval import svtest.utils.VCFUtils as vu # Creates dictionary of trees[sv_type][contig] from iterable records of VariantRecords def create_trees_from_records(records, variant_types, contigs): ...
7425f6980ff43a3298f53f9841a3ec223cac78ac4418d367637a12735a8b9475
Python
4,271
93
# # CEBRA: Consistent EmBeddings of high-dimensional Recordings using Auxiliary variables # © Mackenzie W. Mathis & Steffen Schneider (v0.4.0+) # Source code: # https://github.com/AdaptiveMotorControlLab/CEBRA # # Please see LICENSE.md for the full license document: # https://github.com/AdaptiveMotorControlLab/CEBRA/bl...
7a86bfdc6e54d2c45b8852611084cf8d2f115b3f821b56d94a4d61fb1f5b27d4
Python
4,272
131
from dataclasses import dataclass from typing import Tuple, Dict import numpy as np from denoise_inverse_alg.glm_inverse_alg import _compute_raw_coupling_indices from lib.data_utils.matched_cells_struct import OrderedMatchedCellsStruct from optimization_encoder.trial_glm import FittedGLMFamily, FittedFBOnlyGLMFamily ...
10d035593d843d572182e2e268677dcfd55291fa4b7e3c5cf69cf21c9f0df4f0
Python
4,274
130
#!/usr/bin/env python from __future__ import print_function # batteries import re import sys import gzip import argparse import logging from time import time # 3rd party from lxml import etree # argparse desc = 'Convert UniRef XML to taxonomy table' epi = """DESCRIPTION: A simple script to convert UniRef XML to table ...
1c23024fcb5b57dd9e667f0d8ddb6623aac31421b36e09fa49b412cddf3de525
Python
4,274
129
from typing import TYPE_CHECKING import pandas as pd if TYPE_CHECKING: from .schemas import ( ClassificationTarget, RegressionTarget, TabularDatasetData, ) __all__ = [ "generate_classification_target", "generate_regression_target", "merge_signals_from_multiple_cameras", ] ...
f1bd893b602c5bb3df5e4c5a47c38cf3569ddfd53ffd464af9e02db824093200
Python
4,274
95
#################################################################################################### # Copyright (c) 2020 - 2024, EPFL / Blue Brain Project # Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch> # # This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis> # # This program is fre...
05c6f6f7c86f064461f1c9e483427f257f9b3b5db548be9a7aad53140cef1e36
Python
4,275
146
import os import json from typing import Dict, Any, Union, Optional import boto3 import xarray as xr import numpy as np from neuron_morphology.transforms.pia_wm_streamlines.calculate_pia_wm_streamlines import run_streamlines from harness import step_fns_ecs_harness s3 = boto3.client("s3") DatasetLike = Union[xr....
64a24759ac5ab1d45ff742dbe5240fa4346e2808a711be623b4ca49a2cf620db
Python
4,275
136
''' check if we can cluster the scene vectors in particular, can we derive good clustering parameters from the training set and generalize to the validation set this is essential for the clustering based shortcut model to work ''' import os import pickle import numpy as np import pandas as pd import seaborn as sns imp...
3eccbf648a7f2b32c4b511b1eaec4217fb0d5ab66e49a294fe6281978e9411e5
Python
4,276
139
import logging import numpy as np import scipy.sparse as sp from scipy.sparse import csr_matrix, issparse def linear_embedding_velocity(V, PCs): return V @ PCs def _estimate_dt(X, V, nbrs_idx): """Estimates the time step (`dt`) based on local density for each cell. This function calculates an estimate ...
a3f956bec505da63e1008e0e96747277b9bcf7023f012d6abf09b3fb8bb50584
Python
4,276
124
import os from deepinterpolation.generator_collection import SingleTifGenerator from deepinterpolation.trainor_collection import core_trainer from deepinterpolation.network_collection import unet_single_1024 import datetime import pathlib if __name__ == '__main__': # This is used for record-keeping now = datet...
6d27cc44ddcb8a4600882fccd81fd44b40eb58940e17f9a7727ed82d716ef181
Python
4,277
118
import logging from ray._private.utils import get_num_cpus logger = logging.getLogger(__name__) CPU_USAGE_PATH = "/sys/fs/cgroup/cpuacct/cpuacct.usage" CPU_USAGE_PATH_V2 = "/sys/fs/cgroup/cpu.stat" PROC_STAT_PATH = "/proc/stat" container_num_cpus = None host_num_cpus = None last_cpu_usage = None last_system_usage ...
51c006efffd63b0bc7d99e590e89d8c2c19e105c1afbec7de3685b3ad6d42d09
Python
4,278
123
import os import subprocess as sp import unittest import shutil import tempfile from neuron_morphology.morphology_builder import MorphologyBuilder from neuron_morphology.swc_io import morphology_to_swc from neuron_morphology.transforms.scale_correction.compute_scale_correction import ( estimate_scale_correction, r...
84df45bbbda2b7b3e67e19846304deb81c0d6f3fb6198144f58676796a55b3de
Python
4,279
119
# -*- coding: utf-8 -*- import pytest from nilearn.image import concat_imgs, index_img, math_img from nilearn.maskers import NiftiMasker from numpy.testing import assert_array_almost_equal from fmralign.template_alignment import TemplateAlignment, _rescaled_euclidean_mean from fmralign.tests.utils import random_niimg,...
e9514494702454b4ad94dad9d651cff0994f2eb30dddab8d3eab6b07f05affcc
Python
4,279
143
import functools from typing import Callable, Dict import numpy as np import pandas as pd from pandas.api import types as pdt from visions.backends.pandas.series_utils import series_handle_nulls from data_profiling.config import Settings from data_profiling.utils.versions import is_pandas_1 def is_nulla...
44502b0c92486d1d8123ae8627a01c21840fcc6a8ba3e3a49d5b48f253b7839b
Python
4,280
172
""" Script for tuning synfire chain parameters. original parameters and model from Yexin: V_rest = -70 V_reset = -70 threshold = -57 T_refract = 2 exp_TC = 0.904837 g_membrane = 29 I_offset = 0 V_rev_E = 0 V_rev_I = -75 exc_decay = 0.513417119 inh_decay = 0.367879441 exc_init = 0...
6829b9edc0336ca3feac59482a372b809574d6b689314d2aa96945585d5da459
Python
4,280
139
""" These are 'standard' batch correction methods to compare with. """ import scanpy as sc import scvelo as scv import numpy as np import scipy as scp import anndata as ad def compute_scvi(adata_raw, counts_key = 'counts_spliced', batch_key = 'batch', n_latent=20, gene_likelihood='nb', encode_covaria...
a347259e30775d799e7ce3638fd3676c3df0bdcdd03633528aa9bb443f7a2ff7
Python
4,280
86
# Copyright 2023 Kakao Brain and The HuggingFace Team. 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 requi...
39adc05743137474d783865bb15fba980c776e03f44762588414ecc2a9cc1d44
Python
4,282
148
import os import sys import pytest import ray from ray._private.test_utils import request_with_auth_token from ray.job_submission import JobSubmissionClient from ray.tests.conftest import * # noqa # For local testing on a Macbook, set `export TEST_ON_DARWIN=1`. TEST_ON_DARWIN = os.environ.get("TEST_ON_DARWIN", "0")...
fb3d0d207bc057f6c5463d405480c9ac4d8c769907eeecff838374392bca088c
Python
4,282
117
#!/usr/bin/env python3 """Plot the enrichment of covariates on graphs.""" import logging import numpy as np import pandas as pd # Plotting: from matplotlib import pyplot as plt import seaborn as sns from .utils_enrichment import calc_df_enrichment, format_enrichment_matrices def plot_df_enrichment(obj, graph_id, df...
4593fe267d9018e61892b77bfc97e39eae11d5ad7ed0542caa47e10478999d20
Python
4,283
123
""" Copyright (c) Meta Platforms, Inc. and affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. Script to generate gifs from traj Note: This is just a quick way to generate gifs and visualizations from traj, there are many parameters and ...
9264287572b71522e43e19237dec723349df175d841c0b157904deb7e134779a
Python
4,283
108
from typing import Optional, Sequence from mmeval.metrics import StructuralSimilarity as MMEVAL_SSIM from lqit.registry import METRICS @METRICS.register_module() class StructuralSimilarity(MMEVAL_SSIM): """Calculate SSIM (structural similarity). A wrapper of : class:`mmeval.SSIM`. Ref: Image quali...
c4c752d1d56d13daeb014015f86a63060ced512138a95dd68cd1796e39659f3c
Python
4,284
133
#!/usr/bin/env python # coding: utf-8 # In[5]: import numpy as np import tensorflow.keras as keras import os from tensorflow.keras.models import Sequential, Model from tensorflow.keras.layers import * from tensorflow.keras import backend as K import tensorflow as tf import pdb gpus = tf.config.experimental.list_phys...
bcdc028da7b24f16c37bc69f7b99bd59f677a6c85c28ba7079d81d7fd48dce49
Python
4,285
112
# -------------------------------------------------------- # SimMIM # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Zhenda Xie # -------------------------------------------------------- import os import torch.distributed as dist from torch.utils.data import DataLo...
40025f2f54ee7815f98d80aab133731c8a951a315d9306a605089904da067a50
Python
4,286
101
import numpy as np import matplotlib.pyplot as plt import string from itertools import cycle def label_axes(fig, labels=None, loc=None, **kwargs): """ Walks through axes and labels each. kwargs are collected and passed to `annotate` Parameters ---------- fig : Figure Figure object to...