prompt
stringlengths
15
655k
completion
stringlengths
3
32.4k
api
stringlengths
8
52
import csv import click import numpy as np from tqdm import tqdm from src.helpers import paths from src.helpers.flags import AttackModes, Verbose from src.multimodal import multimodal from src.multimodal.data import make_dataset from src.multimodal.features import build_features from src.regnet.data.make_dataset impo...
np.array(batch[2])
numpy.array
import pytest import numpy as np from numpy.testing import (assert_array_equal, assert_array_almost_equal, assert_almost_equal, assert_equal) from nose.tools import assert_raises from pystruct.models import NodeTypeEdgeFeatureGraphCRF, EdgeFeatureGraphCRF from pystruct.inference.linear_prog...
np.eye(n_states)
numpy.eye
# -*- coding: utf-8 -*- import numpy as np import scipy.stats as ss import itertools as it from statsmodels.sandbox.stats.multicomp import multipletests from statsmodels.stats.multicomp import pairwise_tukeyhsd from statsmodels.stats.libqsturng import psturng from pandas import DataFrame, Categorical, Series def __co...
np.empty((k-1, k-1))
numpy.empty
import numpy as np import time import pytest import os, pickle, re, shutil from flare import struc, env, gp from flare import otf_parser from flare.mgp.mgp_en import MappedGaussianProcess from flare.lammps import lammps_calculator from flare.ase.calculator import FLARE_Calculator from ase.calculators.lammpsrun import ...
np.abs(lmp_stress - flare_stress)
numpy.abs
import pandas as pd import numpy as np from scipy.stats import chi2 def get_data(input_file): ''' Read data from a csv file. For the meaning of each variable, please see Ben-Tal et al. (2013) ''' df = pd.read_csv(input_file) c_vec = np.array(df["c"]) v_vec = np.array(df["v"]) ...
np.array(df["l"])
numpy.array
""" Includes functions to assist in spreadsheet functionality """ import re from PyQt5.QtCore import QDateTime import datetime import numpy as np import difflib global lists """ 'lists' contains pre-defined sequences that autofill when using the fill-handle """ lists = [ ['SUN','MON','TUE','WED','THU','FRI','SAT'...
np.round(value,9)
numpy.round
import os import unittest import numpy as np import statsmodels.api as sm import ConfigSpace as CS from hpbandster.optimizers.kde.mvkde import MultivariateKDE from pdb import set_trace rapid_development=True rapid_development=False class Base1dTest(object): n_train = 128 n_test = 1024 def setUp(self): sel...
np.abs(hp_factor_ll)
numpy.abs
import copy import concurrent.futures import numpy as np import scipy.sparse as sparse import scipy.sparse.linalg as splinalg from pyslam.losses import L2Loss class Options: """Class for specifying optimization options.""" def __init__(self): self.max_iters = 100 """Maximum number of iterat...
np.array(cost_blocks)
numpy.array
import numpy as np h = 0.2 c = np.zeros(4) c[0] = 0.1 # estimate c[1] = 0.3 c[2] = 0.1 # estimate c[3] = 0.12 m = np.zeros(3) m[0] = 9. # estimate m[1] = 28. m[2] = 18. real_y = np.loadtxt('y3.txt') def get_A(m, c): A = np.zeros((6, 6)) A[0, 1] = 1. A[1, 0] = -(c[1]+c[0])/m[0] A[1, 2] = c[1]/m[...
np.transpose(delta_y_new)
numpy.transpose
# -*- coding: utf-8 -*- # @Time : 2019/3/13 14:17 # @Author : LunaFire # @Email : <EMAIL> # @File : trainningmodel.py import glob import pickle import numpy as np from PIL import Image from tensorflow import gfile from keras import backend as K from keras.models import Model from keras.layers import Input, C...
np.dot(images[..., :3], [0.299, 0.587, 0.114])
numpy.dot
# Posterior inference. import pyro import pyro.distributions as dist import torch import numpy as np import scipy.sparse as sp import cellbender.remove_background.consts as consts from typing import Tuple, List, Dict, Optional from abc import ABC, abstractmethod import logging class Posterior(ABC): """Base cla...
np.where(self.latents['p'] > 0.9)
numpy.where
''' Testing trackvis module ''' from __future__ import division, print_function, absolute_import from functools import partial import numpy as np from io import BytesIO from .. import trackvis as tv from ..orientations import aff2axcodes from ..volumeutils import native_code, swapped_code from nose.tools import ass...
assert_array_equal(hdr['voxel_size'], [1, 2, 3])
numpy.testing.assert_array_equal
import csv from collections import defaultdict import json import logging import math import os import time import ctk import numpy as np import qt import scipy.spatial import vtk import slicer from slicer.ScriptedLoadableModule import * from slicer.util import NodeModify # needed for topological sort. Yes, this is ...
np.sign(value)
numpy.sign
import os import sys import numpy as np import tensorflow as tf from tqdm import tqdm from config import cfg from utils import load_data from capsNet import CapsNet import pdb import csv import pandas as pd def save_to(): if not os.path.exists(cfg.results): os.mkdir(cfg.results) if cfg.is_training: ...
np.zeros((cfg.batch_size,))
numpy.zeros
# -*- coding: utf-8 -*- """ Created on Thu Jun 23 00:45:04 2020 @author: <NAME> """ import numpy as np import math '''Beale''' def F1(x): x = np.asarray_chkfinite(x) x1 = x[0] x2 = x[1] s = ((1.5 - x1 + x1 * x2) ** 2.0 + (2.25 - x1 + x1 * x2 ** 2.0) ** 2.0+ (2.625 - x1 + x1 * x2 ** ...
np.asarray_chkfinite(x)
numpy.asarray_chkfinite
# # 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...
np.ones((ldab, n), dtype=float)
numpy.ones
import copy import math import numpy as np from sklearn import metrics import Levenshtein from misc import matching from misc import adapted_utils from misc.constants import UU_FILTER, MU_FILTER, UNC_FILTER, UNC_MAPPING from misc.utils import BColors from misc import utils ## # evaluation utils def calc_scores( ...
np.unique(gt)
numpy.unique
# MIT License # # Copyright (c) 2018-2019 Tskit Developers # Copyright (C) 2016 University of Oxford # # 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 l...
np.linalg.inv(K)
numpy.linalg.inv
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
np.array(expected2)
numpy.array
import os import numpy as np import torch from .metric_computer import MetricComputer from ..common_util.image import get_gt_frame, get_comp_frame from ..models.i3d.pytorch_i3d import InceptionI3d from ..fid import calculate_frechet_distance from ..fid.util import extract_video_features SCRIPT_DIR = os.path.dirname(...
np.cov(gt_clip_features, rowvar=False)
numpy.cov
from utils.env_utils import minigrid_render, minigrid_get_env import os, time import numpy as np import argparse import random import matplotlib.pyplot as plt import pickle5 as pickle from imitation.data import rollout from imitation.util import logger, util from imitation.algorithms import bc import gym import gym...
np.array(obs_list)
numpy.array
from __future__ import print_function from __future__ import division from builtins import zip from builtins import map from builtins import str from builtins import range from past.utils import old_div from future.utils import raise_ import numpy as num import unittest import tempfile import os import sys from anuga.f...
num.ones(n,num.int)
numpy.ones
""" Test module to make sure that simple representations of hyperbolic errors are equivalent to more generalized expressions. """ import numpy as N from scipy.stats import chi2 from ..display.plot.cov_types.regressions import hyperbola from ..orientation.test_pca import random_pca from ..orientation.pca import augment...
N.identity(ndim+1)
numpy.identity
#-*- coding: utf-8 -*- '''utility functions for causality analysis''' import math import numpy as np def _tsdata_to_var(X, p): """ Calculate coefficients and recovariance and noise covariance of the optimized model order. ref: http://users.sussex.ac.uk/~lionelb/MVGC/html/tsdata_to_var.html Parame...
np.zeros((n, p1, m + p, N))
numpy.zeros
""" Plot full light curves, one panel per band Advice on aesthetic from <NAME> this is Fig 3 in the paper """ import matplotlib.pyplot as plt plt.rc("font", family="serif") plt.rc("text", usetex=True) from mpl_toolkits.axes_grid1.inset_locator import inset_axes from mpl_toolkits.axes_grid1.inset_locator import mark_...
np.append(mag, add_mag[choose])
numpy.append
# -*- coding: utf-8 -*- """ Created on Wed Mar 01 11:05:31 2018 @author: willie """ import numpy as np import matplotlib.pyplot as plt from sklearn.ensemble import RandomForestClassifier import time import _pickle as pickle from random import sample import sklearn.metrics as mt class FlagError(Exception): def __...
np.sum(confu_matrix)
numpy.sum
""" utility.py pytracer package Defines global constants and utility functions. Created by Jiayao on Aug 13, 2017 """ from __future__ import absolute_import import numpy as np from pytracer import (FLOAT, INT, UINT, EPS) __all__ = ['progress_reporter','logging','feq', 'eq_unity', 'ne_unity', 'ftoi', 'ct...
np.clip(x, min, max)
numpy.clip
# Copyright (c) 2019-2021, <NAME>, <NAME>, <NAME>, and <NAME>. # # Distributed under the 3-clause BSD license, see accompanying file LICENSE # or https://github.com/scikit-hep/vector for details. import collections.abc import numpy import vector.backends.object_ from vector.methods import ( Azimuthal, Azimut...
numpy.array(*args, **kwargs)
numpy.array
from abc import ABC, abstractmethod import numpy as np from scipy.special import gammaln import numbers from .constants import MIN_POSTERIOR_VARIANCE __all__ = ['Distribution', 'Gamma', 'Uniform', 'Normal', 'LogNormal', 'Horseshoe'] class Distribution(ABC): ...
np.log(self.beta)
numpy.log
from constants import WHOLEBODY_KEYPOINTS, WHOLEBODY_SKELETON, WHOLEBODY_SCORE_WEIGHTS, \ WHOLEBODY_STANDING_POSE from constants import SKELETON_CONNECT, CAR_KEYPOINTS, CAR_SKELETON, CAR_SCORE_WEIGHTS, \ CAR_POSE, HFLIP_ids import networkx as nx import numpy as np import json import pandas as pd import os def...
np.linalg.norm(CAR_POSE[bone[0]]-CAR_POSE[bone[1]])
numpy.linalg.norm
# -*- coding: utf-8 -*- import numpy as np import os from math import ceil from scipy.signal import cont2discrete import json class Acutator(object): def __init__(self, linear): self.linear = linear self.controller = None def initiate_model(self): raise Exception('The _in...
np.array([[0.,1.,0.]])
numpy.array
import unittest import jax import numpy as np from fe import estimator_abfe from timemachine.lib import LangevinIntegrator, potentials, MonteCarloBarostat from parallel.client import CUDAPoolClient from md.barostat.utils import get_bond_list, get_group_indices def get_harmonic_bond(n_atoms, n_bonds): atom_idxs ...
np.arange(n_atoms)
numpy.arange
# Pyhton code to run the ABC-SMC algorithm to parametrise the exponential model with cell generations # making use of OT-I T cells data. # Reference: "Approximate Bayesian Computation scheme for parameter inference and model selection # in dynamical systems" by <NAME>. et al. (2008). # Import the required modules. imp...
np.zeros(dist_gen)
numpy.zeros
import numpy as np from torch.utils.data.sampler import RandomSampler class Customsampler(RandomSampler): def __init__(self, data_source, replacement=False, num_samples=None, batch_size=None, generator=None): super(Customsampler, self).__init__(data_source=data_source, replacement=replacement, ...
np.random.shuffle(tmp)
numpy.random.shuffle
#!/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.arctan2(relative_pos2[1]-relative_pos[1], relative_pos2[0]-relative_pos[0])
numpy.arctan2
import datetime import glob import os import random import shutil import time from hashlib import md5 import cv2 import keras import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import tensorflow as tf from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D from ...
np.argmax(test_gen.y, axis=1)
numpy.argmax
import numpy as np def potential(x,y, mu): return -np.exp(-mu*np.sqrt(np.sum(np.square(y - x), axis = -1))) def forces(x,y, mu): return -mu*(y - x)/(np.finfo(float).eps+np.sqrt(np.sum(np.square(y - x), \ axis = -1, keepdims = True)))*np.exp(-mu*np.sqrt(np.sum(np.square(y - x), axis = -1, ke...
np.zeros((n_samples,1))
numpy.zeros
from __future__ import division, absolute_import, print_function try: # Accessing collections abstract classes from collections # has been deprecated since Python 3.3 import collections.abc as collections_abc except ImportError: import collections as collections_abc import tempfile import sys import sh...
assert_array_equal(a['k'][-5:], 0)
numpy.testing.assert_array_equal
"""Unit tests for the one.alf.io module""" import logging import unittest import tempfile from pathlib import Path import shutil import json import numpy as np import pandas as pd from iblutil.io import jsonable import one.alf.io as alfio from one.alf.exceptions import ALFObjectNotFound from one.alf.spec import FILE...
np.all(df['tata_0'].values == vectors.tata[:, 0])
numpy.all
# Copyright 2017 <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 writing, software ...
np.mean(results[en])
numpy.mean
from __future__ import print_function import os, sys, gc #from time import time #from copy import deepcopy import numpy as np #import numpy.linalg as la from warnings import warn from Kuru import FunctionSpace, QuadratureRule #from Florence.Base import JacobianError, IllConditionedError #from Florence.Utils import PWD,...
np.eye(3,3,dtype=np.float64)
numpy.eye
import numpy as np from matplotlib import pyplot as plt import keyboard size = 15 # random map generator mapa = [[list(np.random.uniform(0, 1, 3))] * size for i in range(size)] mapah = [[1] * size for i in range(size)] for i in range(size-2): for j in range(size-2): mapah[i+1][j+1] = np.random.cho...
np.asarray([0.5,0.5,1])
numpy.asarray
import numpy as np from deicode._optspace import optspace from .base import _BaseImpute from scipy.spatial import distance import warnings class OptSpace(_BaseImpute): def __init__(self, rank=2, iteration=5, tol=1e-5): """ OptSpace is a matrix completion algorithm based on a singular value ...
np.min(X_sparse.shape)
numpy.min
import unittest import numpy as np from nptest import nptest class MathematicalFunctionsTests(unittest.TestCase): #region Trigonometric Functions def test_sin_1(self): a = np.arange(0, 10, dtype = np.float64) a = a[::2] b = np.sin(a) print(b) a = np.arange(0, 10, dty...
np.remainder([-4, -7], [2, 3])
numpy.remainder
#!/usr/bin/env python3 import numpy import re import itertools import json from collections import OrderedDict from os import listdir, getcwd, stat, path from os.path import isfile, join import copy import warnings from urllib.parse import urlparse import gzip import pickle from functools import reduce # forward compa...
numpy.where(perf_meas < 0)
numpy.where
# Copyright 2020 Forschungszentrum Jülich GmbH and Aix-Marseille Université # "Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements; and to You under the Apache License, Version 2.0. " import tvb.simulator.lab as lab from nest_elephant_tvb.Tvb.modify_tvb.test_interface imp...
np.sum(diff)
numpy.sum
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Tests for the groupstars module. """ from astropy.table import Table, vstack import numpy as np from numpy.testing import assert_almost_equal import pytest from ..groupstars import DAOGroup, DBSCANGroup try: import sklearn.cluster # noqa HA...
np.sqrt(2)
numpy.sqrt
# -*- coding: utf-8 -*- """ Tests for Results.predict """ import numpy as np import pandas as pd from numpy.testing import assert_allclose, assert_equal import pandas.util.testing as pdt from statsmodels.regression.linear_model import OLS from statsmodels.genmod.generalized_linear_model import GLM class CheckPredi...
np.random.randn(nobs)
numpy.random.randn
""" A few different backtracking line search subsolvers. BoundsEnforceLS - Only checks bounds and enforces them by one of three methods. ArmijoGoldsteinLS -- Like above, but terminates with the ArmijoGoldsteinLS condition. """ import sys import numpy as np from openmdao.core.analysis_error import AnalysisError from...
np.isscalar(var_upper)
numpy.isscalar
# 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.array(token.array)
numpy.array
def transform(dataset, SX=0.5, SY=0.5, SZ=0.5, noise=15.0): """Deblur Images with a Weiner Filter.""" import numpy as np from numpy import exp, square, pi from scipy.fftpack import fftn, ifftn, fftshift #Import information from dataset array = dataset.active_scalars dim = array.shape ...
square(pi)
numpy.square
import unittest import numpy as np from probnum.diffeq.ode import ivp, ivp_examples from probnum.random_variables import Constant from tests.testing import NumpyAssertions class TestConvenienceFunction(unittest.TestCase): """Test case for correct object initialization.""" def setUp(self): self.tspa...
np.ones(2)
numpy.ones
# Copyright (c) OpenMMLab. All rights reserved. import copy import os.path as osp import pickle from abc import ABCMeta, abstractmethod import json_tricks as json import numpy as np from scipy.io import loadmat from torch.utils.data import Dataset from mmpose.datasets import DatasetInfo from mmpose.datasets.pipelines...
np.array(cam['k'], dtype=np.float32)
numpy.array
#!/usr/bin/python3 import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import os import sys import pprint import numpy as np import pickle import itertools import config from agents.learning import LearningAgent from environment.bandit import Bandit from experiments.experiment import Experiment, P...
np.std(cumulative_regret_exp_lta, 0)
numpy.std
# -*- coding: utf-8 -*- # Copyright (C) 2017 AGB # Full license can be found in LICENSE.txt # --------------------------------------------------------------------------- """ Perform OCB gridding for SuperMAG data Functions --------- supermag2ascii_ocb(smagfile, outfile, kwargs) Write and ASCII file with SuperMAG ...
np.array(out[k], dtype=str)
numpy.array
# test_basic.py: some basic tests of the code import numpy numpy.random.seed(2) from extreme_deconvolution import extreme_deconvolution def test_single_gauss_1d_nounc(): # Generate data from a single Gaussian, recover mean and variance ndata= 3001 ydata= numpy.atleast_2d(numpy.random.normal(size=ndata)).T ...
numpy.fabs(initcovar-1.)
numpy.fabs
import numpy as np import cv2 import matplotlib.pyplot as plt # Identify pixels above the threshold # Threshold of RGB > 160 does a nice job of identifying ground pixels only def color_thresh(img, rgb_thresh=(160, 160, 160)): # Create an array of zeros same xy size as img, but single channel color_select =
np.zeros_like(img[:,:,0])
numpy.zeros_like
import cv2 import numpy as np import calib.corner_kernels as ck from math import pi, tan from skimage.feature import peak_local_max def compute_corner_kernel_whole(size, offset=0.0): kern = np.zeros((size, size), dtype=np.uint8) half = size // 2 factor = 255 / ((half - offset) * (half - offset)) for r...
np.array(detected_corners)
numpy.array
import numpy as np import pandas as pd import scipy.interpolate as si import chart_studio.plotly as py # import plotly.graph_objs as go from plotly.graph_objs import * from rho_factor.config import * class rho: def __init__(self, df=None, wl=None): self.df = df self.aot = 0.1 self.ws = 2 ...
np.cos(2 * theta)
numpy.cos
import time from typing import List, Dict, Optional, Tuple import numpy as np import pickle import rl_env import os import torch import torchvision import rulebased_agent as ra from internal_agent import InternalAgent from outer_agent import OuterAgent from iggi_agent import IGGIAgent from legal_random_agen...
np.array(source['actions'])
numpy.array
import argparse import numpy as np import os import tabulate import torch import torch.nn.functional as F from torch.nn.utils import vector_to_parameters, parameters_to_vector import data import models import curves import utils parser = argparse.ArgumentParser(description='DNN curve evaluation') parser.add_argument...
np.min(values)
numpy.min
def etiquetar(): rotulo_Liquido = "Composición de fase líquido" rotulo_Vapor = "Composición de fase vapor" rotulo_Separador = "-" * 11 etiqueta_liquido = "{0}{1}{0}".format(rotulo_Separador, rotulo_Liquido) etiqueta_vapor = "{0}{1}{0}".format(rotulo_Vapor, rotulo_Vapor) return etiqueta_liquid...
np.max(ZfvR)
numpy.max
import numpy as np import time from keras.utils import np_utils from keras.preprocessing.image import transform_matrix_offset_center, apply_transform np.random.seed(int((time.time()*1e6)%1e6)) def rotation(x, theta, row_axis=0, col_axis=1, channel_axis=2, fill_mode='wrap', cval=0.): rotation_...
np.sin(theta)
numpy.sin
# this script trains 3 different classifiers # stores the model weights in pickle files PATH_TO_FACES = './models/eigenfaces.pickle' PATH_TO_TRAINING_PERSON_1 = './data/training_faces/person_1/' PATH_TO_TRAINING_PERSON_2 = './data/training_faces/person_2/' PATH_TO_KNN_MODEL = './models/knn_model.pickle' PATH_TO_SVM_MOD...
np.transpose(item)
numpy.transpose
# -*- coding: utf-8 -*- """ Created on Sat Jul 14 11:14:16 2018 @author: SilverDoe """ # Import `datasets` from `sklearn` from sklearn import datasets,svm,metrics from pprint import pprint # Load in the `digits` data digits = datasets.load_digits() # Print the `digits` data pprint(digits) # Get the keys of the `...
np.unique(digits.target)
numpy.unique
import pytest import numpy as np from scipy.interpolate import interpn from ardent.utilities import _validate_xyz_resolution from ardent.utilities import _compute_axes from ardent.utilities import _compute_coords from ardent.preprocessing.resampling import _resample from ardent.preprocessing.resampling import _downsa...
np.arange(3*11)
numpy.arange
import numpy as np np.set_printoptions(precision=4, suppress=True) from BN import * ev = (1,1,1,1,1) p1 = Node(
np.array([.001])
numpy.array
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Nov 25 11:55:07 2020 @author: ja17375 """ import EnsembleVisualiser import plotly.graph_objs as go import matplotlib.pyplot as plt import mplstereonet from numpy import deg2rad, rad2deg, sin, cos import numpy as np from skimage import measure from mpl_t...
np.linspace(0, 0.02, 50)
numpy.linspace
from coopihc.space.State import State from coopihc.space.StateElement import StateElement from coopihc.space.Space import Space from coopihc.space.utils import discrete_space, multidiscrete_space, continuous_space import numpy from collections import OrderedDict state = State() substate = State() substate["x1"] = Sta...
numpy.ones((3, 3))
numpy.ones
# __author__ = 'Hochikong' from __future__ import absolute_import from __future__ import print_function from keras.models import Sequential from keras.layers import Dense, Activation, Dropout, Embedding, LSTM from keras.utils import plot_model from configparser import ConfigParser import matplotlib.pyplot as plt # impo...
numpy.array(test_Y, dtype=int)
numpy.array
#!/usr/bin/env python3 """ Scrapes the HF logs passed in via a glob string and calculates the amount of core hours lost to thread idling Takes in a single or glob path to HF log files. """ import argparse from datetime import datetime from glob import glob import numpy as np def get_duration_and_dead_ratio(file_na...
np.logical_and(fault_mask, outliers)
numpy.logical_and
# ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. # ------------------------------------ import seaborn as sns import matplotlib matplotlib.use("agg") import matplotlib.pyplot as pp # noqa: E402 from matplotlib import cm # noqa: E402 import numpy as np #...
np.transpose(res.PREDICT[locs, :], [2, 0, 1])
numpy.transpose
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
np.allclose(res[1], 2)
numpy.allclose
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # BCDI: tools for pre(post)-processing Bragg coherent X-ray diffraction imaging data # (c) 07/2017-06/2019 : CNRS UMR 7344 IM2NP # (c) 07/2019-present : DESY PHOTON SCIENCE # authors: # <NAME>, <EMAIL> import tkinter as tk from tkinter import filedialog...
np.isnan(diff_strain)
numpy.isnan
import numpy as np import tensorflow as tf from tensorflow.keras import layers from tensorflow import keras from tensorflow.keras.layers import Activation, Dense from tensorflow.keras.optimizers import RMSprop from sklearn.impute import SimpleImputer from sklearn import preprocessing from sklearn.decomposition import ...
np.zeros(40)
numpy.zeros
# -*- coding: utf-8 -*- """ @author: <NAME> The work is licensed under the MIT licence, for more details: https://github.com/LiorReznik/Mde-release-1/blob/master/LICENSE """ import numpy as np import os, pickle from collections import OrderedDict import urllib,zipfile from stanza.server import ...
np.zeros(dims)
numpy.zeros
from vmad import autooperator, operator from vmad.core import stdlib from vmad.lib import fastpm from vmad.lib import linalg from vmad.lib.fastpm import FastPMSimulation, ParticleMesh import numpy from vmad.lib.linalg import sum, mul import scipy from mpi4py import MPI import numpy as np import MADLens.PGD as PGD from...
np.asarray([0,1,0],dtype=int)
numpy.asarray
from numpy import array, matrix, zeros, linspace, arange # from matplotlib.pyplot import * import scipy.linalg import matplotlib.pyplot as plt from matplotlib.pyplot import plot, figure, xlim, ylim, title, xlabel, ylabel, show import numpy as np plt.rcParams['figure.figsize'] = (10, 8) # (width, height) def cst_fem...
zeros((6, 1))
numpy.zeros
import numpy as np import pandas as pd import pickle import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torchvision from torchvision import datasets, transforms from torch.autograd import Variable import torch.utils.data as data import os class synth_data2(data.Datas...
np.random.uniform(-args['delta'],args['delta'],size=(args['d']))
numpy.random.uniform
# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE from __future__ import absolute_import import pytest # noqa: F401 import numpy as np # noqa: F401 import awkward as ak # noqa: F401 def test(): layout = ak.layout.ListOffsetArray64( ak.layout.Index64(np.array([0, ...
np.array([0, 1, 2, 3], dtype=np.int64)
numpy.array
# -*- coding: utf-8 -*- import os import re import yaml import numpy as np from tensorflow.keras.layers import Input, Embedding, LSTM, Dense from tensorflow.keras.models import Model from tensorflow.keras import preprocessing, utils from flask import Flask, render_template, request app = Flask(__name__) @app.route(...
np.argmax(dec_outputs[0, -1, :])
numpy.argmax
import numpy as np from utils import system import pdb import matplotlib.pyplot as plt from ftocp import FTOCP from nlp import NLP from matplotlib import rc from numpy import linalg as la # rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']}) # rc('text', usetex=True) # ============================= # Initi...
np.eye(d)
numpy.eye
from __future__ import print_function import numpy as np import time, os, sys import matplotlib.pyplot as plt from scipy import ndimage as ndi from skimage import color, feature, filters, io, measure, morphology, segmentation, img_as_ubyte, transform import warnings import math import pandas as pd import argparse impor...
np.array(LowCaps['Cap'])
numpy.array
import numpy as np import matplotlib import matplotlib.pyplot as plt import matplotlib.animation as animation import matplotlib.cm as cm import gym import cv2 import sys class AtariGame(object): """Environment wrapper for Atari Pong. This class simplifies the interaction of the agent with the Pong environ...
np.copy(obs)
numpy.copy
from unittest.mock import Mock import numpy as np from shfl.data_base.data_base import DataBase from shfl.data_distribution.data_distribution_iid import IidDataDistribution from shfl.federated_aggregator.iowa_federated_aggregator import IowaFederatedAggregator from shfl.federated_government.iowa_federated_government ...
np.testing.assert_array_equal(iowa_fg.performance_clients.call_args[0][1], validation_label)
numpy.testing.assert_array_equal
"""SMEFT beta functions""" import numpy as np from collections import OrderedDict from wilson.util.smeftutil import C_keys, C_keys_shape, C_array2dict, C_dict2array from functools import lru_cache I3 = np.identity(3) class HashableArray(np.ndarray): def __new__(cls, data, dtype=None): return np.array(d...
np.conj(Gu)
numpy.conj
import heatsim2 import copy import cProfile import numpy as np numpy=np import pylab as pl import scipy as sp import scipy.interpolate # define materials: composite_rho=1.75e3 # kg/m^3 composite_c=730.0 # J/kg/deg K ## Use these values for (roughly) quasi-isotropic layup specimens #composite_k=3.7 # W/m/deg K #max...
np.arange(tsr_num_predefknots-2,dtype='d')
numpy.arange
# # Beeler-Reuter model for mammalian ventricular action potential. # # This file is part of PINTS. # Copyright (c) 2017-2019, University of Oxford. # For licensing information, see the LICENSE file distributed with the PINTS # software package. # from __future__ import print_function import numpy as np import pints...
np.exp(-0.25 * (V + 78))
numpy.exp
#!/usr/bin/env python # coding: utf-8 ''' Author: <NAME> License: Apache 2.0 ''' import os import argparse import pandas as pd import numpy as np from sklearn.preprocessing import StandardScaler, MinMaxScaler, LabelEncoder from sklearn.pipeline import Pipeline from sklearn.model_selection import GroupShuffleSplit im...
np.array(b)
numpy.array
from __future__ import print_function import os import argparse import torch import torch.nn as nn import torch.optim as optim from torch.optim.lr_scheduler import CosineAnnealingLR from util.data_util import ModelNet40 from model.GDANet_cls import GDANET import numpy as np from torch.utils.data import DataLoader from ...
np.concatenate(test_true)
numpy.concatenate
#!/usr/bin/env python ############################################################################### # # Primary code to perform RING-MaP analysis on ShapeMapper output files # # See README for further details # Run with -h flag for arguments # # Lead developer: <NAME> # Contributors: <NAME>, <NAME> # # Thi...
np.log(n)
numpy.log
#!/usr/bin/env python # encoding: utf-8 from __future__ import division import numpy as np from scipy.interpolate import interp1d from . import model __author__ = '<NAME>' class AbrahamsonSilvaKamai2014(model.Model): """Abrahamson, Silva, and Kamai (2014, :cite:`abrahamson14`) model. This model was devel...
np.log(dist)
numpy.log
# -*- coding: utf-8 -*- import os import pickle import random import argparse import torch as t import numpy as np import resource from tqdm import tqdm from torch.optim import SGD from torch.utils.data import Dataset, DataLoader from model import SkipGramNeg #from data_utils import build_dataset, DataPipeline #os.e...
np.vstack([neg, delta])
numpy.vstack
# coding: utf-8 # In[14]: import os os.environ['CUDA_VISIBLE_DEVICES'] = '1' # In[15]: import numpy as np import os import sys import matplotlib.pyplot as plt get_ipython().magic(u'matplotlib inline') from skimage.transform import rescale, resize from tqdm import tqdm import cv2 import random # In[16]: from...
np.ceil(input_shape[1] / 4)
numpy.ceil
#!/usr/bin/env python2 # -*- coding: utf-8 -*- # ---------------------------------------------------------------------------------------------------------------------- # ROS-MAGNA # ---------------------------------------------------------------------------------------------------------------------- # The MIT License ...
np.arange(poses_set_def["dimensions"][2])
numpy.arange
import test_helpers import numpy as np import pytest from trecs.components import Users, Items from trecs.models import SocialFiltering, ContentFiltering, PopularityRecommender, BassModel from trecs.metrics import ( InteractionSpread, MSEMeasurement, DiffusionTreeMeasurement, StructuralVirality, Int...
np.random.randint(2, 100)
numpy.random.randint
# Copyright 2022 The Brax 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 applicable law or agreed to in wri...
np.radians(a)
numpy.radians
#!/usr/bin/env python3 """ @author: <NAME> """ import numpy.testing as nt import numpy as np import roboticstoolbox as rp import spatialmath as sm import unittest import math class TestDHRobot(unittest.TestCase): def test_DHRobot(self): l0 = rp.DHLink() rp.DHRobot([l0]) def test_prismaticjoi...
nt.assert_array_almost_equal(M0, Mr, decimal=4)
numpy.testing.assert_array_almost_equal
import os import yaml import time import torch from mesh_data import PointCloudData from pathlib import Path import argparse import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torch.backends.cudnn as cudnn import torch.distributed as dist from torch.utils.data import DataLoader fro...
np.array([1e10] * B)
numpy.array
from numpy import allclose, hstack, vstack, zeros from quadprog import solve_qp """ Solve a Quadratic Program defined as minimize (1/2) * x.T * H * x + g.T * x subject to C * x <= d A * x == b The solution is saved and returned in QPSolution object def <solver>Wrapper(H, g, C, d, A, b, initvals) :param H : numpy.array...
hstack([b, d])
numpy.hstack