prompt stringlengths 15 655k | completion stringlengths 3 32.4k | api stringlengths 8 52 |
|---|---|---|
##################################################################
# Radio Map Construction with Regression Kriging
# Written by <NAME>, Ph.D.
# Requirements:
# - Python 3.x
# - numpy
# - scipy
# - matplotlib
##################################################################
# The MIT License (MIT)
#
# Copyright (c) 2... | np.abs(sill) | numpy.abs |
import collections
import numpy as np
import time
import datetime
import os
import networkx as nx
import pytz
import cloudvolume
import pandas as pd
from multiwrapper import multiprocessing_utils as mu
from . import mincut
from google.api_core.retry import Retry, if_exception_type
from google.api_core.exceptions impo... | np.array(new_parent_id) | numpy.array |
from os.path import join
import pickle
from csbdeep.models import Config, CARE
import numpy as np
import json
from scipy import ndimage
from numba import jit
@jit
def pixel_sharing_bipartite(lab1, lab2):
assert lab1.shape == lab2.shape
psg = np.zeros((lab1.max()+1, lab2.max()+1), dtype=np.int)
for i in... | np.std(X_train) | numpy.std |
# Copyright (c) 2018 <NAME>
import numpy as np
from numba import njit, prange
from skimage import measure
try:
import pycuda.driver as cuda
import pycuda.autoinit
from pycuda.compiler import SourceModule
FUSION_GPU_MODE = 1
except Exception as err:
print('Warning: {}'.format(err))
print('Failed to import... | np.prod(self._vol_dim) | numpy.prod |
# coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# 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 applicab... | np.arange(2) | numpy.arange |
from cemc.mcmc import NetworkObserver
import h5py as h5
import numpy as np
from ase.visualize import view
from scipy.stats import linregress
import os
from ase.units import kB
class Mode(object):
bring_system_into_window = 0
sample_in_window = 1
equillibriate = 2
transition_path_sampling = 3
class N... | np.log(hist) | numpy.log |
# pylint:disable=no-name-in-module, import-error
import aiofiles
import time
from fastapi import APIRouter, File, UploadFile, Response, status, Depends
import app.api.utils_com as utils_com
from app.api import classes
from app import crud, fileserver_requests
from app.api.dependencies import get_db
from app.api import ... | np.array(img_zarr) | numpy.array |
import numpy as np
from numpy.matlib import repmat
import cv2
from scipy.ndimage import map_coordinates
from lib.utils import cos_window,gaussian2d_rolled_labels
from lib.fft_tools import fft2,ifft2
from cftracker.base import BaseCF
from cftracker.feature import extract_hog_feature,extract_cn_feature,extract_cn_... | np.arange(n2) | numpy.arange |
# --------------------------------------------------------
# Licensed under The MIT License [see LICENSE for details]
# --------------------------------------------------------
import numpy as np
import scipy.io as sio
import os
from numpy.linalg import inv
import torch
import cv2
import argparse
import IPython
imp... | np.sin(rotx) | numpy.sin |
#!/usr/bin/env python
#
# Author: <NAME> <<EMAIL>>
#
import time
import ctypes
import tempfile
import numpy
import h5py
from pyscf import lib
from pyscf.lib import logger
from pyscf import ao2mo
from pyscf.cc import ccsd
from pyscf.cc import _ccsd
#
# JCP, 95, 2623
# JCP, 95, 2639
#
def gamma1_intermediates(mycc, t1... | numpy.einsum('ij,ij', doo, fock0[:nocc,:nocc]) | numpy.einsum |
import numpy as np
from classes.model import Model
# An object with a set of methods to generate and train multiple models and compare clusters
# Uses monte carlo like methods to approximately explore the optima of the marginal distributions of observed variables given the latent variable
# Generate a given number of ... | np.arange(self.N) | numpy.arange |
"""
MIT License
Copyright (c) 2020 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distri... | np.concatenate((self.match_table[c], match_table), axis=0) | numpy.concatenate |
import numpy as np
import pytest
from simba.utils.linalg import cosine, compute_pc, normalise_rows
@pytest.mark.parametrize(
'x, y, expected',
[
([1, 2, 3], [2, 4, 6], 1),
([1, 1, 1, 1], [-1, -1, -1, -1], -1),
([1, 1], [1, -1], 0),
([1, 1], [1, 0], np.cos(np.pi / 4)),
]
)
... | np.random.random((4, 5)) | numpy.random.random |
# Utilities supporting gaze calibration
import numpy as np
import cv2
import pandas as pd
import os
def onoff_from_binary(data, return_duration=True):
"""Converts a binary variable data into onsets, offsets, and optionally durations
This may yield unexpected behavior if the first value of `data` is true.
... | np.nonzero(ddata > 0) | numpy.nonzero |
import numpy as np
import math
from scipy.special import gamma
import scipy
import scipy.ndimage
def paired_product(new_im):
shift1 = np.roll(new_im.copy(), 1, axis=1)
shift2 = np.roll(new_im.copy(), 1, axis=0)
shift3 = np.roll(np.roll(new_im.copy(), 1, axis=0), 1, axis=1)
shift4 = np.roll(np.roll(new... | np.zeros((h, w), dtype=np.float32) | numpy.zeros |
# 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... | np.hstack((height, width, im_scale)) | numpy.hstack |
import numpy as np
import config
class Trajectory:
def __init__(self, q_f, delay=0):
self.delay = delay
k_v = config.k_v
k_a = config.k_a
self.k_v = np.array(k_v)
self.k_a = np.array(k_a)
self.q_f = np.array(q_f)
self.num_joints = len(q_f)
self.d... | np.where(travel_time == max_travel_time) | numpy.where |
import unittest
import numpy as np
import cspyce.typemap_samples as ts
def flatten(array):
return tuple(tuple(array.ravel()))
# noinspection PyTypeChecker
class test_array1_1(unittest.TestCase):
# %apply (int IN_ARRAY1[ANY]) {int arg[3]}
# cs.in_array1_1 just returns whatever 3 integers it was passed a... | np.arange(100., 200.) | numpy.arange |
#!/usr/bin/env python
# Analysis/plotting functions for HDX analysis
import Functions, Methods
import numpy as np
import matplotlib.pyplot as plt
import os, glob, copy, itertools, pickle
from scipy.stats import pearsonr as correl
from scipy.stats import sem as stderr
from matplotlib.backends.backend_pdf import PdfPag... | np.zeros(self.resfracs.shape) | numpy.zeros |
import numpy as np, matplotlib.pyplot as plt
from matplotlib.cm import rainbow
from matplotlib.cm import YlGn as cmap_gradient
from matplotlib import colors, cm
#from PreFRBLE.convenience import *
from PreFRBLE.label import *
from PreFRBLE.likelihood import *
#from PreFRBLE.physics import *
#from PreFRBLE.parameter im... | np.log10(b) | numpy.log10 |
import pygame
import numpy as np
import colorsys
from PyEvolv.assets.font import FONT, get_font
from typing import Dict, List, Tuple
def display_creature(f):
def inner(self, gameDisplay: pygame.Surface, creatures: List) -> None:
pixels_per_relative = self.display_height / self.relatives_on_screen
... | np.radians(sensor_2[1]) | numpy.radians |
# from tqdm.notebook import tqdm as tqdm_notebook
# import os
# import glob
import pickle
import numpy as np
from src.support_class import *
from matplotlib import pyplot as plt
from matplotlib import colors as mcolors
from scipy import linalg
from codeStore import support_fun as spf
colors11 = plt.get_cmap('Blues')
c... | np.array((0, 0, 1)) | numpy.array |
from utils.speech_featurizers import SpeechFeaturizer
from utils.text_featurizers import TextFeaturizer
import pypinyin
import numpy as np
from augmentations.augments import Augmentation
import random
import tensorflow as tf
import os
class AM_DataLoader():
def __init__(self, config_dict,training=True):
... | np.array(speech_features, 'float32') | numpy.array |
import sys
import os
import pickle
import numpy as np
from metrics_ddie import ddie_compute_metrics
from scipy.special import softmax
from transformers import BertTokenizer
_, cv_dir, k = sys.argv
k = int(k)
tokenizer = BertTokenizer.from_pretrained('/mnt/model/scibert_scivocab_uncased', do_lower_case=True)
paths ... | np.argmax(preds, axis=1) | numpy.argmax |
# pylint: disable=R0201
import platform
from unittest.mock import MagicMock
import numpy as np
import pytest
from napari.utils.colormaps import make_colorbar
from qtpy import PYQT5
from qtpy.QtCore import QPoint, Qt
from qtpy.QtGui import QImage
import PartSegData
from PartSeg.common_backend.base_settings import Bas... | np.any(image2 != 255) | numpy.any |
import numpy as np
import os
import parmap
import scipy
def remove_duplicates(fname_templates, fname_weights,
save_dir, CONFIG, units_in=None, units_to_process=None,
multi_processing=False, n_processors=1):
# output folder
if not os.path.exists(save_dir):
os... | np.abs(min_val[units_in_dont_process] - min_val[[j]]) | numpy.abs |
import numpy as np
import copy as cp
from scipy.linalg import expm
from . import cmanif
class ManifoldPointArray:
def __init__(self, manifold):
self._manifold = cp.deepcopy(manifold)
self._coords = np.array([])
def __str__(self):
return "Array of {num} points of the manifold: ".format... | np.matmul(m_v,expm1_step) | numpy.matmul |
import itertools
import unittest
from copy import copy
import numpy as np
import pytest
from coremltools._deps import _HAS_KERAS2_TF, _HAS_KERAS_TF
from coremltools.models.utils import _macos_version, _is_macos
np.random.seed(1377)
if _HAS_KERAS2_TF or _HAS_KERAS_TF:
import keras
from keras.models import Se... | np.dot(W_o_back, x) | numpy.dot |
# coding: utf-8
import sys, os
sys.path.append(os.pardir) # 부모 디렉터리의 파일을 가져올 수 있도록 설정
import numpy as np
from common.functions import softmax, cross_entropy_error
from common.gradient import numerical_gradient
# np.random.seed(1)
class simpleNet:
def __init__(self):
self.W = np.random.randn(2,3) # 정규분포로... | np.dot(x, self.W) | numpy.dot |
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
from threading import Lock
import numpy as np
import sys
import array
import math
import ctypes
import pyzed.sl as sl
VERTEX_SHADER = """
# version 330 core
layout(location = 0) in vec3 in_Vertex;
layout(location = 1) in vec4 in_Color;
unifor... | np.array(_pts[quad[0]]) | numpy.array |
'''
Walker-v2 solution by <NAME>
**Experimentatl**
https://github.com/FitMachineLearning/FitML/
https://www.youtube.com/channel/UCi7_WxajoowBl4_9P0DhzzA/featured
Using DeepQ Learning
'''
import numpy as np
import keras
import gym
import os
import h5py
from keras.models import Sequential
from keras.layers import Dense... | np.random.rand(1) | numpy.random.rand |
import numpy as np
import matplotlib.pyplot as plt
from scipy import ndimage
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.image as mplimg
from matplotlib.colors import LogNorm
from numpy import fft
def get_photon_positions(image, cdf, cdf_indexes, nphot=1):
"""
Uses an inverse CDF lookup to find ... | np.arange(fft_truth.size, dtype=int) | numpy.arange |
#!/usr/bin/env python3
import os.path
import numpy as np
import numpy.linalg as la
import scipy.io as sio
import matplotlib.pyplot as plt
from neml import models, elasticity, parse
import sys
sys.path.append('../../..')
from srlife import receiver, structural
class TestCase:
def __init__(self, name, T, analytic,... | np.round(c2, decimals=dec) | numpy.round |
from sqlalchemy import true
import FinsterTab.W2020.DataForecast
import datetime as dt
from FinsterTab.W2020.dbEngine import DBEngine
import pandas as pd
import sqlalchemy as sal
import numpy
from datetime import datetime, timedelta, date
import pandas_datareader.data as dr
def get_past_data(self):
"""
Get raw... | numpy.arange(-3.7, 3.6, .25) | numpy.arange |
# In order to manipulate the array
import numpy as np
# In order to load mat file
from scipy.io import loadmat
# In order to import the libsvm format dataset
from sklearn.datasets import load_svmlight_file
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import Imputer
from sklearn.preprocess... | np.savez('../../data/clean/uci-isolet.npz', data=data, label=label) | numpy.savez |
import copy as cp
import numpy as np
from scipy.linalg import pinv, eigh
from sklearn.base import TransformerMixin
from mne import EvokedArray
def shrink(cov, alpha):
n = len(cov)
shrink_cov = (1 - alpha) * cov + alpha * np.trace(cov) * np.eye(n) / n
return shrink_cov
def fstd(y):
y = y.astype(np.f... | np.abs(eigvals) | numpy.abs |
"""
Library of simple image processing effects that can be applied to source
images or video
"""
from __future__ import print_function
from __future__ import division
import cv2
import numpy as np
from vidviz.utils import SmoothNoise
class Effect(object):
"""Base class for vid-viz effects"""
def __init__... | np.zeros((3, 2)) | numpy.zeros |
import sys
import open3d as o3d
from model import *
from utils import *
import argparse
import random
import numpy as np
import torch
import os
import visdom
sys.path.append("./emd/")
import emd_module as emd
parser = argparse.ArgumentParser()
parser.add_argument('--model', type=str, default = './trained_model/network... | np.array(pcd.points) | numpy.array |
"""
Classes holding information on global DOFs and mapping of all DOFs -
equations (active DOFs).
Helper functions for the equation mapping.
"""
import numpy as nm
import scipy.sparse as sp
from sfepy.base.base import assert_, Struct, basestr
from sfepy.discrete.functions import Function
from sfepy.discrete.condition... | nm.where(master_slave[meq] != 0) | numpy.where |
# -*- coding: utf-8 -*-
########################################################
### estimate mutual information (dependency) between ###
### feature vectors with different search radius for ###
### local feature estimation and target ###
########################################################
import nu... | np.loadtxt(read_file) | numpy.loadtxt |
# general libraries
import warnings
import numpy as np
# image processing libraries
from scipy import ndimage, interpolate, fft, signal
from scipy.optimize import fsolve
from skimage.feature import match_template
from skimage.transform import radon
from skimage.measure import ransac
from sklearn.cluster import KMeans
... | np.arange(-1,+2) | numpy.arange |
import math
import os
import time
import xml.etree.ElementTree as ET
from xml.dom import minidom
import multiprocessing as mp
import cv2
import matplotlib.pyplot as plt
import numpy as np
import openslide
from PIL import Image
import pdb
import h5py
import math
from wsi_core.wsi_utils import savePatchIter_bag_hdf5, ini... | np.flatnonzero(hierarchy[:, 1] == cont_idx) | numpy.flatnonzero |
import json
import os
import pickle
from os import listdir
from os.path import isfile, join
import fire
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import numpy as np
from skimage import feature
# data_list = [
# "/Users/sschickler/Code_Devel/LSSC-python/plotting_functions/demo_files/roi_lis... | np.percentile(background_image_temp, percent) | numpy.percentile |
try:
from vrep import*
except:
print ('--------------------------------------------------------------')
print ('"vrep.py" could not be imported. This means very probably that')
print ('either "vrep.py" or the remoteApi library could not be found.')
print ('Make sure both are in the same folder as t... | np.min(obj_x_array) | numpy.min |
import numpy as np
import pandas as pa
import requests, sys
import json
from Bio.Seq import Seq
import os
class TF3DScan:
def __init__(self,genes,PWM_directory,seqs=None):
self.gene_names=genes
self.PWM_dir=PWM_directory
self.seq=None
self.PWM=None
self.weights=None
... | np.argsort(motif_score) | numpy.argsort |
# Copyright (c) 2020 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute... | np.amax(x_matrix[:, j]) | numpy.amax |
import os
import unittest
import time
from datetime import datetime
try:
import torch
GPU = torch.cuda.is_available() and not os.environ.get("USE_CPU")
TORCH_INSTALLED = True
except ModuleNotFoundError:
GPU = False
TORCH_INSTALLED = False
class TestModule(unittest.TestCase):
def test_hbb(self... | np.array([0.0, 0.0, 15.33884298, 15.33884298]) | numpy.array |
from collections import defaultdict
import copy
import numpy as np
ACTIVE = 1
INACTIVE = 0
def day17a(input_path):
num_cycles = 6
dimension = Dimension(input_path, 3)
print(dimension.total)
for step in range(num_cycles):
dimension.step()
return dimension.total
def test17a():
asser... | np.array(current_keys) | numpy.array |
'''
-------------------------
SETUP THE MODEL
-------------------------
A) Environmental parameters
B) True wind angle and velocity range
C) Initial guess for solving the VPP
D) Delft coefficients for resistance estimation
E) Derivated elementary dimensions
-------------------------
VPP MAIN ROUTINE
-----------------... | np.cos(angle_sail) | numpy.cos |
#Author: <NAME>
import numpy as np
import matplotlib.pyplot as plt
#perform experiments
def main():
training_data = read_training_data("train-images-idx3-ubyte")
training_data = np.divide(training_data, 255)
training_label = read_training_label("train-labels-idx1-ubyte")
test_data = read_test_data("t10k... | np.random.permutation(training_data.shape[0]) | numpy.random.permutation |
import unittest
import numpy as np
from io import BytesIO
import h5py
from exetera.core import session
from exetera.core import fields
from exetera.core import persistence as per
from exetera.core import operations as ops
from exetera.core import utils
class TestOpsUtils(unittest.TestCase):
def test_chunks(se... | np.asarray([1, 1, 2, 3, 5, 5, 6, 7, 8, 8, 8], dtype=np.int64) | numpy.asarray |
'''
measure/prepare.py
TODO:
- data fitting
- data evaluation/interpolation
'''
import os
import sys
import time
import numpy as np
import scipy.linalg as linalg
import matplotlib.pyplot as plt
def weighted_average_filter(a, w, count=1,
overwrite_a=False, overwrite_w=False):
'''Weighted mean filter al... | np.asarray(uk, float) | numpy.asarray |
# ----------------------------------------------------------------------------
# - Open3D: www.open3d.org -
# ----------------------------------------------------------------------------
# The MIT License (MIT)
#
# Copyright (c) 2018-2021 www.open3d.org
#
# Permission i... | np.testing.assert_allclose(s, s_numpy, 1e-6) | numpy.testing.assert_allclose |
"""ResNet50 model for Keras.
Adapted from tf.keras.applications.resnet50.ResNet50().
This is ResNet model version 1.5.
Related papers/blogs:
- https://arxiv.org/abs/1512.03385
- https://arxiv.org/pdf/1603.05027v2.pdf
- http://torch.ch/blog/2016/02/04/resnets.html
"""
from __future__ import absolute_import
from __future... | np.array([128, 128, 512]) | numpy.array |
import numpy as np
import PIL, PIL.Image
import math
def imbounds(width, height, transform):
# calc output bounds based on transforming source image pixel edges and diagonal distance, ala GDAL
# TODO: alternatively based on internal grid or just all the pixels
# see https://github.com/OSGeo/gdal/blob/60d... | np.meshgrid(cols, rows) | numpy.meshgrid |
import cv2,torch
import numpy as np
from PIL import Image
import torchvision.transforms as T
import torch.nn.functional as F
import scipy.signal
mse2psnr = lambda x : -10. * torch.log(x) / torch.log(torch.Tensor([10.]))
def visualize_depth_numpy(depth, minmax=None, cmap=cv2.COLORMAP_JET):
"""
depth: (H, W)
... | np.min(x[x>0]) | numpy.min |
import numpy as np
from math import *
from pylab import *
from matplotlib import pyplot as plt
mRatio = 2.0 #0.223/0.203 #Mass ratio M_1/M_2 = M_1 (because M_2 = 1)
L=4.5 # Distance between nuclei times number of nuclei (for lattice constant a=1)
#xMass = range(1,int(L))
xMass... | np.sin(k*xMass[g+1]) | numpy.sin |
#<NAME>
#(cc) <EMAIL>
import numpy as np
import pandas as pd
# standard parameters after Carsel & Parrish 1988
carsel=pd.DataFrame(
[[ 'C', 30., 15., 55., 0.068, 0.38, 0.008*100., 1.09, 0.200/360000.],
[ 'CL', 37., 30., 33., 0.095, 0.41, 0.019*100., 1.31, 0.258/360000.],
[ 'L', 40., 40.... | np.abs(psi) | numpy.abs |
import numpy as np
import pandas as pd
import h5py
from numpy.lib.arraysetops import isin
from scipy.special import erf
from scipy.special import erf
from scipy.signal import find_peaks, convolve
from math import floor, ceil
import time
import matplotlib.pyplot as plt
import multiprocessing as mp
#===================... | np.sqrt(2*np.pi) | numpy.sqrt |
# Copyright 2019 <NAME>, <NAME> and <NAME>
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in w... | assert_equal(local_matrix.a, 3) | numpy.testing.assert_equal |
# -*- coding: utf-8 -*-
"""
Academy Color Encoding System - Log Encodings
=============================================
Defines the *Academy Color Encoding System* (ACES) log encodings:
- :func:`colour.models.log_encoding_ACESproxy`
- :func:`colour.models.log_decoding_ACESproxy`
- :func:`colour.models.log_encod... | np.resize(constants.CV_min, lin_AP1.shape) | numpy.resize |
# Copyright (C) 2022 <NAME>
#
# SPDX-License-Identifier: MIT
import numpy as np
import pytest
import ufl
from dolfinx.cpp.mesh import to_type
from dolfinx.io import XDMFFile
import dolfinx.fem as _fem
from dolfinx.graph import create_adjacencylist
from dolfinx.mesh import (CellType, create_mesh, locate_entities_boun... | np.isclose(x[tdim - 1], 0) | numpy.isclose |
import unittest
import mapf_gym as MAPF_Env
import numpy as np
# Agent 1
num_agents1 = 1
world1 = [[ 1, 0, 0, -1, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[-1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0... | np.array(world3) | numpy.array |
# -*- mode: python; coding: utf-8 -*
# Copyright (c) 2018 Radio Astronomy Software Group
# Licensed under the 2-clause BSD License
"""Commonly used utility functions."""
from __future__ import absolute_import, division, print_function
import numpy as np
import six
import warnings
import copy
from scipy.spatial.distan... | np.cos(ra) | numpy.cos |
import ctypes as ct
import numpy as np
import numpy.ctypeslib as ctl
from .base import NullableFloatArrayType
from smlmlib.context import Context
from smlmlib.calib import sCMOS_Calib
import scipy.stats
class PSF:
def __init__(self, ctx:Context, psfInst):
self.inst = psfInst
self.ctx = ctx
... | np.random.poisson(ev) | numpy.random.poisson |
import numpy as np
from .Track import Track
# Track descriptor information:
# 0 - straight, 1 - corner
# 0 - left, 1 - right
# [type,length/sweep,radius,direction]
segments = np.array(
[
[0, 150, 0, -1],
[1, np.pi / 2, 50, 0],
[0, 100, 0, -1],
[1, np.pi / 2, 90, 0],
[0, 300... | np.deg2rad(21.5) | numpy.deg2rad |
import config
from utils import SumTree
import numpy as np
import random
import torch
TD_INIT = config.td_init
EPSILON = config.epsilon
ALPHA = config.alpha
class Replay_buffer:
'''
basic replay buffer
'''
def __init__(self, capacity = int(1e6), batch_size = None):
self.capacity = capacity
... | np.vstack([self.memory[ind][0] for ind in index_set]) | numpy.vstack |
# coding=utf-8
"""
Module to apply a previously trained model to estimate the epigenome
for a specific cell type in a different species
"""
import os as os
import pandas as pd
import numpy as np
import numpy.random as rng
import operator as op
import multiprocessing as mp
import json as json
import pickle as pck
fro... | np.isclose(model_perf, perf_score, rtol=1e-05, atol=1e-05) | numpy.isclose |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2018 <NAME> <<EMAIL>>
#
# Distributed under terms of the GNU-License license.
"""
"""
import numpy as np
import numpy.linalg as LA
import scipy.stats as scistats
import matplotlib.pyplot as plt
import sklearn.gaussian_process as skgp
from... | np.std(y_max, axis=0,ddof=1 ) | numpy.std |
import numpy as np
import numpy.linalg as lg
class atom:
def __init__(self,name,pos):
self.type=name
self.pos=pos
self.rank=0
self.q=0
self.d=np.zeros(3)
self.quad=np.zeros(5)
self.pol=np.zeros([3,3])
def setmultipoles(self,q,d,quad,pol):
se... | np.zeros(5) | numpy.zeros |
import numpy as np
from numpy.testing import assert_array_equal, assert_raises
from nilabels.tools.aux_methods.morpological_operations import get_morphological_patch, get_morphological_mask, \
get_values_below_patch, get_circle_shell_for_given_radius
# TEST aux_methods.morphological.py
def test_get_morpologica... | np.ones([3, 3]) | numpy.ones |
"""
Collection of environment classes that are based on rai-python
"""
import sys
import os
import time
import tqdm
import numpy as np
import matplotlib.pyplot as plt
sys.path.append(os.getenv("HOME") + '/git/rai-python/rai/rai/ry')
if os.getenv("HOME") + '/git/rai-python/rai/rai/ry' in sys.path:
import libry as r... | np.zeros((state_now.shape[0], 6)) | numpy.zeros |
import numpy as np
import astropy.units as u
import astropy.time as at
import astropy.coordinates as coord
import scipy.interpolate as interp
import scipy.ndimage as img
import scipy.sparse
import numpy.random as random
def dict_from_h5(hf,data):
import h5py
for key in hf.keys():
if key == 'obs_times'... | np.array(hf[key]) | numpy.array |
import tensorflow as tf
import numpy as np
import sac_dev.util.tf_util as TFUtil
import sac_dev.util.mpi_util as MPIUtil
from sac_dev.util.logger import Logger
class MPISolver():
CHECK_SYNC_ITERS = 1000
def __init__(self, sess, optimizer, vars):
self._vars = vars
self._sess = sess
self... | np.zeros(grad_dim, dtype=np.float32) | numpy.zeros |
#coding:utf-8
import numpy as np
import time
from videocore.assembler import qpu
from videocore.driver import Driver
def mask(idx):
values = [1]*16
values[idx] = 0
return values
@qpu
def piadd(asm):
A_ADDR=0 #インデックス
B_ADDR=1
C_ADDR=2
IO_ITER=3
THR_ID=4
THR_NM=5
COMPLETED=0 #セマフォ用... | np.abs(C - CC) | numpy.abs |
import os
import numpy as np
import pyccl as ccl
# Set cosmology
cosmo = ccl.Cosmology(Omega_c=0.25, Omega_b=0.05, Omega_g=0, Omega_k=0,
h=0.7, sigma8=0.8, n_s=0.96, Neff=0, m_nu=0.0,
w0=-1, wa=0, T_CMB=2.7255,
transfer_function='eisenstein_hu')
# Read ... | np.fabs(nm_h / nm_d - 1) | numpy.fabs |
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 18 11:45:32 2018
Empirical Wavelet Transform implementation for 1D signals
Original paper:
<NAME>., 2013. Empirical Wavelet Transform. IEEE Transactions on Signal Processing, 61(16), pp.3999–4010.
Available at: http://ieeexplore.ieee.org/lpdocs/epic03/wrapper.htm?a... | np.append(boundaries,boundaries[-1]+deltaw) | numpy.append |
#!/usr/bin/env python
from datetime import datetime
import copy
import traceback
import os, subprocess, time, signal
#from cv_bridge import CvBridge
import gym
import math
import random
# u
import numpy as np
import cv2 as cv
import rospy
# Brings in the SimpleActionClient
import actionlib
# Brings in the .actio... | np.cos(-center_orientation) | numpy.cos |
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 11 16:19:39 2014
"""
import os
import sys
import imp
# Put location of
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..\\..')) + '\\modules') # add ODYM module directory to system path
#NOTE: Hidden variable __file__ must be know to script ... | np.array([3,5,2,4]) | numpy.array |
# Imported and adapated from Trimesh
#
# Copyright (c) 2019 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, cop... | np.roll(o, -1, axis=1) | numpy.roll |
# -*- coding: utf-8 -*-
"""
Test nematusLL for consistency with nematus
"""
import os
import unittest
import sys
import numpy as np
import logging
import Pyro4
nem_path = os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../'))
sys.path.insert(1, nem_path)
from nematus.pyro_utils import setu... | np.tile(x0, [1, 1, 2]) | numpy.tile |
# AUTO GENERATED. DO NOT CHANGE!
from ctypes import *
import numpy as np
class MJCONTACT(Structure):
_fields_ = [
("dist", c_double),
("pos", c_double * 3),
("frame", c_double * 9),
("includemargin", c_double),
("friction", c_double * 5),
("solref", c_double * ... | np.array(value, dtype=np.float64) | numpy.array |
import torch as torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence, pad_sequence
from torch.utils.data import Dataset, DataLoader
from torch.utils.tensorboard import SummaryWriter
import collections
import gl... | np.mean(losses) | numpy.mean |
#!/usr/bin/env python
""" Remove nan from vertex coordinates and uv coordinates
"""
import argparse
import pymesh
import numpy as np
def parse_args():
parser = argparse.ArgumentParser(__doc__);
parser.add_argument("input_mesh");
parser.add_argument("output_mesh");
return parser.parse_arg... | np.arange(mesh.num_vertices, dtype=int) | numpy.arange |
#!/usr/bin/env python
# Software License Agreement (BSD License)
#
# Copyright (c) 2014, <NAME>, Social Robotics Lab, University of Freiburg
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#... | numpy.linalg.norm(lastVelocity) | numpy.linalg.norm |
#!/usr/bin/env python
# coding: utf-8
# # Imports
import numpy as np
import tensorflow as tf
import tensorflow_model_optimization as tfmot
import matplotlib.pyplot as plt
import json
import tempfile
import itertools
#from google.colab import drive
from mat4py import loadmat
print(tf.__version__)
# # Data pre-p... | np.sqrt(lstm_val_loss_10) | numpy.sqrt |
import unittest
import matplotlib
import matplotlib.pyplot
matplotlib.use("Agg")
matplotlib.pyplot.switch_backend("Agg")
class Test(unittest.TestCase):
def test_cantilever_beam(self):
import numpy as np
import matplotlib.pyplot as plt
from smt.problems import CantileverBeam
ndim... | np.ones((num, ndim)) | numpy.ones |
# coding: utf-8
# !/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 19 11:05:23 2017
@author: zhangji
"""
from matplotlib import pyplot as plt
# plt.rcParams['figure.figsize'] = (18.5, 10.5)
# fontsize = 40
import os
# import glob
import numpy as np
from datetime import datetime
# import matplotl... | np.ma.getmask(result) | numpy.ma.getmask |
import numpy as np
import tensorflow as tf
#定义函数:将中心点、高、宽坐标 转化为[x0, y0, x1, y1]坐标形式
def detections_boxes(detections):
center_x, center_y, width, height, attrs = tf.split(detections,
[1, 1, 1, 1, -1],
... | np.nonzero(iou_mask) | numpy.nonzero |
"""Serialization Unit Tests"""
import numpy as np
from pytest import raises
from proxystore.serialize import serialize, deserialize
from proxystore.serialize import SerializationError
def test_serialization() -> None:
"""Test serialization"""
x = b'test string'
b = serialize(x)
assert deserialize(b)... | np.array([1, 2, 3]) | numpy.array |
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
colors = ['navy', 'turquoise', 'darkorange']
def make_ellipses(gmm, ax):
for n, color in enumerate(colors):
if gmm.covariance_type == 'full':
covariances = gmm.covariances_[n][:2, :2]
elif gmm.covariance_type == 'tied':
covariances ... | np.sqrt(2.) | numpy.sqrt |
import matplotlib.pyplot as plt
import modelmiezelb.arg_inel_mieze_model as arg
import os
###############################################################################
from numpy import linspace, tile, trapz, all, isclose, arange, ones, atleast_2d, where
from pprint import pprint
from time import time
###############... | arange(-UPPER_INTEGRATION_LIMIT, UPPER_INTEGRATION_LIMIT+0.001, 15e-3) | numpy.arange |
# Author: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
#
# License: BSD (3-clause)
import os.path as op
from nose.tools import assert_true, assert_raises, assert_equal
import numpy as np
from numpy.testing import assert_array_almost_equal, assert_array_equal
from mne import io, Epochs, read_events, pick_types
from mn... | assert_array_almost_equal(V, V_matlab) | numpy.testing.assert_array_almost_equal |
import os
import numpy as np
def load_networks(data_path):
'''Get a list of paths for all the files inside data_path'''
networks_dir = []
for file in os.listdir(data_path):
networks_dir += [os.path.join(data_path, file)]
return networks_dir
def get_degree_distribution(degrees):
... | np.sqrt(t / t_i) | numpy.sqrt |
"""Unit tests for raw_ships_io.py."""
import copy
import unittest
import numpy
from ml4tc.io import raw_ships_io
TOLERANCE = 1e-6
DISTANCES_METRES = numpy.array([-200, -100, -50, 0, 100, 150, 200], dtype=float)
DISTANCES_KM = numpy.array([-0.2, -0.1, -0.05, 0, 0.1, 0.15, 0.2])
TEMPERATURES_DECICELSIUS = numpy.array... | numpy.array([96, 100], dtype=int) | numpy.array |
"""Calculate."""
# --- import --------------------------------------------------------------------------------------
import numpy as np
from .. import units as wt_units
# --- define --------------------------------------------------------------------------------------
__all__ = ["mono_resolution", "nm_width", ... | np.sign(x) | numpy.sign |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import tensorflow as tf
import os
import sys
import keras
from keras.models import Sequential, Model
from keras.layers import Dense, Activation, Dropout, Embedding, LSTM, Bidirectional,Multiply
# Merge,
from keras.layers import BatchNormalization, merge, add
from ... | np.mean(all_rm2) | numpy.mean |
"""
oksar3
Program to calcuate forward models of interferograms, strain tensor, etc.
from Okada subroutine.
Heritage:
- originally fringes.c written by <NAME>
- updated to oksar tjw
- oksar_strain: added strain tensor calculation tjw
- oksar3: added new line of... | np.sqrt(xi*xi+q*q) | numpy.sqrt |
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import numpy as np
import os
import pytest
import time
from openvino.inference_engine import ie_api as ie
from tests_compatibility.conftest import model_path
from ..test_utils.test_utils import generate_image # TODO: reformat into an a... | np.argmax(exec_net.requests[id].output_blobs['fc_out'].buffer) | numpy.argmax |
import pytest
import numpy as np
from scipy import sparse
from scipy.sparse import csgraph
from scipy.linalg import eigh
from sklearn.manifold import SpectralEmbedding
from sklearn.manifold._spectral_embedding import _graph_is_connected
from sklearn.manifold._spectral_embedding import _graph_connected_component
from... | np.std(embedding[:, 1]) | numpy.std |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.