prompt
stringlengths
15
655k
completion
stringlengths
3
32.4k
api
stringlengths
8
52
import sqlite3 import numpy as np import Helpers conn = sqlite3.connect('../data/SandP500.sqlite3') all_tickers = Helpers.get_all_tickers(conn) cursor = conn.cursor() prices_at_start = np.array([]) prices_at_end = np.array([]) for ticker in all_tickers: cursor.execute("SELECT closing_price " ...
np.append(prices_at_start, price_at_start)
numpy.append
import numpy as np from ..visualization import Viewer from ..utils import Subject, Observer, deprecated, matrices, NList import copy from numba import njit, int64, float64 from numba.types import ListType as LT @njit(int64[:](LT(LT(int64))), cache=True) def _valence(adj_x2y): valences = np.zeros(len(adj_x2y), dtyp...
np.logical_xor(flip_z,((centroids[:,2] >= min_z) & (centroids[:,2] <= max_z)))
numpy.logical_xor
import os, math import _pickle as pickle from datetime import datetime, timedelta import numpy as np import pandas as pd from sklearn import preprocessing import argparse parser = argparse.ArgumentParser() parser.add_argument('--data-folder', default='data', help='Parent dir of the dataset') parser.add_argument('--f...
np.zeros(shape=(test_n, input_len))
numpy.zeros
import numpy as np import sys, os if __name__== "__main__": # read samples mesh gids smgids = np.loadtxt("sample_mesh_gids.dat", dtype=int) print(smgids) # read full velo fv = np.loadtxt("./full/velo.txt") # read full velo fullJ = np.loadtxt("./full/jacobian.txt") # read sample mesh velo sv = np...
np.allclose(maskedJacob.shape, sjac.shape)
numpy.allclose
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Module for tools used in vaspy """ import bz2 from itertools import zip_longest import os import re import numpy as np from typing import List, Iterable, Sequence, Tuple, Union, IO, Any, Optional def open_by_suffix(filename: str) -> IO[str]: """Open file.""" ...
np.array(crystal_axes[2])
numpy.array
__author__ = 'Mario' import numpy as np from scipy.stats import norm class EuropeanLookback(): def __init__(self, strike, expiry, spot, sigma, rate, dividend, M, flag, N=100, Vbar=.12, alpha=.69): # Instantiate variables self.strike = float(strike) self.expiry = float(expiry) self...
np.sqrt(Vtn)
numpy.sqrt
import unittest from scipy.stats import gaussian_kde from scipy.linalg import cholesky import numpy as np from pyapprox.bayesian_inference.laplace import * from pyapprox.density import NormalDensity, ObsDataDensity from pyapprox.utilities import get_low_rank_matrix from pyapprox.randomized_svd import randomized_svd, Ma...
np.dot(gradient,directions)
numpy.dot
"""Class for playing and annotating video sources in Python using Tkinter.""" import json import logging import pathlib import datetime import tkinter import tkinter.filedialog import numpy as np import cv2 import PIL.Image import PIL.ImageTk logger = logging.getLogger("VideoPyer") logging.basicConfig(level=logging.I...
np.array([x1, y1])
numpy.array
from DNN.hans_on_feedforward_neural_network import Feedforward_neural_network import numpy as np Net = Feedforward_neural_network() #--------------------------多元回归实验----------------------------- # ---------------------------准备数据------------------------------- #--------------------------------------------------------...
np.random.normal(0, 10, size=Y_data.shape)
numpy.random.normal
#Contains MeldCohort and MeldSubject classes from contextlib import contextmanager from meld_classifier.paths import ( DEMOGRAPHIC_FEATURES_FILE, CORTEX_LABEL_FILE, SURFACE_FILE, DEFAULT_HDF5_FILE_ROOT, BOUNDARY_ZONE_FILE, NVERT, BASE_PATH, ) import pandas as pd import numpy as np import ni...
np.sum(self.cohort.surf_area[lesion])
numpy.sum
import numpy as np import math import os def load_obj(dire): fin = open(dire,'r') lines = fin.readlines() fin.close() vertices = [] triangles = [] for i in range(len(lines)): line = lines[i].split() if len(line)==0: continue if line[0] == 'v': ...
np.array(triangles, np.int32)
numpy.array
# Licensed under an MIT open source license - see LICENSE """ SCOUSE - Semi-automated multi-COmponent Universal Spectral-line fitting Engine Copyright (c) 2016-2018 <NAME> CONTACT: <EMAIL> """ import numpy as np import sys import warnings import pyspeckit import matplotlib.pyplot as plt import itertools import time...
np.abs(velolist[i] - adjacent_velocity)
numpy.abs
import math import numpy as np from scipy import signal def gaussian_pdf_1d(mu, sigma, length): '''Generate one dimension Gaussian distribution - input mu: the mean of pdf - input sigma: the standard derivation of pdf - input length: the size of pdf - output: a row vector represent...
np.arctan(ly/lx)
numpy.arctan
""" desisim.spec_qa.redshifts ========================= Module to run high_level QA on a given DESI run Written by JXP on 3 Sep 2015 """ from __future__ import print_function, absolute_import, division import matplotlib # matplotlib.use('Agg') import numpy as np import sys, os, pdb, glob from matplotlib import pyp...
np.max(xval)
numpy.max
""" fastspecfit.continuum ===================== Methods and tools for continuum-fitting. """ import pdb # for debugging import os, time import numpy as np import astropy.units as u from fastspecfit.util import C_LIGHT from desiutil.log import get_logger log = get_logger() def _fnnls_continuum(myargs): """Mult...
np.nanmin(continuum_phot_abmag[indx])
numpy.nanmin
""" Module for calculating metrics from CO2, usually as a baseline to compare other gases. Author: <NAME> (UK) Adapted by <NAME> """ import numpy as np from fair.constants import molwt from fair.constants.general import M_ATMOS from fair.forcing.ghg import meinshausen from fair.defaults.thermal import q, d def ch4_...
np.array([co2, ch4, n2o])
numpy.array
"""Run chemical evolution model.""" from __future__ import print_function, division, absolute_import import os from os.path import join import copy import traceback import time import numpy as np import pandas as pd import utils def integrate_power_law(exponent, bins=None): """Integrate a power law distributio...
np.array(tmp['ab'])
numpy.array
import os import sys import h5py import torch import numpy as np import importlib import random import shutil from PIL import Image BASE_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.join(BASE_DIR, '../utils')) from colors import colors colors = np.array(colors, dtype=np.float32) ...
np.sin(theta)
numpy.sin
import numpy as np def gradient_descent(x, y): m_curr = b_curr = 0 iterations = 1250 n = len(x) learning_rate = 0.08 for i in range(iterations): y_predicted = m_curr * x + b_curr cost = (1 / n) * sum([val ** 2 for val in (y - y_predicted)]) md = -(2 / n) * sum(x * (y - y_p...
np.array([1, 2, 3, 4, 5])
numpy.array
import os import tqdm import shutil import argparse import setproctitle import pandas as pd import numpy as np from skimage import measure from skimage.io import imsave import matplotlib.pyplot as plt plt.switch_backend('agg') from ast import literal_eval import SimpleITK as sitk import torch import torch.nn as nn...
np.array(dsc_list)
numpy.array
""" Author: <NAME> <<EMAIL>>. References: - - - """ import os import networkx as nx import numpy as np from hyperopt import fmin, tpe, hp, STATUS_OK, Trials from sklearn.metrics import f1_score, accuracy_score # For the plot functions. _Z_ORDER_V = 10 _Z_ORDER_SE = _Z_ORDER_V - 1 _Z_ORDER_SSV = _Z_ORDE...
np.zeros(shape=nsamples, dtype=np.int8)
numpy.zeros
""" File: examples/distribution/binomial_distribution.py Author: <NAME> Date: Oct 15 2019 Description: Example of using the BinomialDistribution class. """ import os, time import numpy as np import matplotlib.pyplot as pl from distpy import BinomialDistribution sample_size = int(1e5) distribution = BinomialDistribut...
np.std(sample)
numpy.std
import numpy as np def Fourier_shear(image,shear_factor,axis=[-1,-2],fftshifted=False): """Accomplishes the following affine transformation to an image: [x'] = [ 1 shear_factor] [x] [y'] [ 0 1 ] [y] via Fourier transform based methods. Paramet...
np.meshgrid(qxout,qyout)
numpy.meshgrid
import numpy as np import scipy.sparse from numpy import sin, cos, tan import sys import slepc4py slepc4py.init(sys.argv) from petsc4py import PETSc from slepc4py import SLEPc opts = PETSc.Options() import pickle as pkl class Model(): def __init__(self, model_variables, model_parameters, physical_constants): ...
sin(th)
numpy.sin
#!/usr/bin/env python3 # encoding: utf-8 # Copyright 2017 Johns Hopkins University (<NAME>) # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """Training/decoding definition for the speech recognition task.""" import copy import json import logging import math import os import sys from chainer import repo...
np.array([x.shape[0] for x in xs_list[i]])
numpy.array
#!/usr/bin/env python # -*- coding: utf-8 -*- """ SeedEditor for organ segmentation Example: $ seed_editor_qp.py -f head.mat """ from loguru import logger # try: # QString = unicode # except NameError: # Python 3 # QString = str QString = str # import unittest from optparse import OptionParser from scipy.io import...
np.max(self.seeds)
numpy.max
import cv2 import numpy as np import os from objects.bbox import BBox from objects.image import Image class BBoxList: def __init__(self): self.data = [] def __len__(self): return len(self.data) def reduce_to_classes(self, class_list): new_data = [] for d in self.data: ...
np.mean(counts)
numpy.mean
# -*- coding: utf-8 -*- """ Created on Wed Jul 20 15:12:49 2016 @author: uzivatel """ import numpy as np import timeit from multiprocessing import Pool, cpu_count from functools import partial from sys import platform import scipy from copy import deepcopy from ..qch_functions import overlap_STO, dipole...
np.power(Z_grid_loc,2)
numpy.power
# -*- coding: utf-8 -*- from datetime import datetime from io import StringIO import re import numpy as np import pytest from pandas.compat import lrange import pandas as pd from pandas import DataFrame, Index, MultiIndex, option_context from pandas.util import testing as tm import pandas.io.formats.format as fmt ...
np.zeros((2, 2), dtype=int)
numpy.zeros
import pandas as pd import numpy as np from ..dataModel.dataProcessing import DataContainer, myDataset import matplotlib.pyplot as plt from torch import nn import torch as tc from sklearn.metrics import * from tqdm import tqdm from torch.nn import functional as F from ..utils import one_hot_embedding, window_padding im...
np.mean(mini_loss)
numpy.mean
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on 11 August, 2018 Testing suite for Network class @author: <NAME> @email: <EMAIL> @date: 11 August, 2018 @modified: 16 february, 2021 """ import unittest import numpy as np from topopy import Flow, Network import os infolder = "data/in" outfolder = "data/out...
np.array([])
numpy.array
''' Helper functions for the puzzle.py ''' import random from simpleimage import SimpleImage import math import numpy as np def create_solution(num_pieces, seed = 2000): ''' Takes a number of pieces as input Returns the original order and a random order of pieces as a dictionary with {orignal_positio...
np.array([0, height - 1, 0])
numpy.array
import math import numpy as np import random class Tiling(): def __init__(self, x_range=[-1.2,0.6], v_range= [-0.07,0.07], n_tiles=4, n_tilings=5, displacement_vector=[1,3]): self.x_range = np.array(x_range) self.v_range = np.array(v_range) self.x = 0 self.v = 0 s...
np.shape(state)
numpy.shape
# -*- coding: utf-8 -*- import os import json from datetime import datetime import numpy as np from matplotlib import pyplot as plt def visualize_result( experiment_name, X_test, Y_test, Y_hat, parameters, losses=None, save_dir="results" ): """ 结果可视化 """ # 没有保存目录时创建...
np.arange(0.0, 1.0, 0.01)
numpy.arange
import numpy as np import pandas as pd from typing import List from brightwind.transform import transform as tf from brightwind.analyse.plot import plot_scatter, plot_scatter_by_sector, plot_scatter_wdir from scipy.odr import ODR, RealData, Model from scipy.linalg import lstsq from brightwind.analyse.analyse import mom...
np.isnan(sec_veers[i - 1])
numpy.isnan
from __future__ import print_function from __future__ import division from builtins import str from flarestack.utils.prepare_catalogue import ps_catalogue_name from flarestack.data.icecube.ps_tracks.ps_v002_p01 import IC86_1_dict, IC86_234_dict from flarestack.core.results import ResultsHandler from flarestack.cluster ...
np.array(sens)
numpy.array
""" 1HN In-phase/Anti-phase Proton CEST =================================== Analyzes chemical exchange during the CEST block. Magnetization evolution is calculated using the (6n)×(6n), two-spin matrix, where n is the number of states:: { Ix(a), Iy(a), Iz(a), IxSz(a), IySz(a), IzSz(a), Ix(b), Iy(b), Iz(b), I...
np.array([intst[offset] for offset in offsets])
numpy.array
from __future__ import division, absolute_import, print_function import platform import numpy as np from numpy import uint16, float16, float32, float64 from numpy.testing import run_module_suite, assert_, assert_equal, dec def assert_raises_fpe(strmatch, callable, *args, **kwargs): try: callable(*args, ...
np.array((1e4,), dtype=float16)
numpy.array
from abc import ABCMeta import numpy as np from typing import List import TransportMaps.Distributions as dist import TransportMaps.Likelihoods as like from utils.LinAlg import is_spd class Distribution(metaclass=ABCMeta): @property def dim(self) -> int: raise NotImplementedError def ...
np.linalg.inv(self._precision)
numpy.linalg.inv
"""Module defining backend agnostic containers for visualisation elements.""" from collections import OrderedDict from collections.abc import Mapping from copy import deepcopy from typing import List import numpy as np class Element(object): """Representation of a single element. Implemented as a frozen dic...
np.array(self._positions)
numpy.array
import os import numpy as np import matplotlib.pyplot as plt class YOLO_Kmeans: def __init__(self, cluster_number, filename, save_path): self.cluster_number = cluster_number self.filename = filename self.save_path = save_path def iou(self, boxes, clusters): # 1 box -> k clusters ...
np.shape(data)
numpy.shape
"""Module handling the creation and use of migration matrices.""" from copy import deepcopy from warnings import warn import numpy as np from .binning import Binning, CartesianProductBinning class ResponseMatrix: """Matrix that describes the detector response to true events. Parameters ---------- ...
np.append(resp2, truth2[np.newaxis, :], axis=0)
numpy.append
import numpy as np from numpy import random from scipy.interpolate import interp1d import pandas as pd msun = 1.9891e30 rsun = 695500000.0 G = 6.67384e-11 AU = 149597870700.0 def component_noise(tessmag, readmod=1, zodimod=1): sys = 59.785 star_mag_level, star_noise_level = np.array( [ [4...
np.zeros(nselect)
numpy.zeros
from sklearn import metrics import numpy as np import pandas as pd import seaborn as sns from .stats import * from .scn_train import * import matplotlib import matplotlib.pyplot as plt def divide_sampTab(sampTab, prop, dLevel="cell_ontology_class"): cts = set(sampTab[dLevel]) trainingids = np.empty(0) for...
np.sum(cm)
numpy.sum
from __future__ import division, print_function import cmath import time from copy import copy import os import argparse import inspect from collections import OrderedDict from timeit import default_timer as timer try: from inspect import getfullargspec except ImportError: from inspect import getargspec as ge...
cos(x)
numpy.cos
import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import Ellipse from scipy.stats import multivariate_normal from tqdm import tqdm class GMM: def __init__(self, x): self.x = x self.pts = x.shape[0] self.k, self.w, self.pi, self.mu, self.sigma = None, None, None, Non...
np.zeros((k, self.x.shape[-1], self.x.shape[-1]))
numpy.zeros
"""" Library of different error metrics like mean squared error, KL-divergence, etc. Used to compute the reconstruction error of the autoencoder """ import os import numpy as np from src.preprocessing import heartbeat_split import random import matplotlib.pyplot as plt from scipy import signal from scipy.stats import...
np.mean(kld, axis=1)
numpy.mean
#! /usr/bin/env python """Phase contraint overlap tool. This tool calculates the minimum and maximum phase of the primary or secondary transit (by default, primary) based on parameters provided by the user. Authors: <NAME>, 2018 <NAME>, 2018 <NAME>, 2020 Usage: calculate_constraint <target_name> [--t0=<...
np.cos(x)
numpy.cos
import pandas as pd import numpy as np import codecs import time from org.mk.training.dl.rnn import bidirectional_dynamic_rnn from org.mk.training.dl.rnn import dynamic_rnn from org.mk.training.dl.rnn import MultiRNNCell from org.mk.training.dl.nn import embedding_lookup from org.mk.training.dl.nn import TrainableVaria...
np.amax(en_text_len)
numpy.amax
# -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright (C) 2014-2018 GEM Foundation # # OpenQuake is free software: you can redistribute it and/or modify it # under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the Licen...
np.radians(dists.azimuth)
numpy.radians
import string import torch from net import RINet, RINet_attention from database import evalDataset_kitti360, SigmoidDataset_kitti360, SigmoidDataset_train, SigmoidDataset_eval import numpy as np from torch.utils.data import DataLoader from tqdm import tqdm from sklearn import metrics import os import argparse # from te...
np.nan_to_num(pred)
numpy.nan_to_num
""" A distributed version of the paraboloid model with an extra input that can be used to shift each index. This version is used for testing, so it will have different options. """ import numpy as np import openmdao.api as om from openmdao.utils.mpi import MPI from openmdao.utils.array_utils import evenly_distrib_idx...
np.arange(io_size)
numpy.arange
import pytest import numpy as np import pandas as pd from ..utils import _check_random_state from ..utils import _check_min_supp from ..utils import _check_growth_rate from ..utils import filter_maximal from ..utils import filter_minimal from ..utils import intersect2d def test_check_random_state(): random_state ...
np.array([1])
numpy.array
# # Created by: <NAME>, September 2002 # import sys import subprocess import time from functools import reduce from numpy.testing import (assert_equal, assert_array_almost_equal, assert_, assert_allclose, assert_almost_equal, assert_array_equal) import pytest from...
assert_equal(info, 0)
numpy.testing.assert_equal
from __future__ import absolute_import, division, print_function import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import numpy as np import cv2 import os import sys from torch.optim.lr_scheduler import ExponentialLR from collections import namedtuple from got10k.trackers ...
np.hanning(self.response_sz)
numpy.hanning
from abc import ABC, abstractmethod from typing import Optional import numpy as np from gym.spaces import Discrete, MultiDiscrete from torch.distributions import Normal, kl_divergence from pearll.common.type_aliases import ( CrossoverFunc, MutationFunc, SelectionFunc, UpdaterLog, ) from pearll.common....
np.min(new_population, axis=0)
numpy.min
import matplotlib.pyplot as plt #import matplotlib.axes as axes import numpy as np #axes.Axis.set_axisbelow(True) x = np.array([1,2,3,4,5,6,7]) my_xticks = ['1','2','3','4','5','6','7'] plt.xticks(x, my_xticks) # for L=1,w=1,d=1 # for L=1,w=2,d=1 # for L=1,w=3,d=1 # for L=1,w=4,d=1 y = np.array([0.207044,np.nan,np.nan...
np.array([np.nan,np.nan,0.375075,0.325434,np.nan,np.nan,np.nan])
numpy.array
from collections import namedtuple from rlpyt.utils.collections import namedarraytuple, AttrDict import numpy as np Samples = namedarraytuple("Samples", ["agent", "env"]) AgentSamples = namedarraytuple("AgentSamples", ["action", "prev_action", "agent_info"]) AgentSamplesBsv = namedarraytuple("AgentSamplesBsv", ...
np.sum(obs_act)
numpy.sum
#!/usr/bin/env python3 def get_input(): import argparse parser = argparse.ArgumentParser() parser.add_argument( 'Output-File', help='Output-File from a RASSI calculation' ) parser.add_argument( '-s', '--sigma', required=False, type=float, default=150, help='Plotting option for gaussian broadening...
np.array([])
numpy.array
# # Short Assignment 2: Image Restoration # ## SCC0251.2020.1 - Image Processing # ### Prof. Dr. <NAME> # ### 10284952 - <NAME> # https://github.com/vitorgt/SCC0251 # Imports import numpy as np import imageio # import matplotlib.pyplot as plt r = imageio.imread(str(input()).rstrip()).astype(np.uint8) k = int(input(...
np.std(r_denoi_deblur)
numpy.std
# -*- coding:utf8 -*- # File : rng.py # Author : <NAME> # Email : <EMAIL> # Date : 2/23/17 # # This file is part of TensorArtist. # This file is part of NeuArtist2 import os import numpy as np import numpy.random as npr __all__ = ['rng', 'reset_rng', 'gen_seed', 'gen_rng', 'shuffle_multiarray'] rng = None de...
npr.RandomState(seed)
numpy.random.RandomState
r""" Python module to compute the Mann-Kendall test for trend in time series data. This module contains a single function 'test' which implements the Mann-Kendall test for a linear trend in a given time series. Introduction to the Mann-Kendall test ------------------------------------- The Mann-Kendall test is used...
np.fabs(S)
numpy.fabs
"""Linear operator tests. """ from __future__ import division, absolute_import import unittest import numpy as np from bcn.linear_operators import LinearOperatorEntry, LinearOperatorDense, LinearOperatorKsparse, LinearOperatorCustom, integer_to_matrix, sample_n_choose_k, choose_random_matrix_elements from bcn.data i...
np.array(self.signal)
numpy.array
__author__ = '<NAME>' import numpy as np def myKMeans(k, Data): dataL = np.zeros((Data.shape[0], Data.shape[1]+1), dtype=np.float64) dataL[:,1:] = Data randInd = np.random.randint(0, Data.shape[0], k, np.int64) centroids = Data[randInd, :] labelsC = np.asarray(range(k)) flag = ...
np.sum((dataL[:, 1:] - meanCent) ** 2, axis=1)
numpy.sum
import numpy as np import matplotlib.pyplot as plt from quat import Quat from sys import exit def ori_matrix(phi1,Phi,phi2,passive=True): ''' Returns (passive) orientation matrix, as a np.matrix from 3 euler angles (in degrees). ''' phi1=np.radians(phi1) Phi=np.radians(Phi) phi2=np....
np.isclose(alpha,0.0)
numpy.isclose
import numpy as np import matplotlib.pyplot as plt from sklearn import metrics from scipy.stats import spearmanr, combine_pvalues, friedmanchisquare from scikit_posthocs import posthoc_nemenyi_friedman from tabulate import tabulate from Orange.evaluation import compute_CD, graph_ranks from hmeasure import h_scor...
np.array(all_aps)
numpy.array
# coding: utf-8 # # Creating a dataset of Ohio injection wells import matplotlib.pyplot as plt import random import numpy as np import pandas as pd import os # set datadir to the directory that holds the zipfile datadir = 'c:\MyDocs/sandbox/data/datasets/FracFocus/' outdir = datadir+'output/' indir = datadir+'OH_...
np.where(four.NoAPIstr,'No API string recorded',four.APIstr)
numpy.where
""" Testing module for Domain.py, Shape.py, BC.py Work in progress TO DO: test inertia test rigid body calculations """ from __future__ import division from builtins import range from past.utils import old_div import unittest import numpy.testing as npt import numpy as np from nose.tools import eq_ from proteus import ...
np.max(flags_v2DRANS)
numpy.max
#!/usr/bin/env python3 # # Tests the cone distribution. # # This file is part of PINTS (https://github.com/pints-team/pints/) which is # released under the BSD 3-clause license. See accompanying LICENSE.md for # copyright notice and full license details. # import pints import pints.toy import unittest import numpy as n...
np.ones((100, 6))
numpy.ones
""" Calculate the wavelet and its significance. """ from __future__ import division, absolute_import import numpy as np from scipy.special._ufuncs import gamma, gammainc from scipy.optimize import fminbound as fmin from scipy.fftpack import fft, ifft __author__ = "<NAME>" __email__ = "<EMAIL>" __all__ = ['Wavelet', ...
np.concatenate(([0.],k1,k2))
numpy.concatenate
''' Contains the following neural pooling functions: 1. min 2. max 3. avg Which are from `Tang et al <https://aclanthology.coli.uni-saarland.de/papers/P14-1146/p14-1146>`_. and the following pooling functions: 4. prod 5. std Which are from `Vo and Zhang <https://www.ijcai.org/Proceedings/15/Papers/194.pdf>`_. and...
np.std(matrix, axis=0)
numpy.std
import numpy as np from surpyval import nonparametric as nonp from scipy.stats import t, norm from .kaplan_meier import KaplanMeier from .nelson_aalen import NelsonAalen from .fleming_harrington import FlemingHarrington_ from scipy.interpolate import interp1d from autograd import jacobian import matplotlib.pyplot as ...
np.log(self.R)
numpy.log
import os, sys, pdb, pickle from profilehooks import profile import time, math, random import numpy as np import scipy as sp from scipy.spatial.distance import cosine from lr.sks import SKS from lr.utils import * def im2col(X, kernel, strides=(1,1), padding=(0,0)): ''' Views X as the matrix-version of a str...
np.ones((1,channels), dtype=dt)
numpy.ones
from pickle import load from keras.preprocessing.sequence import pad_sequences from keras.preprocessing.text import Tokenizer from keras.utils import to_categorical from numpy import array, argmax # load doc into memory def load_doc(filename): # open the file as read only file = open(filename, 'r') # rea...
array(x1)
numpy.array
import numpy as np import pandas as pd import scipy.integrate as intg import matplotlib.pyplot as plt from matplotlib import cm from mpl_toolkits.axes_grid1 import make_axes_locatable from matplotlib.colors import LogNorm import scipy.ndimage.interpolation as interpol import scipy.spatial as sp import decimal import te...
np.mean(tau)
numpy.mean
from __future__ import absolute_import, division, print_function from java import constructor, method, static_proxy, jint, jarray, jdouble, jboolean, jclass from java.lang import String from scipy.signal import butter, lfilter from sklearn.decomposition import FastICA import numpy as np import scipy class NpScip...
np.fft.fftfreq(a, b)
numpy.fft.fftfreq
""" Main script for semantic experiments Author: <NAME> (github/VSainteuf) License: MIT """ import argparse import json import os import pickle as pkl import pprint import time import numpy as np import torch import torch.nn as nn import torch.utils.data as data import torchnet as tnt from src import utils, model_uti...
np.delete(cm, config.ignore_index, axis=0)
numpy.delete
import cv2 import numpy as np import matplotlib.pyplot as plt class Lane: def __init__(self, windows_count = 9, margin = 100, minpix = 50, color=(255, 0, 0), show_image = False): self.show_image = show_image self.color = color # HYPERPARAMETERS # Choose ...
np.concatenate(lane_inds)
numpy.concatenate
from typing import List, Union import numpy as np def get_test_function_method_min(n: int, a: List[List[float]], c: List[List[float]], p: List[List[float]], b: List[float]): """ Функция-замыкание, генерирует и возвращает тестовую функцию, применяя метод Фельдбаума, т. е....
np.array(l)
numpy.array
"""classify.py""" import sys import os import acl path = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.join(path, "..")) sys.path.append(os.path.join(path, "../../../../common/")) sys.path.append(os.path.join(path, "../../../../common/atlas_utils")) from constants import ACL_MEM_MALLOC_HUGE_FIRS...
np.exp(vals[i] - max)
numpy.exp
# -*- coding: utf-8 -*- ####################################### # StabilityMap_2d.py ####################################### # analysis of two coupled tipping elements # for manuscript: # "Emergence of cascading dynamics in interacting tipping elements of ecology and climate" # two coupled tipping elemen...
np.real(x1_stab)
numpy.real
# coding=utf-8 # Copyright 2018 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.array([[2]])
numpy.array
import csv import os import numpy as np import cv2 import matplotlib.image as mpimg from keras.models import Sequential from keras.models import Model import matplotlib.pyplot as plt from keras.layers.core import Dense, Activation, Flatten, Dropout, Lambda from keras.layers.normalization import BatchNormalization from ...
np.copy(angle)
numpy.copy
""" This script produces the Figures 13 from Amaral+2021, the pearson correlation between stellar and planetary mass and surface water loss percentage. @autor: <NAME>, Universidad Nacional Autónoma de México, 2021 @email: <EMAIL> """ import matplotlib.pyplot as plt import numpy as np import scipy.stats import pandas ...
np.genfromtxt(f2, usecols=0 ,unpack=True)
numpy.genfromtxt
import numpy as np from pandas import Series, DataFrame from scipy.signal import savgol_filter, boxcar from scipy import interpolate from matplotlib import pyplot as plt from numpy import abs from numpy import array, poly1d, polyfit def peak_detector(tic, max_tic): dy = derivate(tic) indexes = np.where((...
array(nodes)
numpy.array
import tkinter as tk import tkinter.filedialog as fd import tkinter.messagebox as mb import numpy as np import pyknotid import pyknotid.spacecurves as pkidsc from pyknotid.spacecurves import Knot import sympy import csv import os # set initial values gc_str = "" fileopen = False t = sympy.Symbol("t") # for use in dis...
np.abs(x0)
numpy.abs
#- This simulation with gpu (with the below parameters) took 14h #- In this experiment we also set lr from 0.01 to 0.0025 # but here with masking is like the no masking case (exp2a-d) with 0.03 to 0.0075 # thefactor of corecction is approx 3. # So: probably we should set the next time for masking case: lr=0.005-0.00...
np.array(predict)
numpy.array
from .interval import IntervalGoalEnv from abc import ABC, abstractmethod import numpy as np import copy import matplotlib.pyplot as plt import matplotlib.patches as patches import math #todo first run jsut the algorithm with the minimizer of collision along side to see what Q values it does create #A space visualizer...
np.reshape(extension, (-1, 6))
numpy.reshape
import unittest import numpy as np import numpy.testing as npt from scipy.sparse.csr import csr_matrix from pylogit.scipy_utils import identity_matrix def sparse_assert_equal(a1, a2): """Assert equality of two sparse matrices""" assert type(a1) is type(a2) npt.assert_array_equal(a1.data, a2.data)
npt.assert_array_equal(a1.indices, a2.indices)
numpy.testing.assert_array_equal
import math import numpy as np import torch from torch import nn from utils.geometric import pairwise_distance, calc_angle, calc_dihedral from . import spline from common import config from common.config import EPS from common import constants class OmegaRestraint(nn.Module): """Omega angle is defined as dehidral...
np.concatenate([_y, _y[:, :, :1]], axis=-1)
numpy.concatenate
#Entry point for the LEC agent #Script has anomaly detectors, assurance monitors and risk computations import os import cv2 import torch import torchvision import carla import csv import math import pathlib import datetime import gc import time from numba import cuda from PIL import Image, ImageDraw,ImageFont import th...
np.random.normal(0, 0.5, result['cloud'][0].shape)
numpy.random.normal
""" Routines for building qutrit gates and models """ #*************************************************************************************************** # Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS). # Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government...
_np.array(inputArr)
numpy.array
# -*- 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_state2, [2, 1])
numpy.tile
#!/usr/bin/env python # Copyright 2014-2019 The PySCF Developers. 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 # # U...
numpy.sqrt(coulG[p0:p1])
numpy.sqrt
"""Defines SinglePath MDP and utils.""" from __future__ import print_function from __future__ import division import numpy as np def sample(mdp, pi): """Generate a trajectory from mdp with pi.""" done = False obs = mdp.reset() G = 0 path = {} path['obs'] = [] path['acts'] = [] path['r...
np.zeros((L + 1, S + 1))
numpy.zeros
import unittest import six import tensorflow as tf import numpy as np import GPflow from GPflow import settings float_type = settings.dtypes.float_type np_float_type = np.float32 if float_type is tf.float32 else np.float64 class TestSetup(object): def __init__(self, likelihood, Y, tolerance): self.likelih...
np.concatenate(self.Y_label)
numpy.concatenate
"""Test the text data reader""" import numpy as np import pytest import tensorflow as tf from src.data.text_data_reader import Set, TextDataReader def test_initialization(): dr = TextDataReader() assert dr.name == "text" assert dr.folder == "data/train/text" for set_type in [Set.TRAIN, Set.VAL, Set....
np.concatenate([dataset_labels, labels], axis=0)
numpy.concatenate
"""Tests for chebyshev module. """ from functools import reduce import numpy as np import numpy.polynomial.chebyshev as cheb from numpy.polynomial.polynomial import polyval from numpy.testing import ( assert_almost_equal, assert_raises, assert_equal, assert_, ) def trim(x): return cheb.che...
assert_(v.shape == (3, 2, 4))
numpy.testing.assert_
import time import torch import random import numpy as np from tqdm import tqdm, trange # from torch_geometric.nn import GCNConv from layers_batch import AttentionModule, TenorNetworkModule from utils import * from tensorboardX import SummaryWriter # from warmup_scheduler import GradualWarmupScheduler import os import ...
np.array(batch_target)
numpy.array
import pandas as pd import numpy as np import spacy from tqdm import tqdm from collections import defaultdict nlp = spacy.load("en_core_sci_lg", disable=['ner', 'parser']) path = "../data/" def tokenize(string): doc = nlp.make_doc(string) words = [token.text.lower() for token in doc if token.is_alpha and not ...
np.dot(w_emb, new_word_emb)
numpy.dot