prompt stringlengths 19 879k | completion stringlengths 3 53.8k | api stringlengths 8 59 |
|---|---|---|
# Lint as: python3
# Copyright 2019 DeepMind Technologies Limited. 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
#
# ... | np.array(generated_vals) | numpy.array |
# -*- coding: utf-8 -*-
import numpy as np
import time
# Rotating hyperplane dataset
def create_hyperplane_dataset(n_samples, n_dim=2, plane_angle=0.45):
w = np.dot(np.array([[np.cos(plane_angle), -np.sin(plane_angle)], [np.sin(plane_angle), | np.cos(plane_angle) | numpy.cos |
"""Functions copypasted from newer versions of numpy.
"""
from __future__ import division, print_function, absolute_import
import warnings
import sys
import numpy as np
from numpy.testing.nosetester import import_nose
from scipy._lib._version import NumpyVersion
if NumpyVersion(np.__version__) > '1.7.0.dev':
_... | np.array(array, copy=False, subok=subok) | numpy.array |
from linlearn import BinaryClassifier, MultiClassifier
from linlearn.robust_means import Holland_catoni_estimator, gmom, alg2
import numpy as np
import gzip
import logging
import pickle
from datetime import datetime
import sys
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
from scipy.special ... | np.random.randint(X.shape[0]) | numpy.random.randint |
import numpy as np
import scipy.stats
import os
import logging
from astropy.tests.helper import pytest, catch_warnings
from astropy.modeling import models
from astropy.modeling.fitting import _fitter_to_model_params
from stingray import Powerspectrum
from stingray.modeling import ParameterEstimation, PSDParEst, \
... | np.ones(nsim) | numpy.ones |
"""Test correlation and distance correlation estimators."""
import numpy as np
from frites.estimator import CorrEstimator, DcorrEstimator
array_equal = np.testing.assert_array_equal
class TestCorrEstimator(object):
def test_corr_definition(self):
"""Test definition of correlation estimator."""
... | np.random.rand(100) | numpy.random.rand |
# Copyright 2018 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd
from __future__ import absolute_import
from __future__ import division
from __future__ import p... | np.array(y_test) | numpy.array |
# Copyright (c) 2017 <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, ... | ndpointer(dtype=c_int32) | numpy.ctypeslib.ndpointer |
import argparse
import os
import pickle as pkl
import numpy as np
import scipy.sparse as smat
from pecos.core.base import clib
from pecos.utils import smat_util
from pecos.utils.cluster_util import ClusterChain
from pecos.xmc import MLModel
from pecos.xmc.xlinear import XLinearModel
def parse_arguments():
parser... | np.intersect1d(S1, K1) | numpy.intersect1d |
# This module has been generated automatically from space group information
# obtained from the Computational Crystallography Toolbox
#
"""
Space groups
This module contains a list of all the 230 space groups that can occur in
a crystal. The variable space_groups contains a dictionary that maps
space group numbers an... | N.array([1,2,2]) | numpy.array |
"""
Implement optics algorithms for optical phase tomography using GPU
<NAME> <EMAIL>
<NAME> <EMAIL>
October 22, 2018
"""
import numpy as np
import arrayfire as af
import contexttimer
from opticaltomography import settings
from opticaltomography.opticsmodel import MultiTransmittance, MultiPhaseContrast
from op... | np.array(fields["back_scattered_field"]) | numpy.array |
# coding: utf-8
# ### Compute results for task 1 on the humour dataset.
#
# Please see the readme for instructions on how to produce the GPPL predictions that are required for running this script.
#
# Then, set the variable resfile to point to the ouput folder of the previous step.
#
import string
import pandas as p... | np.unique(pair_ids) | numpy.unique |
# -*- coding: utf-8 -*-
from . import plot_settings as pls
from . import plots as pl
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import logging
from matplotlib.colors import LinearSegmentedColormap, colorConverter
from scipy.stats.kde import gaussian_kde
try:
from scipy... | np.atleast_1d(x) | numpy.atleast_1d |
from __future__ import division
import pytest
import numpy as np
import cudf as pd
import fast_carpenter.masked_tree as m_tree
@pytest.fixture
def tree_no_mask(infile, full_event_range):
return m_tree.MaskedUprootTree(infile, event_ranger=full_event_range)
@pytest.fixture
def tree_w_mask_bool(infile, event_rang... | np.where(mask) | numpy.where |
import pytest
import numpy as np
from numpy.testing import assert_array_almost_equal
from sklearn.metrics.tests.test_ranking import make_prediction
from sklearn.utils.validation import check_consistent_length
from mcc_f1 import mcc_f1_curve
def test_mcc_f1_curve():
# Test MCC and F1 values for all points of the... | np.array([1 if di == 0 else di for di in d]) | numpy.array |
import re
import os
import numpy as np
import pandas as pd
import scipy.stats as sps
pd.options.display.max_rows = 4000
pd.options.display.max_columns = 4000
def write_txt(str, path):
text_file = open(path, "w")
text_file.write(str)
text_file.close()
# SIR simulation
def sir(y, alpha, beta, gamma, nu,... | np.diff(r) | numpy.diff |
import numpy as np
import matplotlib.pyplot as plt
import os
import warnings
from datetime import date
from math import e
def calc_rate(data1, data2):
if(data2 == 0):
return data1
else:
if(data1 < data2):
return (data2 / data1) * -1
else:
return data1 / data2
de... | np.set_printoptions(precision=3) | numpy.set_printoptions |
################################################################################
# Copyright (c) 2009-2019, National Research Foundation (Square Kilometre Array)
#
# Licensed under the BSD 3-Clause License (the "License"); you may not use
# this file except in compliance with the License. You may obtain a copy
# of the... | np.sqrt(1.0 + 2.0 * e2 ** 2 * P) | numpy.sqrt |
import os
import numpy as np
import pandas as pd
import tensorflow as tf
from scipy import stats
from tensorflow.keras import layers
from matplotlib import pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler,OneHotEncoder
from itertools import product
from... | np.arange(length2) | numpy.arange |
"""
See explanation below in the __name__ guard.
"""
from cartpole import Controller, CartPole, simulate, G
from nominal_control import ControlLQR
import numpy as np
from qpsolvers import solve_qp
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import matplotlib.animation as an... | np.cos(state[2]) | numpy.cos |
import os, sys, random, time, copy
from skimage import io, transform
import numpy as np
import scipy.io as sio
from scipy import misc
import matplotlib.pyplot as plt
import PIL.Image
import skimage.transform
import blosc, struct
import torch
from torch.utils.data import Dataset, DataLoader
import torch.nn as nn
impo... | np.expand_dims(ib_np, 2) | numpy.expand_dims |
import numpy as np
from scipy.optimize import root_scalar
class sieplasmajet(object):
def __init__(self, theta_E_g, eta, phi, psi0_plasma_num, theta_0_num, B, C, delta_rs, deltab_10, deltab_20):
self.theta_E_g = theta_E_g
self.eta = eta
self.phi = phi
self.psi0_plasma_num = psi0_pl... | np.sin(phi) | numpy.sin |
import numpy as np
import lsst.pex.config as pexConfig
import lsst.afw.image as afwImage
import lsst.afw.math as afwMath
import lsst.pipe.base as pipeBase
import lsst.pipe.base.connectionTypes as cT
from .eoCalibBase import (EoAmpPairCalibTaskConfig, EoAmpPairCalibTaskConnections,
EoAmpPair... | np.abs((pd1 - pd2)/((pd1 + pd2)/2.)) | numpy.abs |
# @Author: lshuns
# @Date: 2021-04-05, 21:44:40
# @Last modified by: lshuns
# @Last modified time: 2021-05-05, 8:44:30
### everything about Line/Point plot
__all__ = ["LinePlotFunc", "LinePlotFunc_subplots", "ErrorPlotFunc", "ErrorPlotFunc_subplots"]
import math
import logging
import numpy as np
import matplotl... | np.array(yerr) | numpy.array |
from PyUnityVibes.UnityFigure import UnityFigure
import time, math
import numpy as np
# Function of the derivative of X
def xdot(x, u):
return np.array([[x[3, 0]*math.cos(x[2, 0])], [x[3, 0]*math.sin(x[2, 0])], [u[0, 0]], [u[1, 0]]])
# Function witch return the command to follow to assure the trajectory
def contr... | np.array([[10], [0], [1], [1]]) | numpy.array |
# -*- coding: utf-8 -*-
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""
The rapidart module provides routines for artifact detection and region of
interest analysis.
These functions include:
* ArtifactDetect: performs artifact detection on functi... | np.zeros((x, y, z, timepoints), dtype=np.float64) | numpy.zeros |
import numpy as np
def getClosestFactors(n):
i = int(n ** 0.5)
while (n % i != 0):
i -= 1
return (i, int(n/i))
def getBoundary(x, r, n):
"""returns in the form [lower, upper)"""
lower = x - r
upper = x + r + 1
if lower < 0:
lower = 0
if upper > n:
... | np.full(grid1.shape[1], -1) | numpy.full |
import concurrent.futures
import enum
import itertools
import json
import logging
from pathlib import Path
import cv2
import hydra
import numpy as np
import scipy.interpolate
import tifffile
from omegaconf import OmegaConf, DictConfig
from tqdm import tqdm
CONFIG_FILE = 'config.yaml'
class DistortMode(enum.Enum):
... | np.meshgrid(xs, ys) | numpy.meshgrid |
import numpy as np
from epimargin.models import SIR
from epimargin.policy import PrioritizedAssignment
from studies.age_structure.commons import *
mp = PrioritizedAssignment(
daily_doses = 100,
effectiveness = 1,
S_bins = np.array([
[10, 20, 30, 40, 50, 50, 60],
[10, 20, 30, 40... | np.array([0.01, 0.01, 0.01, 0.02, 0.02, 0.03, 0.04]) | numpy.array |
from copy import deepcopy
from numpy import sin, cos, pi, tan, arctan, array, arctan2, square, arcsin, savetxt
from math import pi, inf, sqrt, radians
def fk(q):
# Geometry
a1 = 0.235
a2 = 0.355
a4 = 0.20098
a5 = 0.345
d1 = 0.505
d5 = 0.00837
d6 = 0.6928
# DH table
dh = array(... | sin(q_2) | numpy.sin |
import numpy as np
import pandas as pd
import scipy.stats as stats
from sklearn import decomposition as decomp
from scRNA.abstract_clustering import AbstractClustering
from scRNA.utils import center_kernel, normalize_kernel, kta_align_binary, \
get_matching_gene_inds, get_transferred_data_matrix, get_transferabili... | np.float(X.size) | numpy.float |
#
# Copyright (c) 2021, NVIDIA CORPORATION.
#
# 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.random.rand(size) | numpy.random.rand |
import copy
import functions.setting.setting_utils as su
from joblib import Parallel, delayed
import json
import logging
import multiprocessing
import numpy as np
import os
import time
def search_indices(dvf, c, class_balanced, margin, dim_im, torso):
"""
This function searches for voxels based on the ClassBa... | np.shape(dvf_list[ish[i, 1]]) | numpy.shape |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# # PyKOALA: KOALA data processing and analysis
# by <NAME> and <NAME>
# Extra work by <NAME> (MQ PACE student)
# Plus Taylah and Matt (sky subtraction)
from __future__ import absolute_import, division, print_function
from past.utils import old_div
version = "Version 0.72 - 13t... | np.nanmedian(ratio_object_sky_sl_gaussian) | numpy.nanmedian |
#===========================================#
# #
# #
#----------CROSSWALK RECOGNITION------------#
#-----------WRITTEN BY N.DALAL--------------#
#-----------------2017 (c)------------------#
# ... | np.array([255,255,255]) | numpy.array |
'''
This script reads the results of the previous script, 4_DictL_generate_test_commands.py, and prepare a graph that shows the
statistics of the DictL test runs (for Fig5 in the paper).
(c) <NAME>, UC Berkeley, 2021
'''
import numpy as np
import matplotlib.pyplot as plt
R = np.array([4])
N_examples = 1... | np.zeros((N_examples,pad_ratio_vec.shape[0],sampling_type_vec.shape[0])) | numpy.zeros |
# -*- coding: utf-8 -*-
"""
Copyright Netherlands eScience Center
Function : Forecast Lorenz 84 model - Train BayesConvLSTM model
Author : <NAME>
First Built : 2020.03.09
Last Update : 2020.04.12
Library : Pytorth, Numpy, NetCDF4, os, iris, cartopy, dlacs, matplotlib
Description : This notebook serves... | np.amin(y) | numpy.amin |
import tensorflow.keras.backend as K
import tensorflow as tf
import numpy as np
import cv2
from tensorflow.keras.callbacks import Callback
from .utils import parse_annotation,scale_img_anns,flip_annotations,make_target_anns, decode_netout, drawBoxes, get_bbox_gt, get_boxes,list_boxes,remove_boxes
import math
fro... | np.array([]) | numpy.array |
import numpy as np
import scipy.stats
from scipy import ndimage
from scipy.optimize import curve_fit
from imutils import nan_to_zero
# try to use cv2 for faster image processing
try:
import cv2
cv2.connectedComponents # relatively recent addition, so check presence
opencv_found = True
except (ImportErro... | np.sum(im > 0) | numpy.sum |
import io
import os
import zipfile
import numpy as np
from PIL import Image
from chainer.dataset import download
def get_facade():
root = download.get_dataset_directory('study_chainer/facade')
npz_path = os.path.join(root, 'base.npz')
url = 'http://cmp.felk.cvut.cz/~tylecr1/facade/CMP_facade_DB_base.zip'
... | np.asarray(label) | numpy.asarray |
from ctypes import *
import numpy as np
import math
import keyboard
import matplotlib.pyplot as pl
from mpl_toolkits.mplot3d import Axes3D
class infoformat(Structure):
_fields_ = [\
("posx",c_double),("posy",c_double),("posz",c_double),\
("velocityx",c_double),("velocityy",c_double),("velocityz",... | np.sin(A) | numpy.sin |
import numpy as np
from numpy.linalg import lstsq
from numpy.testing import (assert_allclose, assert_equal, assert_,
run_module_suite, assert_raises)
from scipy.sparse import rand
from scipy.sparse.linalg import aslinearoperator
from scipy.optimize import lsq_linear
A = np.array([
[0.17... | np.array([0.773]) | numpy.array |
'''
Name: load_ops.py
Desc: Input pipeline using feed dict method to provide input data to model.
Some of this code is taken from <NAME>'s colorzation github
and python caffe library.
Other parts of this code have been taken from <NAME>'s library
'''
from __future__ import absolu... | np.zeros((4,4)) | numpy.zeros |
import os, sys
import pickle, warnings
import pandas as pd
import numpy as np
import pmdarima as pm
from sklearn.linear_model import LinearRegression
# Working directory must be the higher .../app folder
if str(os.getcwd())[-3:] != 'app': raise Exception(f'Working dir must be .../app folder and not "{os.getcwd()}"')
f... | np.isnan(out) | numpy.isnan |
"""
Double Integrator with noise in observations.
"""
import math
import gym
from gym import spaces, logger
from gym.utils import seeding
import numpy as np
import scipy.stats as stats
import sympy as sp
import numpy as np
from sympy.physics.vector import dynamicsymbols as dynamicsymbols
import IPython as ipy
from fil... | np.diag(self.x0_belief_std_dev**2) | numpy.diag |
import unittest
import numpy
from cqcpy import test_utils
import cqcpy.spin_utils as spin_utils
import cqcpy.cc_equations as cc_equations
class CCRDMTest(unittest.TestCase):
def setUp(self):
pass
def test_1rdm_opt(self):
no = 4
nv = 8
thresh = 1e-12
T1, T2 = test_util... | numpy.einsum('cdab,abcd->', PcDaB_u, Aab.vvvv) | numpy.einsum |
"""utils for interpreting variant effect prediction for Heritability
"""
import gzip
import os
import sys
from collections import defaultdict
import h5py
import numpy as np
import pandas as pd
def read_vep(vep_dir, check_sanity=False):
_label_fn = [x for x in os.listdir(vep_dir) if x.endswith("_row_labels.txt")... | np.max(vep_data[_annot_idx, label_idx]) | numpy.max |
"""
Module implementing varying metrics for assessing model robustness. These fall mainly under two categories:
attack-dependent and attack-independent.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import config
import numpy as np
import numpy.linalg as la
import tensorflow as... | np.min([-g_x0[0] / loc2, r]) | numpy.min |
# -*- coding: utf-8 -*-
"""
@author: <NAME>
"""
from __future__ import print_function
import time
import numpy as np
_EPS = 1e-14
def mstamp(seq, sub_len, return_dimension=False):
""" multidimensional matrix profile with mSTAMP (stamp based)
Parameters
----------
seq : numpy matrix, shape (n_dim, ... | np.fft.ifft(product_freq) | numpy.fft.ifft |
''' Recurrent Models of Visual Attention
https://papers.nips.cc/paper/5542-recurrent-models-of-visual-attention.pdf
'''
from scipy.misc import imresize as resize
from minpy.nn.model_builder import *
from minpy.nn.modules import *
class CoreNetwork(Model):
def __init__(self):
super(CoreNetwork, self).... | np.pad(images, ((0, 0), (d, d), (d, d)), mode='edge') | numpy.pad |
import matplotlib.pyplot as plt
import numpy as np
class BanditEnv:
def __init__(self, actions):
self.q_star = [np.random.randn() for i in range(actions)]
self.best_action = | np.argmax(self.q_star) | numpy.argmax |
# *_*coding:utf-8 *_*
import os
import sys
from os import makedirs
from os.path import exists, join
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = os.path.dirname(BASE_DIR)
sys.path.append(BASE_DIR)
sys.path.append(os.path.join(ROOT_DIR, 'models'))
sys.path.append(os.path.join(ROOT_DIR, 'utils'))
from... | np.insert(probs, l_ind, 0, axis=1) | numpy.insert |
from __future__ import print_function
import matplotlib
matplotlib.use('Agg')
import pylab as plt
import numpy as np
import os
import sys
from astrometry.util.fits import fits_table
from astrometry.libkd.spherematch import match_radec
from astrometry.util.plotutils import PlotSequence
from legacyanalysis.ps1cat impor... | np.median(ccds.mdiff[J]) | numpy.median |
"""
Module of functions involving great circles
(thus assuming spheroid model of the earth)
with points given in longitudes and latitudes.
"""
from __future__ import print_function
import math
import numpy
import numpy.random
# Equatorial radius of the earth in kilometers
EARTH_ER = 6378.137
# Authalic radius of th... | numpy.arcsin(fwdz) | numpy.arcsin |
import numpy as np
from scipy.io import wavfile
import wave
import librosa
import os
from sklearn.model_selection import train_test_split
from keras.utils import to_categorical
from tqdm import tqdm
X_SIZE = 16000
IMG_SIZE = 28
DATA_PATH = "./data/"
# Input labels
def get_labels(path=DATA_PATH):
labels = os.listd... | np.save(label + 'spec.npy', mfcc_vectors) | numpy.save |
'''
Utilities that are useful to sub- or up-sample weights tensors.
Copyright (C) 2018 <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 ... | np.arange(sampling_inst) | numpy.arange |
"""
Tests to make sure deepchem models can overfit on tiny datasets.
"""
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
__author__ = "<NAME>"
__copyright__ = "Copyright 2016, Stanford University"
__license__ = "MIT"
import os
import tempfile
import numpy ... | np.squeeze(y) | numpy.squeeze |
#!/usr/bin/python
import argparse
import numpy as np
import arrow
import PIL
from tensorrtserver.api import ServerStatusContext, ProtocolType, InferContext
import tensorrtserver.api.model_config_pb2 as model_config
from bistiming import Stopwatch
from eyewitness.detection_utils import DetectionResult
from eyewitness.im... | np.transpose(processed_image, [0, 3, 1, 2]) | numpy.transpose |
"""Resynthesis of signals described as sinusoid tracks."""
import numpy as np
def synthtrax(F, M, SR, SUBF=128, DUR=0):
"""
% X = synthtrax(F, M, SR, SUBF, DUR) Reconstruct a sound from track rep'n.
% Each row of F and M contains a series of frequency and magnitude
% samples for a particular track. The... | np.arange(mm.shape[0]) | numpy.arange |
import numpy as np
from sklearn.naive_bayes import GaussianNB
from scipy.special import logsumexp
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.calibration import CalibratedClassifierCV
from sklearn.model_selection import GroupShuffleSplit
from sklearn... | np.vstack(df['angle']) | numpy.vstack |
from PyQt5 import QtWidgets, uic
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QPixmap
import numpy as np
import sys
import os
from os import path
import cv2
import matplotlib.pyplot as plt
from PIL import Image
import skimage.io
# create our own histogram function
def get_histogram(image, bins):
# array ... | np.fft.ifft2(back_ishift, axes=(0,1)) | numpy.fft.ifft2 |
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 23 14:28:56 2019
@author: balam
"""
from queue import PriorityQueue
import numpy as np
from ObstacleSpace import genObstacleSpace
import MapDiaplay as md
def actions(currentNode, currentCost):
newNodes = []
newNodesFinal = []
# vertical and ... | np.square(fromNode[0]-toNode[0]) | numpy.square |
"""
Impulse reponse-related code
"""
from __future__ import division
import numpy as np
import numpy.linalg as la
import scipy.linalg as L
from scipy import stats
from statsmodels.tools.decorators import cache_readonly
from statsmodels.tools.tools import chain_dot
#from statsmodels.tsa.api import VAR
from statsmode... | np.copy(irfs) | numpy.copy |
import multiprocessing as mp
from copy import copy
import numpy as np
import tkinter
import pickle
import os
from itertools import accumulate
from matplotlib import pyplot as plt, lines
from casadi import Callback, nlpsol_out, nlpsol_n_out, Sparsity
from ..misc.data import Data
from ..misc.enums import PlotType, Cont... | np.concatenate((state, data_states_per_phase[s][i])) | numpy.concatenate |
from collections import defaultdict
import pandas as pd
import numpy as np
import pickle
from sklearn.metrics import f1_score
def save_obj(obj, name):
with open(name + '.pkl', 'wb') as f:
pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)
def load_obj(name):
with open(name + '.pkl', 'rb') as f:
re... | np.argmax(fscore) | numpy.argmax |
# Ignoring some linting rules in tests
# pylint: disable=redefined-outer-name
# pylint: disable=missing-docstring
import csv
import numpy as np
from bingo.symbolic_regression.agraph.generator import AGraphGenerator
from bingo.symbolic_regression.agraph.component_generator \
import ComponentGenerator
from bingo.sym... | np.min(times) | numpy.min |
from utils import detector_utils as detector_utils
from libs.pconv_layer import PConv2D
import cv2
import tensorflow as tf
import datetime
import argparse
import numpy as np
import keras
thresh = 0.9
moving_num = 3
m_input_size = 256
detection_graph, sess = detector_utils.load_inference_graph()
print("m... | np.zeros((1,3)) | numpy.zeros |
from .builder import DATASETS
from .coco import CocoDataset
import numpy as np
from mmdet.utils import get_vocabulary
@DATASETS.register_module()
class CocoTextDataset(CocoDataset):
CLASSES = ('text', )
def __init__(self, ann_file,pipeline,max_seq_len=25, **kwargs):
super(CocoTextDataset, self).__in... | np.zeros((0, 4), dtype=np.float32) | numpy.zeros |
import numpy as np
from .orcadaq import OrcaDecoder, get_ccc, get_readout_info, get_auxhw_info
from .fcdaq import FlashCamEventDecoder
class ORCAFlashCamListenerConfigDecoder(OrcaDecoder):
'''
Decoder for FlashCam listener config written by ORCA
'''
def __init__(self, *args, **kwargs):
... | np.int(data[12]) | numpy.int |
"""
Tools for making FSPS templates
"""
import os
from collections import OrderedDict
import numpy as np
import astropy.units as u
from astropy.cosmology import WMAP9
FLAM_CGS = u.erg/u.second/u.cm**2/u.Angstrom
LINE_CGS = 1.e-17*u.erg/u.second/u.cm**2
try:
from dust_attenuation.baseclasses import BaseAttAvModel... | np.unique(wfull, return_index=True) | numpy.unique |
import ast
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import wilcoxon
from matplotlib.ticker import FormatStrFormatter
import matplotlib
from tabulate import tabulate
text_dir = 'data/qa_example/'
counterfactual_dir = 'counterfactuals/qa_example/model_dist_1layer/'
probe_type = 'model_dist'... | np.asarray(p1_tok0) | numpy.asarray |
from __future__ import print_function
import ast
import baker
import logging
import math
import numpy as np
from sklearn.preprocessing import MaxAbsScaler
from tqdm import tqdm
import core
from core.cascade import load_data, load_data_file, load_costs_data, load_model, save_model, group_counts, group_offsets
from co... | np.sum(weights * E / (1 - gamma * C)) | numpy.sum |
import numpy as np
from scipy.optimize import curve_fit
from scipy.optimize import fsolve, brentq
from scipy.interpolate import interp1d
import scipy.integrate
import sys
import os
import velociraptor_python_tools as vpt
from scipy.spatial import cKDTree
import h5py
import re
from constants import *
from snapshot impor... | np.where(allpinBool) | numpy.where |
# tools to ease plotting
# first, adjust params in matplotlib
import matplotlib
matplotlib.use('Agg')
matplotlib.rcParams['pdf.fonttype'] = 42
matplotlib.rcParams['ps.fonttype'] = 42
matplotlib.rcParams['axes.linewidth'] = 0.1
matplotlib.rcParams['xtick.labelsize'] = 4
matplotlib.rcParams['xtick.major.width'] = 0.1
ma... | np.abs(array[pos_idx]) | numpy.abs |
#!/usr/bin/env python
"""Carry out standard MBAR analysis on 1D REMC simulation output.
The exchange variable is assumed to be temperature.
"""
import argparse
import numpy as np
from scipy import interpolate
from origamipy import conditions
from origamipy import biases
from origamipy import files
from origamipy i... | np.around(melting_temp, decimals=3) | numpy.around |
"""Functions for loading learning examples from disk and numpy arrays into tensors.
Augmentations are also called from here.
"""
import re
import cv2
import numpy as np
import augmentation.appearance
import augmentation.background
import augmentation.voc_loader
import boxlib
import cameralib
import improc
import tfu
... | np.any(imcoords >= FLAGS.proc_side, axis=-1) | numpy.any |
""" Simple maze environment
"""
import numpy as np
# import cv2 #why is this needed?
from deer.base_classes import Environment
import matplotlib
#matplotlib.use('agg')
matplotlib.use('qt5agg')
from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA
import matplotlib.pyplot as plt
fro... | np.concatenate([y[i:i+1],predicted3[0,1:2]]) | numpy.concatenate |
#!/usr/bin/env python
# coding: utf-8
import numpy as np
# Standardised Mean Squared Error
def smse(mu_star_list, Y_test_list):
error_k = []
for k in range(len(Y_test_list)):
res = mu_star_list[k] - Y_test_list[k]
error = (res**2).mean()
error = error / Y_test_list[k].var()
e... | np.log(2 * np.pi * varY) | numpy.log |
# Copyright 2020 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | np.concatenate([maxs, spec.maximum]) | numpy.concatenate |
# %%
#import image_previewer
import glob
from corebreakout import CoreColumn
import pickle
import numpy as np
import matplotlib.pyplot as plt
import colorsys
def slice_depths(top, base, slice_length):
length = base - top
n_slices = int(np.ceil(length / slice_length))
slices = []
for i in range(n_sl... | np.delete(y_train, nan_indices_train, axis=0) | numpy.delete |
import numpy as np
import os
from re import search
import src.numerics as num
import src.fpeqs as fpe
from src.optimal_lambda import (
optimal_lambda,
optimal_reg_param_and_huber_parameter,
)
DATA_FOLDER_PATH = "./data" # "/Volumes/LaCie/final_data_hproblem" # # "/Volumes/LaCie/final_data_hproblem" # # #
... | np.square(m) | numpy.square |
# -------------------------------------------------------------------
import cv2
import numpy as np
import time
from enum import Enum
# =============================================================================
# Ref. design
# https://github.com/Xilinx/Vitis-AI/blob/v1.1/mpsoc/vitis_ai_dnndk_samples/tf_yolov3_voc_p... | np.exp(-x) | numpy.exp |
import numpy as np
from autoarray.structures import grids
from autogalaxy.profiles import geometry_profiles
from autogalaxy.profiles import mass_profiles as mp
from autogalaxy import convert
import typing
from scipy.interpolate import griddata
from autogalaxy import exc
class MassSheet(geometry_profiles.S... | np.full(shape=grid.shape[0], fill_value=self.kappa) | numpy.full |
import torch
import os
from torch.distributions import Normal
import gym
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import cv2
from itertools import permutations
import h5py
from sklearn.feature_selection import mutual_info_regression
import matplotlib.ticker as ticker
fr... | np.linspace(.1, .9, num_codes) | numpy.linspace |
from typing import Any, Set, Tuple, Union, Optional
from pathlib import Path
from collections import defaultdict
from html.parser import HTMLParser
import pytest
from anndata import AnnData
import numpy as np
import xarray as xr
from imageio import imread, imsave
import tifffile
from squidpy.im import ImageContaine... | np.testing.assert_array_equal(crop.data["image_0"].shape, (1, 1, 10)) | numpy.testing.assert_array_equal |
from pathlib import Path
import numpy as np
import pandas as pd
import tensorly as tl
def subsample_data(df: pd.DataFrame) -> np.ndarray:
"""Sub-samples the data to make it more manageable for this assignment
Parameters
----------
df : pd.DataFrame
DataFrame to subsample
Returns
---... | np.arange(df.shape[0]) | numpy.arange |
import numpy as np
def _make_gaussian(x_pts, y_pts, mfd, x_offset=0, y_offset=0):
x0 = (x_pts[-1]+x_pts[0])/2 + x_offset
y0 = (y_pts[-1]+y_pts[0])/2 + y_offset
xx, yy = np.meshgrid(x_pts, y_pts)
sigma = mfd * 0.707 / 2.355
sigma_x = sigma
sigma_y = sigma
gaus_2d = | np.exp(-((xx-x0)**2/(2*sigma_x**2)+
(yy-y0)**2/(2*sigma_y**2))) | numpy.exp |
#%%
import pickle
import matplotlib.pyplot as plt
from matplotlib import rcParams
rcParams.update({'figure.autolayout': True})
import numpy as np
from itertools import product
import seaborn as sns
### MAIN HYPERPARAMS ###
slots = 1
shifts = 6
alg_name = ['L2N','L2F']
########################
#%%
def unpickle(file):
... | np.asarray(ftes) | numpy.asarray |
# This module has been generated automatically from space group information
# obtained from the Computational Crystallography Toolbox
#
"""
Space groups
This module contains a list of all the 230 space groups that can occur in
a crystal. The variable space_groups contains a dictionary that maps
space group numbers an... | N.array([-1,0,0,0,-1,0,0,0,1]) | numpy.array |
# -*- coding: utf-8 -*-
# Copyright 2018 IBM.
#
# 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 agre... | np.asarray(datapoints) | numpy.asarray |
import stokepy as sp
import numpy as np
# instantiate class
fmc = sp.FiniteMarkovChain()
# create initial distribution vector
phi = | np.array([0, 0, 1, 0, 0]) | numpy.array |
import numpy as np
import gym
from gym import spaces
import math
MAX_MARCH = 20
EPSILON = 0.1
DEG_TO_RAD = 0.0174533
WINDOW_SIZE = (200, 300) # Width x Height in pixels
def generate_box(pos=None, size=[10, 25], inside_window=True, color=(255, 255, 255), is_goal=False):
'''
Generate a box with width and height... | np.argmin(dists) | numpy.argmin |
'''
'''
import os
import pickle
import numpy as np
import pandas as pd
from scipy.interpolate import interp1d
from itertools import chain, combinations_with_replacement
# -- astropy --
import astropy.units as u
from astropy.time import Time
# -- specsim --
import specsim
from specsim.atmosphere import Moon
# -- fe... | np.sin(self.moon_zenith) | numpy.sin |
from __future__ import absolute_import, division, print_function
# TensorFlow and tf.keras
import tensorflow as tf
import keras
from keras.utils import CustomObjectScope
from keras.initializers import glorot_uniform
from keras.preprocessing import image
from keras.models import Sequential, load_model, model_from_json
... | np.argmax(predictor) | numpy.argmax |
import sys
import matplotlib.pyplot as plt
from astropy.io import fits
from scipy import optimize
import numpy as np
from pathlib import Path
from scipy import interpolate
import sys
import math as m
from . import nbspectra
########################################################################################
####... | np.vstack([flux[::-1],angle0]) | numpy.vstack |
import glob
import math
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
from pathlib import Path
import cv2
import numpy
import sys
# sys.path.append('.')
from kaggle_ndsb2017 import helpers
from kaggle_ndsb2017 import settings
from kaggle_ndsb2017 import step2_train_nodule_detector
from kaggle_ndsb2017.step1_pr... | numpy.vstack(full_mask) | numpy.vstack |
import numpy as np
from os import listdir
import pickle
import os
import scipy
import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
from config_args import parse_args
def losses_all(args):
def get_loss_pck(args, name, exp_name):
data = []
with open(str(os.getcwd()) +... | np.square(testing_perf['y_predict_std'][t]) | numpy.square |
"""
TODO: some figure numberings (CHOICE, VERSION) were changed: make sure the current numberings are consistent with original runs
TODO: replaces previous versions 161110, 171029
TODO: how to get the grid small log lines also for x-axis?
TODO: mention that Python 3.5.2 or later is required (ideally 3.8)
Plots times f... | np.ma.masked_invalid(Y[method]) | numpy.ma.masked_invalid |
# Copyright 2019 Graphcore Ltd.
# coding=utf-8
from io import BytesIO
import numpy as np
from PIL import Image
import tensorflow as tf
_BINARISED_MNIST_TR = 'http://www.cs.toronto.edu/~larocheh/public/datasets/binarized_mnist/binarized_mnist_train.amat'
_BINARISED_MNIST_TEST = 'http://www.cs.toronto.edu/~larocheh/publ... | np.arange(arrays.shape[0]) | numpy.arange |
"""
This is the main code for P-CRITICAL on Loihi.
The NxPCritical class provides the input and reservoir layers of a liquid state machine.
Output is time-binned on the lakemonts and returned through a snip channel.
Usage examples are available on the scripts directory.
"""
import os
import logging
from time import sl... | np.log2(duration / buffer_size) | numpy.log2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.