sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
5e770737273f3f727e76882495e4087f1b49e589e8ce9e4fb863daa81703248f
Python
2,362
70
"""Module for handling bounding box coordinates Throughout the models and data formats used in exsclaim, bounding boxes are sometimes stored as x1,y1,x2,y2 or 'coords' and sometimes as [{"x": x1, "y": y1}, ...] or 'labelbox' In addition, we often want to check the relation of two bounding boxes and their properites (...
8d7dbf3b2a56c1f699e8d938da28b58fb8f21b3fc9627f1e66873fbfbc7a7a50
Python
2,369
62
import numpy as np class CropPadding: def __init__(self, load_size, training=True): """ Padding the image: C x H x W, if H or W less than load_size, and will keep the overflow side. """ # TODO: Not just support static filling of the padding, but also mirror, etc... if isin...
8e053af9f02f98929036cd16ebdf17c381cbb2e35736409513fa9783d836ff0c
Python
2,370
69
from fontTools.ttLib import TTFont from fontTools.ttLib.tables._c_m_a_p import CmapSubtable import argparse # Default PUAs SOURCE_PUA_START = 0xEA00 SOURCE_PUA_END = 0x100F2 TARGET_PUA_START = 0xF0000 def move_pua_glyphs(input_font_path, output_font_path): font = TTFont(input_font_path) cmap_table = font['cm...
a4d20544c50b738c42f698925de7eb3b8ddeec779a882b2bc7fa0cfb6a56f0eb
Python
2,371
52
import numpy as np from pytictoc import TicToc from skimage.transform import resize class Resize: def __init__(self, load_size, interp="bilinear", training=True): """ Resize the image: C x H x W to the C x load_size[0] x load_size[1] order will apply to image and mask separately. 0: neares...
6b92e008ec6af0724dead55d43a1c348532ce4280c696f17094fff071e864a1c
Python
2,373
83
import numpy as np import scipy.signal as signal import scipy.ndimage as ndimage def butter_highpass(signals, cutoff, fs, order=6, axis=-1): """ Forward-backward filter inpute signals with butterworth kernel Parameter: signals: singnal matrix (number of channels by frames) cutoff: cutoff freq...
0e10586cdb70d4cda71350be3bbfff82a47cd80371484d651f05ec380529ee51
Python
2,376
67
"""test_malloc.py This file is part of the test suite for keras2c Implements tests for dynamic memory allocation """ #!/usr/bin/env python3 import unittest import tensorflow.keras as keras from keras2c import keras2c_main import subprocess import time import os from test_core_layers import build_and_run import tensor...
ed434da0c6068e301aa934ec37a34320bfd62921ab0c08461917ae604a6e799b
Python
2,378
62
#!/usr/bin/env python """ Nipype workflow derived from preprocessing_synthseg.py, swapping the synthseg node by a datagrabber that get the precomputed synthseg parc """ import os from nipype.pipeline.engine import Node, Workflow from shivai.interfaces.datasource import Direct_File_Provider from shivai.workflows...
b457c07a62a4636f83aae2c514e1ad1b67d4d23f91bef5c0f9edc6a6e888f3a0
Python
2,380
90
import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.autograd import Variable from torch.nn.parameter import Parameter import math import utils import argparse import data_loader import rits_i from sklearn import metrics from ipdb import set_trace SEQ_LEN = 36 ...
83f8f0610fdb439572e3b387a60d7187891a0b35cdd507e48fefeb0ad94fc74e
Python
2,383
90
# -*- coding: utf-8 -*- """Logger, taken from Torch WC book""" __author__ = "Sean Benson" __copyright__ = "MIT" import logging.handlers import datetime import time import sys root_logger = logging.getLogger() root_logger.setLevel(logging.INFO) # Some libraries attempt to add their own root logger handlers. This is ...
9296dc11daba4f42c2b0506a290495d5968375330d07d9023123585d25b6c415
Python
2,389
64
""" dataset.py Provides PyTorch Dataset implementations for drug-target interaction data, integrating on-the-fly tokenization and pre-computed protein vector mapping. """ import torch from torch.utils.data import Dataset import pandas as pd import numpy as np from transformers import AutoTokenizer class DTIDataset(D...
06d69d4313f25f489e3aa3945cad0710583a2cafa6e35315eb72f07d6d56db33
Python
2,391
68
import sys import numpy as np import sklearn.linear_model as skl import pickle import argparse parser = argparse.ArgumentParser(description='Argument Parser') parser.add_argument("-sub", "--sub",help="Subject Number",default=1) args = parser.parse_args() sub=int(args.sub) assert sub in [1,2,5,7] train_path = 'data/pro...
a94373ff64b08dc69ea742867dcdb2ad059565668db24c8a5186d9cfd3e7babe
Python
2,392
91
import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.autograd import Variable from torch.nn.parameter import Parameter import math import utils import argparse import data_loader import rits from sklearn import metrics from ipdb import set_trace SEQ_LEN = 48 RNN...
b8526b1303ac7e36173744a69f64afe8221e6f9dc315aba0f0b21cd6162c42bb
Python
2,394
67
import pandas as pd import numpy as np from sklearn.feature_selection import ( mutual_info_classif, mutual_info_regression) def getLearningProb(rank: int, population_size: int, min_prob: float = 0.05, max_prob: float = 0.5) -> float: """ Calculate the learning probability (based on the Conprehensive Learn...
773d9feac34f1ec905989f125f479fd35f52e39ea28cd5204e9bb1493c1e48a1
Python
2,406
64
# Copyright (c) OpenMMLab. All rights reserved. import mmcv import torch from mmdet.models.dense_heads import FCOSHead def test_fcos_head_loss(): """Tests fcos head loss when truth is empty and non-empty.""" s = 256 img_metas = [{ 'img_shape': (s, s, 3), 'scale_factor': 1, 'pad_sh...
9fa8b52325a5351e9097f19625bc9cf86f8ded55eee4d03dd6b4c4bedbbad48d
Python
2,406
76
from math import * import random, time class MyOVBox(OVBox): def __init__(self): OVBox.__init__(self) self.nChannel = 0 self.sampling = 0 self.epochSampleCount = 0 self.startTime = 0 self.endTime = 0 self.dimensionSizes = list() self.dimensionLabels = list() self.timeBuffer = list() self.signalBuf...
e1ef24fe119be8755a32cf9b76bd71bf016df0380515e4ec13ae9eb4f233447a
Python
2,407
82
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Apr 7 12:36:35 2022 @author: baris """ import numpy as np import os import shelve def load_spikes(path, cell_type, trajectories, n_samples): if not os.path.exists(path+'.dir'): print(path) raise Exception('Path does not exist!') ...
508de4a7df81b0ce9164aef84ea93a2af58b48e3b1f8f209175036a18046889e
Python
2,409
66
import math import time import parmap import pickle import multiprocessing from imagen_post_hoc_helper import * import matplotlib.pyplot as plt import seaborn as sns num_cores = multiprocessing.cpu_count() print(f'Available CPU cores: {num_cores}') num_cores = math.floor(num_cores/3) print(f'Set CPU cores: {num_cores}...
b63fae46a3aa5722f504b4827803532d5b9ffa3d8c44e327a607c0e37898848a
Python
2,410
78
from __future__ import annotations import re from typing import ItemsView, KeysView, List, ValuesView from .consts import ALIAS2TARGET class Target: def __init__(self, target: str) -> None: r"""Convert target string in natural language into a dictionary""" self.tt = target self.target = ...
7fe82639ea02fe6d33e508c12c2b7696639eca9ea1c359a9b6afed4981a62a6f
Python
2,411
76
import numpy as np import cv2 class DenseSIFT(object): def __init__(self): self.sift = cv2.xfeatures2d.SIFT_create(nfeatures=1) def detectAndCompute(self, image, step_size=12, window_size=(10, 10)): # 12 10 if window_size is None: winH, winW = image.shape[:2] window_size = (winW // 4, winH // 4) if ima...
06df6a3c62655ec7936a8bdeee3d4581abbc02550944ad681fbb365a0e5d68f4
Python
2,412
76
""" Predict 32x21 mel-spectrogram features from SSS encoder embeddings and report cross-validated R2 per mel bin. """ #### ChatGPT was used to assist writing code. The authors reviewed, edited, and take full responsibility for the content. import os PODCAST_ROOT = os.environ.get("PODCAST_ROOT", "/engram/naplab/users/...
70688afef5e3d31c0417b3ec12d15a26d728836669aa8e9e1cb4f332335b9f3c
Python
2,412
77
from abc import ABC, abstractmethod from typing import TypeVar import eagerpy as ep from .devutils import flatten from .devutils import atleast_kd T = TypeVar("T") class Distance(ABC): @abstractmethod def __call__(self, reference: T, perturbed: T) -> T: ... @abstractmethod def clip_perturb...
ee949b7bc5a5011588bb67e5492d5930aad27fc4ea68385a4a280f71b72ecd6b
Python
2,415
78
# -*- coding: utf-8 -*- """ This file is part of the cerebellar-task-dependent repository (Xie et al. 2023) Copyright (C) 2023 Marjorie Xie and Ashok Litwin-Kumar See README for more information Library of functions for generating activity in the granule cell layer of the model and for learning the readout weights. ...
5c834fd0fea2b10a330521c8624a50a6e95ecd50a16ac74e987787f3a8cd5b65
Python
2,417
87
import copy import torch from daart.models import Segmenter from daart.models.temporalmlp import TemporalMLP def test_temporal_mlp(hparams, data_generator, check_batch): hp = copy.deepcopy(hparams) hp['backbone'] = 'temporal-mlp' hp['variational'] = False model = Segmenter(hp) model.to(hp['devi...
70514935248297235f378b2ee0f2ed7e627624155783a98bcb94a0e808ef6555
Python
2,417
67
import pandas as pd import os pd.set_option('display.max_columns', None) pd.set_option('display.max_rows', None) pd.set_option('display.width', 1000) # fn1 = r'V:\foodsec\Projects\SNYF\SIDv\TN\_SF_test\ObsAsSF\Tuning_data\TNWinter_STATS_cleaned90.csv' # fn2 = r'V:\foodsec\Projects\SNYF\SIDv\TN\_SF_test\NO_SF_baseline...
70c5fbe3c5c95f5c3a60c9ef40ed7182f07a86744236e05bca8d4931ac3d5053
Python
2,423
69
import pytest import matlab.engine import numpy as np import scipy from numpy.testing import assert_allclose from pystoi.utils import thirdoct, stft, remove_silent_frames from pystoi.stoi import FS, N_FRAME, NFFT, NUMBAND, MINFREQ, N, BETA, DYN_RANGE, OBM ATOL = 1e-5 eng = matlab.engine.start_matlab() eng.cd('matlab/...
29a9caf61b00ee8051a6e8404b7bdbfef283be33c0aad116fdb0593b5d53aebe
Python
2,428
71
import sys import numpy as np import sklearn.linear_model as skl import pickle import argparse parser = argparse.ArgumentParser(description='Argument Parser') parser.add_argument("-sub", "--sub",help="Subject Number",default=1) args = parser.parse_args() sub=int(args.sub) assert sub in [1,2,5,7] train_path = 'data/pro...
75e98066188eec443204e2292fe78c37fb6ec36415483277eb34a1d17c44cfaf
Python
2,428
67
# This file is part of sbi, a toolkit for simulation-based inference. sbi is licensed # under the Apache License Version 2.0, see <https://www.apache.org/licenses/> from typing import Callable, Dict, Union import numpy as np import torch import torch.distributions.transforms as torch_tf from torch import Tensor from...
8574d4a906049de56c9d0accfa9b9a64dc157e49fdc1a7b8fad04a53bcfc720e
Python
2,432
93
import xarray as xr import numpy as np import rasterio from rasterio.transform import from_bounds import os nc_file = r"V:\asap\asap_analysis\ERA5 from C3S\b96dade6843f6dd9d9a0fef09ecb5256.nc" output_tif = r"V:\asap\asap_analysis\ERA5 from C3S\2025_era5_dek18_fix_mm2.tif" outdir = r"V:\asap\asap_analysis\ERA5 from C3S...
7fc0b8bfeac3887d9455af6b523f1d4e177095ebc8c245d858db1531033a679e
Python
2,433
62
from ..builder import BBOX_CODERS from ..transforms import bbox2distance, distance2bbox from .base_bbox_coder import BaseBBoxCoder @BBOX_CODERS.register_module() class DistancePointBBoxCoder(BaseBBoxCoder): """Distance Point BBox coder. This coder encodes gt bboxes (x1, y1, x2, y2) into (top, bottom, left, ...
959bd7d8b4570a822ff2cce51b7a8ed1282fdfe45c11c38dcba80a7049cc2da0
Python
2,433
62
# import setuptools from setuptools import Extension, setup, find_packages from Cython.Build import cythonize import numpy from glob import glob VERSION_MAJOR = 0 VERSION_MINOR = 1 VERSION_MICRO = 6 with open("README.txt", "r") as fh: long_description = fh.read() # just build the module with a previously compil...
236f8c43ccb4f2187d7f8c641a2472d79b6a3134d649287473089f526714f8a6
Python
2,435
75
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Aug 31 10:16:37 2021 @author: baris """ from pydentate import net_tunedrev, neuron_tools from grid_model import grid_simulate import shelve import copy import time import numpy as np import scipy.stats as stats from pydentate_integrate import granule_s...
6b425763a170a0a68da93d2bc11fd207983755829636f104803608d986d9e959
Python
2,446
73
import argparse import logging import os from pathlib import Path import numpy as np import pandas as pd from tools.metrics import calculate_all_metrics os.makedirs('../logs', exist_ok=True) logging.basicConfig( format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%d.%m.%Y %I:%M:%S', filename='lo...
5cf1a376d2f9a5aa7181761809a3c0e5a78fbe267edbdb6e5acd96201fdc610b
Python
2,449
73
import jax import jax.numpy as jnp import weno_scheme import weno_roll import matplotlib.pyplot as plt import numpy as np import utils @jax.jit def euler_eqn(u, gamma): rho = u[...,0] rhv = u[...,1] ene = u[...,2] v = rhv/rho p = (gamma-1)*(ene - 0.5 * rhv * v) f1 = rhv f2 = rhv * v + p f3 = v ...
fbf2cbaec6169bedfe64211fa7912ca18624c16924db90e339f3efd81e253494
Python
2,449
79
from typing import Any import sys import pytest import foolbox as fbn from foolbox.zoo.model_loader import ModelLoader @pytest.fixture(autouse=True) def unload_foolbox_model_module() -> None: # reload foolbox_model from scratch for every run # to ensure atomic tests without side effects module_names = ["...
3f66212f617329d00681c131b70a7984b1c7e991625af6b43d813cd323e599bd
Python
2,450
82
import numpy as np from abc import ABCMeta, abstractmethod from typing import List from .particle import Particle class Callback(object): """ Abstract class used to identify callbacks""" __metaclass__ = ABCMeta def __init__(self, name: str): self._name = name @abstractmethod def evaluat...
876690a2a406cf5fc5c906af16c15bcd90be2f059d57612c94e7234ae37335d4
Python
2,454
55
import torch import torch.nn as nn from layers.Transformer_EncDec import Encoder, EncoderLayer from layers.SelfAttention_Family import ReformerLayer from layers.Embed import DataEmbedding class Model(nn.Module): """ Reformer with O(LlogL) complexity - It is notable that Reformer is not proposed for time s...
d465a8df0b0dd62cbd788e3795dd6db9cba54f6760ede3adfcd2b9e45545c29c
Python
2,454
66
# -*- coding: utf-8 -*- """ Created on Wed Jun 9 13:40:21 2021 @author: fhu14 """ #%% Imports, definitions from typing import List, Dict from DFTBLayer import DFTBList import os from .h5handler import per_molec_h5handler, per_batch_h5handler import pickle #%% Code behind def save_feed_h5(feeds: List[Dict], dftb_ls...
90dff0669e5ce64ddac80e89a01a51b8c4bd5206f47fa09ab7a619f677afef7e
Python
2,456
67
""" date: 20/12/2021 author: mathildelpx input: dataset with calcium activity of V2a in paralysed larvae, during MLR single shot stimulation. output: traces of each individually identified V2a in pontine and retropontine regions. """ import os import pandas as pd import matplotlib.pyplot as plt import numpy as np imp...
ab20ee9051c1d9f8d8fe40a4aa4f9d2fd60fa42735bbef92b543d7f6938f03ad
Python
2,456
70
from p4.p4exceptions import P4Error import p4.pf as pf import p4.func from p4.var import var class Part: def __del__(self, freePart=pf.freePart): self.alignment = None # print "Part.__del__() here. cPart=%s" % self.cPart if self.cPart: # print "Part.__del__() about to free ...
87bef5e0b87d69666582fe2718ba6e8f000e0ed91450606437b54fb5581608fd
Python
2,457
56
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: BSD-3-Clause # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source...
deff902ec36d495a32b84bea2d992ecc96a2131a933e57226b74c71861f0023e
Python
2,458
61
import numpy as np import random class ExpCentralCrop3d: """ Crop the 3D numpy [c, h, w, d] and mask [d, 2] in a sample The d should be randomly sampled """ def __init__(self, output_size, padding=0, include_lax_tensor=False, training=True): assert isinstance(output_size, (int, list, tupl...
2142d2144aca6f750c8f83cd0e2e7c84ff27edb1ceaddda54884fe665206a887
Python
2,459
71
#!/usr/bin/env python3 """ A simple example that demonstrates how to run a single attack against a PyTorch ResNet-18 model for different epsilons and how to then report the robust accuracy. """ import torchvision.models as models import eagerpy as ep from foolbox import PyTorchModel, accuracy, samples from foolbox.atta...
ef78edefdc6ea9ad66377a5e974b13bd43a29c097e1fa8267fd1aacb335cce02
Python
2,460
56
import logging from fedml_api.distributed.turboaggregate.message_define import MyMessage from fedml_core.distributed.client.client_manager import ClientManager from fedml_core.distributed.communication.message import Message class TA_DecentralizedWorkerManager(ClientManager): def __init__(self, args, comm, rank,...
36ca2a0c3b1cd7f846efe7714b863c9e8d3366653c7e08856009403453560642
Python
2,461
64
# Copyright (c) 2020, Jonas Rauber # # Licensed under the BSD 3-Clause License # # Last changed: # * 2020-07-15 # * 2020-01-08 # * 2019-04-18 import eagerpy as ep def l2_clipping_aware_rescaling(x, delta, eps: float, a: float = 0.0, b: float = 1.0): # type: ignore """Calculates eta such that norm(clip(x + eta *...
b83b273418d90d51569091a384fb4b6d75d592262c20945425c1bb57b058f96a
Python
2,461
59
import pandas as pd from tqdm import tqdm import numpy as np import rdkit from rdkit import Chem from rdkit.Chem import rdMolDescriptors from rdkit.Chem import Descriptors from rdkit.Chem import AllChem from rdkit import DataStructs #Fingerprint generation #(@ming if we want to use inchi as an input, inchi should be ...
9c253d3dad82b82b30802755c33ab3712e6f020ba20a6d09102761503bd24214
Python
2,463
85
import numpy as np import tensorflow as tf import tensorflow_datasets as tfds from tensorflow.keras.models import load_model from gradient_accumulator import GradientAccumulateModel # get current tf minor version tf_version = int(tf.version.VERSION.split(".")[1]) def normalize_img(image, label): """Normalizes i...
63828a85e3099153c6089574a943da6615fbdb5053ed0d2219c79baf698906f4
Python
2,466
56
import logging from fedml_api.distributed.decentralized_framework.message_define import MyMessage from fedml_core.distributed.client.client_manager import ClientManager from fedml_core.distributed.communication.message import Message class DecentralizedWorkerManager(ClientManager): def __init__(self, args, comm,...
3b07abffc74008480826b88ecec31a03fa2dbd801b42637df9d9cbfede16e03d
Python
2,471
82
"""Internal module for attacks that support logging to TensorBoard""" from typing import Union, Callable, TypeVar, Any, cast from typing_extensions import Literal import eagerpy as ep from functools import wraps FuncType = Callable[..., None] F = TypeVar("F", bound=FuncType) def maybenoop(f: F) -> F: @wraps(f) ...
a00b44c308b62489b8f406a5ad6dfed70eb683179b492efc7b02ef67bcd55561
Python
2,472
50
import re import numpy as np from sklearn.decomposition import PCA def getPCA(self, feature_names, X): # Perform PCA data reduction ON SELECTED FEATURES: Only on NDVI, RAD, Temp (precipitation is excluded) # Note: SF are escluded because the feature2PCA is taken from feature_groups # first: - no request of...
7a17bf6576e4307aa310e9f638cbaaa327087f3d363e4be755f85de5feb5b001
Python
2,474
96
from mmpose.apis import (inference_top_down_pose_model, init_pose_model, vis_pose_result, process_mmdet_results) import matplotlib.pyplot as plt import json import cv2 import numpy as np img_dir = "data/NECK/images/" index = 0 with open("data/NECK/val.json", "r", encoding="utf-8") as f: c...
2e0ac04782d721dcfd0e4119675a79ec3931ef79341e925fb3b6f5960c86f6fa
Python
2,479
80
# -*- coding: utf-8 -*- """ Base ===== This module contains the base extraction class author: Damian Wilary email: dmw51@cam.ac.uk """ from abc import abstractmethod import logging from typing import List log = logging.getLogger(__name__) class BaseExtractor: """Base for all extractor classes. All subclasses sho...
90d9f23d49deff636a985840c86c164fad3cd564a68967fe25a5fb97443d643b
Python
2,480
87
import os import struct import sys import numpy as np import getopt def read_data_from_file(file_name): f = open(file_name, "rb") line = f.readline() line = line.split() nparam = int(line[0]) rec_len = int(line[1]) nrec = int(line[2]) nlast = int(line[3]) print(nparam, rec_len, nrec, nl...
483a943b7cb607fc7acd847fec9532c32e871479206fdafe48f0162784cc54a3
Python
2,481
75
import numpy import numpy as np from tensorflow.keras import Sequential from tensorflow.keras.callbacks import Callback from tensorflow.keras.datasets import imdb from tensorflow.keras.layers import Dense, Dropout, Embedding, LSTM from tensorflow.keras.preprocessing import sequence from attention import Attention de...
b9fa0b5c78f729cadd08854565144f805884bad08bf6297aa1e5155b01710162
Python
2,483
70
# Copyright (c) OpenMMLab. All rights reserved. import warnings import torch from ..builder import DETECTORS from .single_stage import SingleStageDetector @DETECTORS.register_module() class DETR(SingleStageDetector): r"""Implementation of `DETR: End-to-End Object Detection with Transformers <https://arxiv.o...
f9f59ec1b91044a09fad1856615387c264609ffa8344b0ddc7f19cecfea9f455
Python
2,483
54
# This file is part of sbi, a toolkit for simulation-based inference. sbi is licensed # under the Apache License Version 2.0, see <https://www.apache.org/licenses/> import pytest import torch from torch.distributions import Normal from torch.special import log_ndtr from sbi.utils.vector_field_utils import UniformNorm...
5e5c344094c080b740f6e29bf9139071eb92b0f884d356c1f0c33ec7f49bc28b
Python
2,485
70
# -*- coding: utf-8 -*- """ Created on Thu Jul 8 16:26:50 2021 @author: fhu14 This is a dry run of the total machine learning model. The loss numbers should agree well with established benchmarks. This will be using the same settings as was used for the skf_8020_100knot run. """ #%% Imports, definitions import os ...
e2caee1772a01c23b952476e09d31ce8b3bcef431ec59e9939f480cae202b517
Python
2,492
74
# -*- coding: utf-8 -*- """ Recognise ======== This module contains optical chemical structure recognition tools and routines. author: Damian Wilary email: dmw51@cam.ac.uk Recognition is achieved using OSRA and performed via a pyOsra wrapper. """ import os import itertools import logging from PIL import Image impor...
13a698a3c2ca04f29186ec220c9bd0709397ee09b0ee1e274f9b06aa6bb81b5a
Python
2,495
63
import logging from data.manual_labels.data_reader import ManualLabels from data.updated_labels.data_reader import UpdatedLabels # from data.medical_notes.data_reader import ClinicalData import pandas as pd import numpy as np class Data(): def __init__(self, type, id, params): self.data_type = type ...
3f6b329b943daa248f09409262220f0cb4573d6a79189136d9402f1f24b09693
Python
2,500
76
import copy import warnings import numpy as np import torch import torch.nn as nn from torch_geometric.data import Data, Batch def clip_norm(vec, limit, p=2): norm = torch.norm(vec, dim=-1, p=2, keepdim=True) denom = torch.where(norm > limit, limit / norm, torch.ones_like(norm)) return vec * denom d...
5280960f9339950676dbb43094bb88898c91f31ebd191539c1d43e80a21fb292
Python
2,501
81
""" Cross-validated Pearson correlation between SSS embeddings and high-gamma ECoG activity """ #### ChatGPT was used to assist writing code. The authors reviewed, edited, and take full responsibility for the content. import os PODCAST_ROOT = os.environ.get("PODCAST_ROOT", "/engram/naplab/users/rs4613/Podcast") # se...
d0b924e8ea205938a35358ba427c700179a32e03b5f01bceb0c02cce8bb669c5
Python
2,501
79
from typing import Tuple import numpy as np import pandas as pd from scipy import interpolate def inter(preds_raw: np.ndarray, time: np.ndarray): bins = [0, 24, 48, 108] interp = interpolate.PchipInterpolator(bins, preds_raw, axis=1) return interp(time) def pred_reversions(ds) -> Tuple[np.ndarray, np.n...
4977b35e697ef4cac644d253437ea8d7fc96e2f7d99415a4018d0e52508892a6
Python
2,505
69
''' adapted from https://github.com/all-umass/ManifoldWarping ''' # Change: from .distance import SquaredL2 import numpy as np def neighbor_graph(X, metric=SquaredL2, k=None, epsilon=None, symmetrize=True): '''Construct an adj matrix from a matrix of points (one per row)''' assert (k is None) ^ (epsilon is N...
a27e7163b61e2daa9b3b8b6feb21414e33be01c5f0742cf33f2217eb80bf7dfc
Python
2,508
60
import numpy as np from skimage.transform import resize class Scale: def __init__(self, load_size: int, interp="bilinear", training=True): """ Scale the image: Input format: image: C x H x W mask: H x W The output size will be matched smaller edge of the image. If height >...
c77479ce944e4cf53e9f5517c6d27d2306b376bb4db90accbd344b2f5bccb7c8
Python
2,509
65
import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.ensemble import RandomForestClassifier from sklearn.feature_selection import SelectFromModel # Load data from CSV file # Create a new column after the first column in the generated features.csv file to provide the labels of your...
2e58f0f908b801339d7f2badf606c9f3ae297daaf518656912f9b1bacc926aba
Python
2,514
106
from multiprocessing import Process, Event import time import pygame from pygame.locals import * import math from random import randint, randrange import sys sys.argv = ['openvibe'] class OVProcess(Process): def __init__(self): Process.__init__(self) self.initialized = Event() self.stop_asked = Event() def i...
5215606b9d427dbd10d9e8031d2c5e2737ec092f4bd43555f6dea70a66110067
Python
2,514
93
from foolbox.zoo import fetch_weights from foolbox.zoo.common import home_directory_path, sha256_hash from foolbox.zoo.weights_fetcher import FOLDER import os import pytest import shutil import responses import io import zipfile @responses.activate def test_fetch_weights_unzipped() -> None: weights_uri = "http:...
c33f2df745783fc6a18a74b1920495dbee8c3935751e7af1a6d7d511b448d949
Python
2,515
114
import sys def sumf(arr): s = 0 for i in arr: s += i return s def meanf(arr): return sum(arr)/len(arr) def variancef(arr): sq = 0.0 m = meanf(arr) sumsq = 0 for item in arr: sumsq += item**2 return (sumsq/len(arr) - m*m) def stdevf(arr): return variancef(arr) ** 0.5 def msef(arr): result = 0 mean =...
ec49109343d31f8f22c5f797cc5f45ffd157cccbbc3cbb3a4705d661c0dcc320
Python
2,515
60
import argparse from fontTools.ttLib import TTFont import os def unicode_to_utf8_escape(codepoint): return ''.join([f'\\x{b:02x}' for b in chr(codepoint).encode('utf-8')]) def format_macro_name(prefix, glyph_name): # Convert names like 'repo-forked' -> 'ICON_VS_REPO_FORKED' return "ICON_" + prefix + "_" +...
ae5cf8f7349732716279a7c88cd925dcf258576791d167aa32b81aa9f990e707
Python
2,516
82
import math import numpy as np from scipy import signal import matplotlib.pyplot as plt from .constants import SI_SNR_POWER_THRESHOLD import librosa import mir_eval MIN_ERR = 1e-8 def si_sdr(estimated_signal, reference_signals, scaling=True): """ This is a scale invariant SDR. See https://arxiv.org/pdf/1811.0...
36380277ac09cc3291254bb013ec7fc1daa514c66c27f97d6687a1b08acd747b
Python
2,517
58
from copy import deepcopy import pandas as pd from data.data_access import Data from model.model_factory import get_model from model.torch_models.bert_cnn import CNN_Over_BERT from model.torch_models.bert_linear import Linear_Over_BERT from model.torch_models.bert_rnn import RNN_Over_BERT from transformers import Train...
cbd38873368c48e952072f9365a72885fc3201b18cff13908cb9f25baa3cc3dc
Python
2,520
74
from typing import Iterable, List import numpy as np from matplotlib import pyplot as plt from .tfspline import spline_linear_model, spline_vals # TODO: integrate tfspline.py class BSpline: def __init__(self, xknots: np.ndarray, bconds: Iterable, deg: int, maxder: int, coef: np.ndarray = None) ...
2ee06be99bc06c893ddaaaf514daf6b63479492eb9626d8c3ce45586da055d99
Python
2,522
75
# Simulate very hetero data # Below you specify the dataType, length, and relRate of each data # partition (and symbols, if it is standard dataType). There is one # part per alignment, in this example. You also specify the number of # taxa in the tree import random import math def randomNumbersThatSumTo1(length, m...
486233289e0e574a35de4afd967a7ee3e29bd5c065f36161642052e8b4f40b72
Python
2,523
77
# 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 ex...
b5ef218de55800f21c403dc5736f2a5c6219509f7f51b40c05f6deec93661cc6
Python
2,524
33
from bayes_design.protein_mpnn.training import main as run_training import argparse argparser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) argparser.add_argument("--path_for_training_data", type=str, default="my_path/pdb_2021aug02", help="path for loading training data") argpar...
65f483adbfb5109dea981dcb10ee3b6f50a6b1d7f1ecdaa87f526a467d2fd7da
Python
2,526
74
# training surv-based network without pretrained model # Modified: 5/21/2021 # Status: OK # Consider merge into 1 main file import torch.nn as nn import sys sys.path.insert(1, '../plot/') from plot import report_table,roc_plot_perfrom_table from networks import CNN_Surv_Wrapper from utils import read_json, cross_set i...
5ac537f7b227034e9f9e8dbe42a562cc5bd99f936781998e9a4d732d8cd25a45
Python
2,528
75
import pytest import torch from mmdet.core.post_processing import mask_matrix_nms def _create_mask(N, h, w): masks = torch.rand((N, h, w)) > 0.5 labels = torch.rand(N) scores = torch.rand(N) return masks, labels, scores def test_nms_input_errors(): with pytest.raises(AssertionError): ma...
830f72aacb369ac75342004d89948b2c7128f0982caf73dccdd83e71bec0175a
Python
2,530
61
import numpy as np class RandomCrop3d: """ Crop the 3D numpy [c, h, w, d] and mask [h, w, d] in a sample """ def __init__(self, output_size, padding=0, training=True): assert isinstance(output_size, (int, list, tuple)) if isinstance(output_size, int): self.output_size = (o...
c4a5d20beedb3872de18f713647c38aa49c9322303c700076cd064549b981eb2
Python
2,530
96
# This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be usef...
3a5a08bf7b7cfcdf57e40170b71b5864434f4bc9732310b1a03a332f29f2ce76
Python
2,534
67
import logging from abc import abstractmethod from mpi4py import MPI from ..communication.message import Message from ..communication.mpi.com_manager import MpiCommunicationManager from ..communication.mqtt.mqtt_comm_manager import MqttCommManager from ..communication.observer import Observer class ClientManager(Ob...
8c8fa386220e1ce56d2cd25707c8745cfae2f2efe73f4f04c51c5d1e00139be5
Python
2,534
73
import pytest from binn import BINNExplainer, BINN, Network import torch import pandas as pd @pytest.fixture def binn_explainer(): input_data = pd.DataFrame({"Protein": ["a", "b", "c"]}) pathways = pd.DataFrame( {"source": ["A", "B", "C"], "target": ["path1", "path1", "path2"]} ) translation =...
80be0878b25374069c0d82b2229f3620cf519da4c59247e4a509f8f2dc6f59ea
Python
2,538
77
import torch import torch.nn as nn import torchvision.models as models import torchvision.transforms as transforms from torch.autograd import Variable from PIL import Image # import numpy as np import torch.nn.functional as F class ResnetSimilarity(): def __init__(self): self.train_on_gpu = torch.cuda.is...
842fa2d0eba56ff63aede6e516dcd4c21821885490297cb83e1e824b96bf1c76
Python
2,538
72
import tensorflow as tf # implementation from: https://github.com/sayakpaul/Adaptive-Gradient-Clipping/blob/main/agc.py def compute_norm(x, axis, keepdims): """ Computes the euclidean norm of a tensor :math:`x`. Args: x: input tensor. axis: which axis to compute norm across. keepd...
cdd9316a66a8086e64a654c4b7cec39bf6cb37f675400f45c01e456439c1641b
Python
2,540
99
import torch.nn as nn import torch.nn.functional as F import torch import numpy as np J = 10 NB_EPOCH = 1000 BATCH_SIZE = 128 DROPOUT_RATIO = 0.5 # F(t) = 1 - exp(-(t-g)^m/s) def weibull_cdf(parameters: torch.Tensor): m = parameters[:, 0] s = torch.clamp(parameters[:, 1], min=0.001) output_list = [] ...
3725f9b8b0a5fca22bfa3610601389da4bb4dd360a607d9da3707fe8711d7791
Python
2,541
81
from typing import Optional, Tuple import torch as pt from NNPOps.CFConv import CFConv from NNPOps.CFConvNeighbors import CFConvNeighbors from .models.model import TorchMD_Net from .models.torchmd_gn import TorchMD_GN class TorchMD_GN_optimized(pt.nn.Module): def __init__(self, model): if model.rbf_type...
8f30ba4ad9554a0bade2a684d0c554d7ff3d3f59163fae815aa181489f25589e
Python
2,542
58
#!/usr/bin/env python """ Nipype workflow derived from preprocessing_synthseg.py, swapping the synthseg node by a datagrabber that get the precomputed synthseg parc """ import os from nipype.pipeline.engine import Node, Workflow from nipype.interfaces.io import DataGrabber from shivai.workflows.preprocessing_s...
0f27f496cab23383fcf0d359a8ad2c5b0fca7263fd1f21ae53ca25777ecbd3ab
Python
2,543
77
# Copyright (c) OpenMMLab. All rights reserved. import warnings from mmcv import Config from ...builder import DATASETS from .topdown_coco_dataset import TopDownCocoDataset @DATASETS.register_module() class TopDownHalpeDataset(TopDownCocoDataset): """HalpeDataset for top-down pose estimation. 'https://gith...
dae5fe164198d045d2e804e15f8b0b4115711c109053a2da5fcf201ef23e23b2
Python
2,543
92
# Copyright Universitat Pompeu Fabra 2020-2023 https://www.compscience.org # Distributed under the MIT License. # (See accompanying file README.md file or copy at http://opensource.org/licenses/MIT) # Configuration file for the Sphinx documentation builder. # -- Project information project = "TorchMD-Net" author = "...
56bd4b1511495e7b857a426fdf9de840a7a2f166ca13fc2112091a0677c56013
Python
2,545
72
# Copyright (c) OpenMMLab. All rights reserved. import torch def images_to_levels(target, num_levels): """Convert targets by image to targets by feature level. [target_img0, target_img1] -> [target_level0, target_level1, ...] """ target = torch.stack(target, 0) level_targets = [] start = 0 ...
056f45ad80cbe210d97f6c27b13069795eeebff3e4600ec7af4d7c04061ea9d5
Python
2,548
70
# Copyright (c) OpenMMLab. All rights reserved. import mmcv import torch from mmdet.models.dense_heads import AnchorHead def test_anchor_head_loss(): """Tests anchor head loss when truth is empty and non-empty.""" s = 256 img_metas = [{ 'img_shape': (s, s, 3), 'scale_factor': 1, '...
e97687c9f4d6c8dda6133c889a7b2b607a18b779cd2e4c0a59351d7563478140
Python
2,554
89
import numpy as np import collections import os DEFAULT_WORD_COUNT_FILE = 'stackoverflow.word_count' word_count_file_path = None word_dict = None word_list = None _pad = '<pad>' _bos = '<bos>' _eos = '<eos>' ''' This code follows the steps of preprocessing in tff stackoverflow dataset: https://github.com/google-resea...
8f9bcb8dd0d8116d3478d1940514a65dfbf45bb1b589c97cc34ba5967ef99698
Python
2,558
85
import pandas as pd import pytest import networkx as nx from binn import ImportanceNetwork @pytest.fixture def importance_df(): df = pd.DataFrame( { "source name": ["A", "B", "C", "D", "E", "F"], "source": [1, 2, 3, 4, 5, 6], "target": [4, 5, 6, 0, 0, 0], "v...
f2a5b6a29877231a6b9e1807bf5b6d91691c92ce57ce55588085cbed2777a7d8
Python
2,559
60
import numpy as np import tensorflow as tf tf.config.set_visible_devices([], device_type='GPU') import os from utils import load_json os.environ['XLA_PYTHON_CLIENT_PREALLOCATE'] = 'false' def split_equation(equation, lead_n=4): '''equation is a string, e.g. 'ode_auto_linear1_forward_0.806_0.047''' # Split th...
d3ecb54f9585527ae203da037300f932a211c9532b4441f07687b459bcaa0b73
Python
2,560
71
# Copyright (c) OpenMMLab. All rights reserved. import base64 import os import mmcv import torch from ts.torch_handler.base_handler import BaseHandler from mmdet.apis import inference_detector, init_detector class MMdetHandler(BaseHandler): threshold = 0.5 def initialize(self, context): properties ...
03592a5b8aa6ddbe36a64d41fc70cf9eb94324ab57b2bc095e95a2444e01dc69
Python
2,561
63
# Copyright (c) OpenMMLab. All rights reserved. import mmcv import torch from mmdet.models.dense_heads import VFNetHead def test_vfnet_head_loss(): """Tests vfnet head loss when truth is empty and non-empty.""" s = 256 img_metas = [{ 'img_shape': (s, s, 3), 'scale_factor': 1, 'pad...
3522d526bc8ad64a70d1aefc14a8a6ec0101f99c755bfcf47a4c9cb2cd003156
Python
2,561
42
def fill_caption_number(caption_template, identifier, params, format_str = '{:.3g}'): if "ode_auto_const" in identifier: caption = caption_template.replace('[0.001]', format_str.format(params[0])) \ .replace('[0.002]', format_str.format(params[1])) elif "ode_auto_linear1" in ident...
9cf0cfba52db37ff4dfb933c7a6a15fd8c4c7e7f38ff0b4f2b1152359597d343
Python
2,573
54
from data.manual_labels.data_reader import ManualLabels # data = ManualLabels(outcome = 'any_cancer', text='IMPRESS') data =[{'id':'any_cancer_IMPRESS','type': 'manual_label' , 'params': {'outcome': 'any_cancer', 'text': 'NARR+IMPRESS', 'training_split':9}}] # data = ManualLabels(outcome = 'any_cancer') data = Manual...
f365f8d83b222ff626f6185fe1cbc0133103f060656f2f01f182ba2f56e68245
Python
2,573
103
''' Author: ---- Date: 2022-06-30 11:56:44 LastEditors: GhMa LastEditTime: 2022-09-20 14:35:33 ''' import torch import torch.nn as nn import torch.distributions as distrib import numpy as np import math def heaviside(x: torch.Tensor): return (x >= 0.0).to(x) class StochasticST(torch.autograd.Function): ...
5f77649d5c501b1e59d6045440f3ca3432a7b2c19fd4f7d3a781df3ef8489074
Python
2,574
100
import os import shutil import numpy as np import torch from torch.autograd import Variable class AvgrageMeter(object): def __init__(self): self.reset() def reset(self): self.avg = 0 self.sum = 0 self.cnt = 0 def update(self, val, n=1): self.sum += val * n ...
5774e0c625508ea6f846e2be9b17c4f97a9f1e3cc8eccdfd5abb10fe318a7c24
Python
2,577
87
# ref: https://github.com/cprogrammer1994/ModernGL/blob/master/examples/julia_fractal.py import moderngl import numpy as np class SquareProgram: def __init__(self, screen): # save settings self.screen = screen # initialize settings self.color = 1.0 self.toggle = True ...
16c19af20cf8eda1172965c7e48a2da0a239355458fc92a50905b8d9e12292fb
Python
2,578
83
import numpy as np from .methods import intersect class LinearWall: def __init__(self, name, bias, slope, t=[0, 1]): """ line-segment: u+tv """ self.name = name self.bias = bias self.slope = slope self.t = t self.intersects = {} @property ...