How to use mp method in Pytest

Best Python code snippet using pytest

main_test.py

Source:main_test.py Github

copy

Full Screen

1from cvxpy import *2import numpy as np3from init_params import *4import picos as pic5from gurobipy import *6# define the objects7mp = params()8model = DynModel(mp)9mld = MLD(mp, model)10N = 10 # horizon length11N_max = 10012# variables definition here13x = Variable(mp.nstates, N + 1)14z = Variable(mp.nstates, N + 1)15u = Variable(mp.ninputs, N)16d = Bool(mp.nlogics, N)17# penalize the logical varables for obstacles to zeros18d_f = np.ones((mp.nlogics, 1))19d_f[0:4, 0:1] = np.zeros((4, 1))20# Parameters definition here21x_0 = Parameter(mp.nstates, 1)22x_r = Parameter(mp.nstates, 1)23E5 = Parameter(len(mld.E1), 1)24goal_r = Parameter(6, 1)25# for testing purpose26# x_init = Variable(mp.nstates,1)27# x_ref = Variable(mp.nstates,1)28# Eaff = Variable(len(mld.E1),1)29# goal_ref = variable(6,1)30class TrajectoryPlanner:31 def __init__(self):32 a = 033 def MPC(self):34 # problem formulation of hybrid mpc35 states = []36 for t in range(N):37 cost = quad_form((x[:, t + 1] - x_r), mp.Q1) + quad_form((u[:, t]), mp.R)38 constr = [x[:, t + 1] == model.A2 * x[:, t] + model.B2 * u[:, t],39 # constarints on the inputs40 mp.u_min <= u[0, t], u[0, t] <= mp.u_max,41 mp.u_min <= u[1, t], u[1, t] <= mp.u_max,42 mp.u_min <= u[2, t], u[2, t] <= mp.u_max,43 -np.pi <= u[3, t], u[3, t] <= np.pi]44 states.append(Problem(Minimize(cost), constr))45 if (mp.act_term_cnst):46 constr = [mld.P * x[:, N] <= goal_r]47 prob = sum(states)48 prob.constraints += [x[:, 0] == x_0]49 return prob50 def HMPC(self):51 # problem formulation of hybrid mpc52 states = []53 for t in range(N):54 q1 = quad_form((x[:, t + 1] - x_r), mp.Q1)55 print(x[:, t + 1])56 q2 = quad_form((z[:, t + 1] - x_r), mp.Q2)57 print(d[:, t])58 print(d_f)59 p1 = (d[:, t] - d_f)60 q3 = quad_form((d[:, t] - d_f), mp.Q3)61 q4 = quad_form((u[:, t]), mp.R)62 cost = quad_form((x[:, t + 1] - x_r), mp.Q1) + quad_form((z[:, t + 1] - x_r), mp.Q2) + quad_form(63 (d[:, t] - d_f), mp.Q3) + quad_form((u[:, t]), mp.R)64 # cost = quad_form((x[:, t+1] - x_r),mp.Q1) + quad_form((w[:, t]),mp.R)65 constr = [x[:, t + 1] == z[:, t],66 mld.E2 * d[:, t] + mld.E3 * z[:, t] <= mld.E1 * u[:, t] + mld.E4 * x[:, t] + E5,67 # constarints on the inputs68 # x[:,t+1] == model.A2*x[:,t] + model.B2*w[:,t],69 mp.u_min <= u[0, t], u[0, t] <= mp.u_max,70 mp.u_min <= u[1, t], u[1, t] <= mp.u_max,71 mp.u_min <= u[2, t], u[2, t] <= mp.u_max,72 -np.pi <= u[3, t], u[3, t] <= np.pi]73 states.append(Problem(Minimize(cost), constr))74 if (mp.act_term_cnst):75 constr = [mld.P * x[:, N] <= goal_r]76 prob = sum(states)77 prob.constraints += [x[:, 0] == x_0]78 return prob79 def HMPC_test(self, x_ref, goal_ref):80 # problem formulation of hybrid mpc81 states = []82 for t in range(N):83 cost = quad_form((x[:, t + 1] - x_ref), mp.Q1) + quad_form((z[:, t + 1] - x_ref), mp.Q2) + quad_form(84 (d[:, t] - d_f), mp.Q3) + quad_form((u[:, t]), mp.R)85 # cost = quad_form((x[:, t+1] - x_r),mp.Q1) + quad_form((w[:, t]),mp.R)86 constr = [x[:, t + 1] == z[:, t],87 mld.E2 * d[:, t] + mld.E3 * z[:, t] <= mld.E1 * u[:, t] + mld.E4 * x[:, t] + mld.E5,88 # constarints on the inputs89 # x[:,t+1] == model.A2*x[:,t] + model.B2*w[:,t],90 mp.u_min <= u[0, t], u[0, t] <= mp.u_max,91 mp.u_min <= u[1, t], u[1, t] <= mp.u_max,92 mp.u_min <= u[2, t], u[2, t] <= mp.u_max,93 -np.pi <= u[3, t], u[3, t] <= np.pi]94 states.append(Problem(Minimize(cost), constr))95 # if(mp.act_term_cnst):96 # constr = [mld.P*x[:,N] <= goal_ref]97 prob = sum(states)98 prob.constraints += [x[:, 0] == x_0]99 # prob.constraints += [z[:,0] == x_0]100 return prob101 def GetStaticObstPos(self):102 # Determine the position of obstacles based on the start and end indx of quad103 stat_obst_pos = np.zeros((mp.n_stat_obst, 3))104 indx_array = np.zeros((mp.n_stat_obst, 1))105 i = 0106 for k in range(len(mp.obst_centers)):107 if (k != mp.startindx and k != mp.endindx):108 indx_array[i] = k109 i += 1110 for k in range(len(indx_array)):111 stat_obst_pos[k][:] = mp.obst_centers[int(indx_array[k])]112 return stat_obst_pos113 def CalculateE5Static(self):114 static_ref = np.zeros((6, mp.n_stat_obst))115 E5_static = np.zeros((22 * mp.n_stat_obst, 1))116 l_st_obs = mp.obst_rad + mp.quad_rad117 l_dy_obs = 2 * mp.quad_rad118 # Get the positions of static obstacles119 stat_obst_pos = self.GetStaticObstPos()120 for i in range(mp.n_stat_obst):121 static_ref[:, i] = np.array((l_st_obs + int(stat_obst_pos[i][0]),122 l_st_obs + int(stat_obst_pos[i][1]),123 l_st_obs + int(stat_obst_pos[i][2]),124 l_st_obs - int(stat_obst_pos[i][0]),125 l_st_obs - int(stat_obst_pos[i][1]),126 l_st_obs - int(stat_obst_pos[i][2])))127 E5_static[22 * i:22 * (i + 1)] = np.concatenate(128 (np.add(mld.Big_M.reshape((6, 1)), static_ref[:, i].reshape((6, 1))),129 -static_ref[:, i].reshape((6, 1)), mld.d_bin2.reshape((10, 1))))130 return E5_static131 def GetDynamObstPos(self):132 dynam_obst_pos = np.zeros((mp.n_dynam_obst, 3))133 # code starts here134 for i in range(mp.n_dynam_obst):135 dynam_obst_pos[i, :] = np.array((20, 20, 20))136 return dynam_obst_pos137 def CalculateE5Dynam(self):138 l_dy_obs = 2 * mp.quad_rad;139 dynamic_ref = np.zeros((6, mp.n_dynam_obst))140 dynam_obst_pos = self.GetDynamObstPos()141 E5_dynam = np.zeros((22 * mp.n_dynam_obst, 1))142 # code starts here143 for i in range(mp.n_dynam_obst):144 dynamic_ref[:, i] = np.array((l_dy_obs + int(dynam_obst_pos[i][0]),145 l_dy_obs + int(dynam_obst_pos[i][1]),146 l_dy_obs + int(dynam_obst_pos[i][2]),147 l_dy_obs - int(dynam_obst_pos[i][0]),148 l_dy_obs - int(dynam_obst_pos[i][1]),149 l_dy_obs - int(dynam_obst_pos[i][2])))150 E5_dynam[22 * i:22 * (i + 1)] = np.concatenate(151 (np.add(mld.Big_M.reshape((6, 1)), dynamic_ref[:, i].reshape((6, 1))),152 -dynamic_ref[:, i].reshape((6, 1)), mld.d_bin2.reshape((10, 1))))153 return E5_dynam154 def SimulateQuad(self, x, u):155 # Also add the integral part of the Discrete SS model156 zd = mp.obst_centers[mp.endindx, 2]157 DInt = np.array([0, 0, 0, 0, 0, 0, 0, 0, -mp.Ts])158 # print(DInt)159 z_int = DInt * zd160 print(model.A2 * x + model.B2.dot(u.reshape((4, 1))) + z_int.reshape((9, 1)))161 return model.A2 * x + model.B2.dot(u.reshape((4, 1))) + z_int.reshape((9, 1))162 def run(self):163 # while not rospy.is_shutdown():164 # pos_init = np.transpose(np.array([0,0,0,0,0,0,0,0,0]))165 # x_0.value = np.transpose(np.array([0,0,0,0,0,0,0,0,0]))166 # based on the initial poition of quad define the MPC controller167 my_prob = self.HMPC()168 # print(my_prob)169 # state the reference points170 x_r.value = np.concatenate(171 (mp.obst_centers[mp.endindx], np.array([0, 0, 0, 0, np.pi / 4, int(mp.obst_centers[mp.endindx, 2])])))172 # print(x_r.value)173 # define the goal_ref for terminal constraints i-e solve the polyhedral set174 s = 0.2175 l_r = mp.obst_rad + s176 goal_r.value = np.array([l_r + int(mp.obst_centers[mp.endindx, 0]),177 l_r + int(mp.obst_centers[mp.endindx, 1]),178 l_r + int(mp.obst_centers[mp.endindx, 2]),179 l_r - int(mp.obst_centers[mp.endindx, 0]),180 l_r - int(mp.obst_centers[mp.endindx, 1]),181 l_r - int(mp.obst_centers[mp.endindx, 2])])182 E5_static = self.CalculateE5Static()183 # print(E5_static.shape)184 # define the variable for simulation185 z = np.zeros((N_max, mp.nstates))186 u = np.zeros((N_max, mp.ninputs))187 # print(my_prob)188 # loop starts here189 count = 0190 while (count < N_max - 1):191 x_0.value = z[count, :]192 # Get the dynamic part of affine matrix of MLD system193 E5_dynam = self.CalculateE5Dynam()194 E5.value = np.concatenate((mld.M.reshape((mp.nstates, 1)), mld.M.reshape((mp.nstates, 1)),195 E5_static.reshape((22 * mp.n_stat_obst, 1)),196 E5_dynam.reshape((22 * mp.n_dynam_obst, 1)),197 mld.M1.reshape((mp.nstates, 1)), mld.M1.reshape((mp.nstates, 1)),198 np.zeros((2 * mp.nstates, 1)), np.zeros((mp.nobst + 1, 1))))199 # print(abc.shape)200 # print(mld.E2.shape)201 # solve the receding horizon problem202 my_prob.solve(solver=GUROBI)203 count = count + 1204 # simulate the system205 z[count, :] = self.SimulateQuad(x.value[:, 0], u.transpose()[:, 0]).reshape((1, 9))206 print("x:")207 # print(x.value)208 print(z[count, 0:3])209 # for testing purpose210 def test(self):211 x_ref = np.concatenate(212 (mp.obst_centers[mp.endindx], np.array([0, 0, 0, 0, np.pi / 4, int(mp.obst_centers[mp.endindx, 2])])))213 s = 0.2214 l_r = mp.obst_rad + s215 goal_ref = np.array([l_r + int(mp.obst_centers[mp.endindx, 0]),216 l_r + int(mp.obst_centers[mp.endindx, 1]),217 l_r + int(mp.obst_centers[mp.endindx, 2]),218 l_r - int(mp.obst_centers[mp.endindx, 0]),219 l_r - int(mp.obst_centers[mp.endindx, 1]),220 l_r - int(mp.obst_centers[mp.endindx, 2])])221 E5_static = self.CalculateE5Static()222 E5_dynam = self.CalculateE5Dynam()223 mld.E5 = np.concatenate((mld.M.reshape((mp.nstates, 1)), mld.M.reshape((mp.nstates, 1)),224 E5_static.reshape((22 * mp.n_stat_obst, 1)),225 E5_dynam.reshape((22 * mp.n_dynam_obst, 1)),226 mld.M1.reshape((mp.nstates, 1)), mld.M1.reshape((mp.nstates, 1)),227 np.zeros((2 * mp.nstates, 1)), np.zeros((mp.nobst + 1, 1))))228 # print(mld.E2.shape)229 my_prob = self.HMPC_test(x_ref, goal_ref)230 # define the variable for simulation231 z = np.zeros((N_max, mp.nstates))232 u = np.zeros((N_max, mp.ninputs))233 count = 0234 while (count < N_max - 1):235 x_0.value = z[count, :]236 my_prob.solve(solver=GUROBI)237 count = count + 1238 # simulate the system239 z[count, :] = self.SimulateQuad(x.value[:, 0], u[:, 0]).reshape((1, 9))240 print("x:")241 # print(x.value)242 print(z[count, 0:3])243if __name__ == "__main__":244 # rospy.init_node("Trajectory Planner")245 trajplanner = TrajectoryPlanner()246 trajplanner.run()...

Full Screen

Full Screen

policy_test.py

Source:policy_test.py Github

copy

Full Screen

1# Copyright 2019 The TensorFlow Authors. All Rights Reserved.2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7# http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14# ==============================================================================15"""Tests Policies."""16from __future__ import absolute_import17from __future__ import division18from __future__ import print_function19from tensorflow.python.framework import dtypes20from tensorflow.python.framework import ops21from tensorflow.python.framework import test_util22from tensorflow.python.keras import testing_utils23from tensorflow.python.keras.engine import base_layer_utils24from tensorflow.python.keras.mixed_precision.experimental import policy as mp_policy25from tensorflow.python.keras.optimizer_v2 import gradient_descent26from tensorflow.python.platform import test27from tensorflow.python.platform import tf_logging28from tensorflow.python.training.experimental import loss_scale as loss_scale_module29from tensorflow.python.training.experimental import mixed_precision30@test_util.run_all_in_graph_and_eager_modes31class PolicyTest(test.TestCase):32 """Tests Policies."""33 @testing_utils.enable_v2_dtype_behavior34 def test_dtype_attributes(self):35 policy = mp_policy.Policy('infer')36 self.assertEqual(policy.compute_dtype, None)37 self.assertEqual(policy.variable_dtype, None)38 policy = mp_policy.Policy('infer_float32_vars')39 self.assertEqual(policy.compute_dtype, None)40 self.assertEqual(policy.variable_dtype, 'float32')41 for dtype in 'int32', 'bool', 'float16', 'float32':42 policy = mp_policy.Policy(dtype)43 self.assertEqual(policy.name, dtype)44 self.assertEqual(policy.compute_dtype, dtype)45 self.assertEqual(policy.variable_dtype, dtype)46 policy = mp_policy.Policy(dtype + '_with_float32_vars')47 expected_name = (48 dtype if dtype == 'float32' else dtype + '_with_float32_vars')49 self.assertEqual(policy.name, expected_name)50 self.assertEqual(policy.compute_dtype, dtype)51 self.assertEqual(policy.variable_dtype, 'float32')52 for dtype in 'float16', 'bfloat16':53 policy = mp_policy.Policy('mixed_' + dtype)54 self.assertEqual(policy.name, 'mixed_' + dtype)55 self.assertEqual(policy.compute_dtype, dtype)56 self.assertEqual(policy.variable_dtype, 'float32')57 @testing_utils.enable_v2_dtype_behavior58 def test_repr(self):59 for policy in ('infer', 'infer_with_float32_vars', 'float32',60 'float16_with_float32_vars'):61 self.assertEqual(repr(mp_policy.Policy(policy)),62 '<Policy "%s", loss_scale=None>' % policy)63 self.assertEqual(repr(mp_policy.Policy('float32_with_float32_vars')),64 '<Policy "float32", loss_scale=None>')65 self.assertEqual(repr(mp_policy.Policy('float16', loss_scale=2)),66 '<Policy "float16", loss_scale=FixedLossScale(2.0)>')67 @testing_utils.enable_v2_dtype_behavior68 def test_policy_errors(self):69 # Test passing invalid strings70 expected_error = 'Cannot convert value %s to a mixed precision Policy.'71 for invalid_policy in ('abc', 'abc_with_float32_vars',72 'float32_with_float16_vars'):73 with self.assertRaisesRegexp(ValueError,74 expected_error % invalid_policy):75 mp_policy.Policy(invalid_policy)76 # Test passing a DType77 with self.assertRaisesRegexp(TypeError,78 "'name' must be a string, not a DType. "79 "Instead, pass DType.name. Got: float16"):80 mp_policy.Policy(dtypes.float16)81 # Test passing a non-DType invalid type82 with self.assertRaisesRegexp(TypeError,83 "'name' must be a string, but got: 5"):84 mp_policy.Policy(5)85 @testing_utils.enable_v2_dtype_behavior86 def test_with_input_dtype(self):87 policy = mp_policy.with_input_dtype(mp_policy.Policy('infer'), 'float16')88 self.assertEqual(policy.compute_dtype, 'float16')89 self.assertEqual(policy.variable_dtype, 'float16')90 policy = mp_policy.with_input_dtype(91 mp_policy.Policy('infer_with_float32_vars'), 'float16')92 self.assertEqual(policy.compute_dtype, 'float16')93 self.assertEqual(policy.variable_dtype, 'float32')94 policy = mp_policy.with_input_dtype(95 mp_policy.Policy('infer_with_float32_vars'), 'float32')96 self.assertEqual(policy.compute_dtype, 'float32')97 self.assertEqual(policy.variable_dtype, 'float32')98 @testing_utils.enable_v2_dtype_behavior99 def test_loss_scale(self):100 policy = mp_policy.Policy('float32')101 self.assertEqual(policy.loss_scale, None)102 policy = mp_policy.Policy('float32', loss_scale=None)103 self.assertEqual(policy.loss_scale, None)104 ls = loss_scale_module.DynamicLossScale()105 policy = mp_policy.Policy('float32', loss_scale=ls)106 self.assertIs(policy.loss_scale, ls)107 policy = mp_policy.Policy('float32', loss_scale='dynamic')108 self.assertIsInstance(policy.loss_scale, loss_scale_module.DynamicLossScale)109 policy = mp_policy.Policy('mixed_float16')110 self.assertIsInstance(policy.loss_scale, loss_scale_module.DynamicLossScale)111 policy = mp_policy.Policy('mixed_float16', loss_scale=None)112 self.assertEqual(policy.loss_scale, None)113 policy = mp_policy.Policy('mixed_bfloat16')114 self.assertEqual(policy.loss_scale, None)115 @testing_utils.enable_v2_dtype_behavior116 def test_global_policy(self):117 if base_layer_utils.v2_dtype_behavior_enabled():118 default_policy = 'float32'119 else:120 default_policy = 'infer'121 self.assertEqual(mp_policy.global_policy().name, default_policy)122 try:123 mp_policy.set_policy('infer_with_float32_vars')124 self.assertEqual(mp_policy.global_policy().name,125 'infer_with_float32_vars')126 with ops.Graph().as_default(): # Policies are not associated with a graph127 self.assertEqual(mp_policy.global_policy().name,128 'infer_with_float32_vars')129 mp_policy.set_policy('infer')130 self.assertEqual(mp_policy.global_policy().name, 'infer')131 policy = mp_policy.Policy('infer_with_float32_vars')132 mp_policy.set_policy(policy)133 self.assertIs(mp_policy.global_policy(), policy)134 finally:135 mp_policy.set_policy(None)136 @testing_utils.enable_v2_dtype_behavior137 def test_loss_scale_warning(self):138 with test.mock.patch.object(tf_logging, 'warn') as mock_warn:139 mp_policy.Policy('float32', loss_scale=2.)140 self.assertEqual(141 mock_warn.call_args[0][0],142 'Creating a Policy with a loss scale is only useful for float16 '143 'policies. You passed loss_scale=2.0 for policy float32. Consider '144 'not passing any loss_scale instead.')145 for policy_name in 'float16', 'float16_with_float32_vars', 'mixed_float16':146 with test.mock.patch.object(tf_logging, 'warn') as mock_warn:147 mp_policy.Policy(policy_name, loss_scale=2.)148 mock_warn.assert_not_called()149 @testing_utils.enable_v2_dtype_behavior150 def test_policy_scope(self):151 if base_layer_utils.v2_dtype_behavior_enabled():152 default_policy = 'float32'153 else:154 default_policy = 'infer'155 with mp_policy.policy_scope('infer_with_float32_vars'):156 self.assertEqual(mp_policy.global_policy().name,157 'infer_with_float32_vars')158 with mp_policy.policy_scope('infer'):159 self.assertEqual(mp_policy.global_policy().name, 'infer')160 self.assertEqual(mp_policy.global_policy().name,161 'infer_with_float32_vars')162 self.assertEqual(mp_policy.global_policy().name, default_policy)163 @testing_utils.enable_v2_dtype_behavior164 def test_error_if_graph_rewrite_enabled(self):165 try:166 mixed_precision.enable_mixed_precision_graph_rewrite(167 gradient_descent.SGD(1.))168 with self.assertRaisesRegexp(169 ValueError, 'the mixed precision graph rewrite has already been '170 'enabled'):171 mp_policy.set_policy('infer_float32_vars')172 finally:173 mixed_precision.disable_mixed_precision_graph_rewrite()174 @testing_utils.disable_v2_dtype_behavior175 def test_v1_dtype_behavior(self):176 # These policies are allowed with V1 dtype behavior177 with mp_policy.policy_scope(mp_policy.Policy('infer')):178 pass179 with mp_policy.policy_scope(mp_policy.Policy('infer_float32_vars')):180 pass181 # These policies are not allowed with V1 dtype behavior182 with self.assertRaisesRegexp(183 ValueError,184 'global policy can only be set to a non-infer policy in TensorFlow 2'):185 with mp_policy.policy_scope(mp_policy.Policy('float32')):186 pass187 with self.assertRaisesRegexp(188 ValueError,189 'global policy can only be set to a non-infer policy in TensorFlow 2'):190 with mp_policy.policy_scope(191 mp_policy.Policy('float16_with_float32_vars')):192 pass193if __name__ == '__main__':...

Full Screen

Full Screen

__init__.py

Source:__init__.py Github

copy

Full Screen

1__version__ = '0.19'2from .usertools import monitor, timing3from .ctx_fp import FPContext4from .ctx_mp import MPContext5from .ctx_iv import MPIntervalContext6fp = FPContext()7mp = MPContext()8iv = MPIntervalContext()9fp._mp = mp10mp._mp = mp11iv._mp = mp12mp._fp = fp13fp._fp = fp14mp._iv = iv15fp._iv = iv16iv._iv = iv17# XXX: extremely bad pickle hack18from . import ctx_mp as _ctx_mp19_ctx_mp._mpf_module.mpf = mp.mpf20_ctx_mp._mpf_module.mpc = mp.mpc21make_mpf = mp.make_mpf22make_mpc = mp.make_mpc23extraprec = mp.extraprec24extradps = mp.extradps25workprec = mp.workprec26workdps = mp.workdps27autoprec = mp.autoprec28maxcalls = mp.maxcalls29memoize = mp.memoize30mag = mp.mag31bernfrac = mp.bernfrac32qfrom = mp.qfrom33mfrom = mp.mfrom34kfrom = mp.kfrom35taufrom = mp.taufrom36qbarfrom = mp.qbarfrom37ellipfun = mp.ellipfun38jtheta = mp.jtheta39kleinj = mp.kleinj40qp = mp.qp41qhyper = mp.qhyper42qgamma = mp.qgamma43qfac = mp.qfac44nint_distance = mp.nint_distance45plot = mp.plot46cplot = mp.cplot47splot = mp.splot48odefun = mp.odefun49jacobian = mp.jacobian50findroot = mp.findroot51multiplicity = mp.multiplicity52isinf = mp.isinf53isnan = mp.isnan54isnormal = mp.isnormal55isint = mp.isint56isfinite = mp.isfinite57almosteq = mp.almosteq58nan = mp.nan59rand = mp.rand60absmin = mp.absmin61absmax = mp.absmax62fraction = mp.fraction63linspace = mp.linspace64arange = mp.arange65mpmathify = convert = mp.convert66mpc = mp.mpc67mpi = iv._mpi68nstr = mp.nstr69nprint = mp.nprint70chop = mp.chop71fneg = mp.fneg72fadd = mp.fadd73fsub = mp.fsub74fmul = mp.fmul75fdiv = mp.fdiv76fprod = mp.fprod77quad = mp.quad78quadgl = mp.quadgl79quadts = mp.quadts80quadosc = mp.quadosc81pslq = mp.pslq82identify = mp.identify83findpoly = mp.findpoly84richardson = mp.richardson85shanks = mp.shanks86levin = mp.levin87cohen_alt = mp.cohen_alt88nsum = mp.nsum89nprod = mp.nprod90difference = mp.difference91diff = mp.diff92diffs = mp.diffs93diffs_prod = mp.diffs_prod94diffs_exp = mp.diffs_exp95diffun = mp.diffun96differint = mp.differint97taylor = mp.taylor98pade = mp.pade99polyval = mp.polyval100polyroots = mp.polyroots101fourier = mp.fourier102fourierval = mp.fourierval103sumem = mp.sumem104sumap = mp.sumap105chebyfit = mp.chebyfit106limit = mp.limit107matrix = mp.matrix108eye = mp.eye109diag = mp.diag110zeros = mp.zeros111ones = mp.ones112hilbert = mp.hilbert113randmatrix = mp.randmatrix114swap_row = mp.swap_row115extend = mp.extend116norm = mp.norm117mnorm = mp.mnorm118lu_solve = mp.lu_solve119lu = mp.lu120qr = mp.qr121unitvector = mp.unitvector122inverse = mp.inverse123residual = mp.residual124qr_solve = mp.qr_solve125cholesky = mp.cholesky126cholesky_solve = mp.cholesky_solve127det = mp.det128cond = mp.cond129hessenberg = mp.hessenberg130schur = mp.schur131eig = mp.eig132eig_sort = mp.eig_sort133eigsy = mp.eigsy134eighe = mp.eighe135eigh = mp.eigh136svd_r = mp.svd_r137svd_c = mp.svd_c138svd = mp.svd139gauss_quadrature = mp.gauss_quadrature140expm = mp.expm141sqrtm = mp.sqrtm142powm = mp.powm143logm = mp.logm144sinm = mp.sinm145cosm = mp.cosm146mpf = mp.mpf147j = mp.j148exp = mp.exp149expj = mp.expj150expjpi = mp.expjpi151ln = mp.ln152im = mp.im153re = mp.re154inf = mp.inf155ninf = mp.ninf156sign = mp.sign157eps = mp.eps158pi = mp.pi159ln2 = mp.ln2160ln10 = mp.ln10161phi = mp.phi162e = mp.e163euler = mp.euler164catalan = mp.catalan165khinchin = mp.khinchin166glaisher = mp.glaisher167apery = mp.apery168degree = mp.degree169twinprime = mp.twinprime170mertens = mp.mertens171ldexp = mp.ldexp172frexp = mp.frexp173fsum = mp.fsum174fdot = mp.fdot175sqrt = mp.sqrt176cbrt = mp.cbrt177exp = mp.exp178ln = mp.ln179log = mp.log180log10 = mp.log10181power = mp.power182cos = mp.cos183sin = mp.sin184tan = mp.tan185cosh = mp.cosh186sinh = mp.sinh187tanh = mp.tanh188acos = mp.acos189asin = mp.asin190atan = mp.atan191asinh = mp.asinh192acosh = mp.acosh193atanh = mp.atanh194sec = mp.sec195csc = mp.csc196cot = mp.cot197sech = mp.sech198csch = mp.csch199coth = mp.coth200asec = mp.asec201acsc = mp.acsc202acot = mp.acot203asech = mp.asech204acsch = mp.acsch205acoth = mp.acoth206cospi = mp.cospi207sinpi = mp.sinpi208sinc = mp.sinc209sincpi = mp.sincpi210cos_sin = mp.cos_sin211cospi_sinpi = mp.cospi_sinpi212fabs = mp.fabs213re = mp.re214im = mp.im215conj = mp.conj216floor = mp.floor217ceil = mp.ceil218nint = mp.nint219frac = mp.frac220root = mp.root221nthroot = mp.nthroot222hypot = mp.hypot223fmod = mp.fmod224ldexp = mp.ldexp225frexp = mp.frexp226sign = mp.sign227arg = mp.arg228phase = mp.phase229polar = mp.polar230rect = mp.rect231degrees = mp.degrees232radians = mp.radians233atan2 = mp.atan2234fib = mp.fib235fibonacci = mp.fibonacci236lambertw = mp.lambertw237zeta = mp.zeta238altzeta = mp.altzeta239gamma = mp.gamma240rgamma = mp.rgamma241factorial = mp.factorial242fac = mp.fac243fac2 = mp.fac2244beta = mp.beta245betainc = mp.betainc246psi = mp.psi247#psi0 = mp.psi0248#psi1 = mp.psi1249#psi2 = mp.psi2250#psi3 = mp.psi3251polygamma = mp.polygamma252digamma = mp.digamma253#trigamma = mp.trigamma254#tetragamma = mp.tetragamma255#pentagamma = mp.pentagamma256harmonic = mp.harmonic257bernoulli = mp.bernoulli258bernfrac = mp.bernfrac259stieltjes = mp.stieltjes260hurwitz = mp.hurwitz261dirichlet = mp.dirichlet262bernpoly = mp.bernpoly263eulerpoly = mp.eulerpoly264eulernum = mp.eulernum265polylog = mp.polylog266clsin = mp.clsin267clcos = mp.clcos268gammainc = mp.gammainc269gammaprod = mp.gammaprod270binomial = mp.binomial271rf = mp.rf272ff = mp.ff273hyper = mp.hyper274hyp0f1 = mp.hyp0f1275hyp1f1 = mp.hyp1f1276hyp1f2 = mp.hyp1f2277hyp2f1 = mp.hyp2f1278hyp2f2 = mp.hyp2f2279hyp2f0 = mp.hyp2f0280hyp2f3 = mp.hyp2f3281hyp3f2 = mp.hyp3f2282hyperu = mp.hyperu283hypercomb = mp.hypercomb284meijerg = mp.meijerg285appellf1 = mp.appellf1286appellf2 = mp.appellf2287appellf3 = mp.appellf3288appellf4 = mp.appellf4289hyper2d = mp.hyper2d290bihyper = mp.bihyper291erf = mp.erf292erfc = mp.erfc293erfi = mp.erfi294erfinv = mp.erfinv295npdf = mp.npdf296ncdf = mp.ncdf297expint = mp.expint298e1 = mp.e1299ei = mp.ei300li = mp.li301ci = mp.ci302si = mp.si303chi = mp.chi304shi = mp.shi305fresnels = mp.fresnels306fresnelc = mp.fresnelc307airyai = mp.airyai308airybi = mp.airybi309airyaizero = mp.airyaizero310airybizero = mp.airybizero311scorergi = mp.scorergi312scorerhi = mp.scorerhi313ellipk = mp.ellipk314ellipe = mp.ellipe315ellipf = mp.ellipf316ellippi = mp.ellippi317elliprc = mp.elliprc318elliprj = mp.elliprj319elliprf = mp.elliprf320elliprd = mp.elliprd321elliprg = mp.elliprg322agm = mp.agm323jacobi = mp.jacobi324chebyt = mp.chebyt325chebyu = mp.chebyu326legendre = mp.legendre327legenp = mp.legenp328legenq = mp.legenq329hermite = mp.hermite330pcfd = mp.pcfd331pcfu = mp.pcfu332pcfv = mp.pcfv333pcfw = mp.pcfw334gegenbauer = mp.gegenbauer335laguerre = mp.laguerre336spherharm = mp.spherharm337besselj = mp.besselj338j0 = mp.j0339j1 = mp.j1340besseli = mp.besseli341bessely = mp.bessely342besselk = mp.besselk343besseljzero = mp.besseljzero344besselyzero = mp.besselyzero345hankel1 = mp.hankel1346hankel2 = mp.hankel2347struveh = mp.struveh348struvel = mp.struvel349angerj = mp.angerj350webere = mp.webere351lommels1 = mp.lommels1352lommels2 = mp.lommels2353whitm = mp.whitm354whitw = mp.whitw355ber = mp.ber356bei = mp.bei357ker = mp.ker358kei = mp.kei359coulombc = mp.coulombc360coulombf = mp.coulombf361coulombg = mp.coulombg362lambertw = mp.lambertw363barnesg = mp.barnesg364superfac = mp.superfac365hyperfac = mp.hyperfac366loggamma = mp.loggamma367siegeltheta = mp.siegeltheta368siegelz = mp.siegelz369grampoint = mp.grampoint370zetazero = mp.zetazero371riemannr = mp.riemannr372primepi = mp.primepi373primepi2 = mp.primepi2374primezeta = mp.primezeta375bell = mp.bell376polyexp = mp.polyexp377expm1 = mp.expm1378powm1 = mp.powm1379unitroots = mp.unitroots380cyclotomic = mp.cyclotomic381mangoldt = mp.mangoldt382secondzeta = mp.secondzeta383nzeros = mp.nzeros384backlunds = mp.backlunds385lerchphi = mp.lerchphi386stirling1 = mp.stirling1387stirling2 = mp.stirling2388# be careful when changing this name, don't use test*!389def runtests():390 """391 Run all mpmath tests and print output.392 """393 import os.path394 from inspect import getsourcefile395 from .tests import runtests as tests396 testdir = os.path.dirname(os.path.abspath(getsourcefile(tests)))397 importdir = os.path.abspath(testdir + '/../..')398 tests.testit(importdir, testdir)399def doctests(filter=[]):400 try:401 import psyco; psyco.full()402 except ImportError:403 pass404 import sys405 from timeit import default_timer as clock406 for i, arg in enumerate(sys.argv):407 if '__init__.py' in arg:408 filter = [sn for sn in sys.argv[i+1:] if not sn.startswith("-")]409 break410 import doctest411 globs = globals().copy()412 for obj in globs: #sorted(globs.keys()):413 if filter:414 if not sum([pat in obj for pat in filter]):415 continue416 sys.stdout.write(str(obj) + " ")417 sys.stdout.flush()418 t1 = clock()419 doctest.run_docstring_examples(globs[obj], {}, verbose=("-v" in sys.argv))420 t2 = clock()421 print(round(t2-t1, 3))422if __name__ == '__main__':...

Full Screen

Full Screen

test_levin.py

Source:test_levin.py Github

copy

Full Screen

1#!/usr/bin/python2# -*- coding: utf-8 -*-3from mpmath import mp4from mpmath import libmp5xrange = libmp.backend.xrange6# Attention:7# These tests run with 15-20 decimal digits precision. For higher precision the8# working precision must be raised.9def test_levin_0():10 mp.dps = 1711 eps = mp.mpf(mp.eps)12 with mp.extraprec(2 * mp.prec):13 L = mp.levin(method = "levin", variant = "u")14 S, s, n = [], 0, 115 while 1:16 s += mp.one / (n * n)17 n += 118 S.append(s)19 v, e = L.update_psum(S)20 if e < eps:21 break22 if n > 1000: raise RuntimeError("iteration limit exceeded")23 eps = mp.exp(0.9 * mp.log(eps))24 err = abs(v - mp.pi ** 2 / 6)25 assert err < eps26 w = mp.nsum(lambda n: 1/(n * n), [1, mp.inf], method = "levin", levin_variant = "u")27 err = abs(v - w)28 assert err < eps29def test_levin_1():30 mp.dps = 1731 eps = mp.mpf(mp.eps)32 with mp.extraprec(2 * mp.prec):33 L = mp.levin(method = "levin", variant = "v")34 A, n = [], 135 while 1:36 s = mp.mpf(n) ** (2 + 3j)37 n += 138 A.append(s)39 v, e = L.update(A)40 if e < eps:41 break42 if n > 1000: raise RuntimeError("iteration limit exceeded")43 eps = mp.exp(0.9 * mp.log(eps))44 err = abs(v - mp.zeta(-2-3j))45 assert err < eps46 w = mp.nsum(lambda n: n ** (2 + 3j), [1, mp.inf], method = "levin", levin_variant = "v")47 err = abs(v - w)48 assert err < eps49def test_levin_2():50 # [2] A. Sidi - "Pratical Extrapolation Methods" p.37351 mp.dps = 1752 z=mp.mpf(10)53 eps = mp.mpf(mp.eps)54 with mp.extraprec(2 * mp.prec):55 L = mp.levin(method = "sidi", variant = "t")56 n = 057 while 1:58 s = (-1)**n * mp.fac(n) * z ** (-n)59 v, e = L.step(s)60 n += 161 if e < eps:62 break63 if n > 1000: raise RuntimeError("iteration limit exceeded")64 eps = mp.exp(0.9 * mp.log(eps))65 exact = mp.quad(lambda x: mp.exp(-x)/(1+x/z),[0,mp.inf])66 # there is also a symbolic expression for the integral:67 # exact = z * mp.exp(z) * mp.expint(1,z)68 err = abs(v - exact)69 assert err < eps70 w = mp.nsum(lambda n: (-1) ** n * mp.fac(n) * z ** (-n), [0, mp.inf], method = "sidi", levin_variant = "t")71 assert err < eps72def test_levin_3():73 mp.dps = 1774 z=mp.mpf(2)75 eps = mp.mpf(mp.eps)76 with mp.extraprec(7*mp.prec): # we need copious amount of precision to sum this highly divergent series77 L = mp.levin(method = "levin", variant = "t")78 n, s = 0, 079 while 1:80 s += (-z)**n * mp.fac(4 * n) / (mp.fac(n) * mp.fac(2 * n) * (4 ** n))81 n += 182 v, e = L.step_psum(s)83 if e < eps:84 break85 if n > 1000: raise RuntimeError("iteration limit exceeded")86 eps = mp.exp(0.8 * mp.log(eps))87 exact = mp.quad(lambda x: mp.exp( -x * x / 2 - z * x ** 4), [0,mp.inf]) * 2 / mp.sqrt(2 * mp.pi)88 # there is also a symbolic expression for the integral:89 # exact = mp.exp(mp.one / (32 * z)) * mp.besselk(mp.one / 4, mp.one / (32 * z)) / (4 * mp.sqrt(z * mp.pi))90 err = abs(v - exact)91 assert err < eps92 w = mp.nsum(lambda n: (-z)**n * mp.fac(4 * n) / (mp.fac(n) * mp.fac(2 * n) * (4 ** n)), [0, mp.inf], method = "levin", levin_variant = "t", workprec = 8*mp.prec, steps = [2] + [1 for x in xrange(1000)])93 err = abs(v - w)94 assert err < eps95def test_levin_nsum():96 mp.dps = 1797 with mp.extraprec(mp.prec):98 z = mp.mpf(10) ** (-10)99 a = mp.nsum(lambda n: n**(-(1+z)), [1, mp.inf], method = "l") - 1 / z100 assert abs(a - mp.euler) < 1e-10101 eps = mp.exp(0.8 * mp.log(mp.eps))102 a = mp.nsum(lambda n: (-1)**(n-1) / n, [1, mp.inf], method = "sidi")103 assert abs(a - mp.log(2)) < eps104 z = 2 + 1j105 f = lambda n: mp.rf(2 / mp.mpf(3), n) * mp.rf(4 / mp.mpf(3), n) * z**n / (mp.rf(1 / mp.mpf(3), n) * mp.fac(n))106 v = mp.nsum(f, [0, mp.inf], method = "levin", steps = [10 for x in xrange(1000)])107 exact = mp.hyp2f1(2 / mp.mpf(3), 4 / mp.mpf(3), 1 / mp.mpf(3), z)108 assert abs(exact - v) < eps109def test_cohen_alt_0():110 mp.dps = 17111 AC = mp.cohen_alt()112 S, s, n = [], 0, 1113 while 1:114 s += -((-1) ** n) * mp.one / (n * n)115 n += 1116 S.append(s)117 v, e = AC.update_psum(S)118 if e < mp.eps:119 break120 if n > 1000: raise RuntimeError("iteration limit exceeded")121 eps = mp.exp(0.9 * mp.log(mp.eps))122 err = abs(v - mp.pi ** 2 / 12)123 assert err < eps124def test_cohen_alt_1():125 mp.dps = 17126 A = []127 AC = mp.cohen_alt()128 n = 1129 while 1:130 A.append( mp.loggamma(1 + mp.one / (2 * n - 1)))131 A.append(-mp.loggamma(1 + mp.one / (2 * n)))132 n += 1133 v, e = AC.update(A)134 if e < mp.eps:135 break136 if n > 1000: raise RuntimeError("iteration limit exceeded")137 v = mp.exp(v)138 err = abs(v - 1.06215090557106)...

Full Screen

Full Screen

Pytest Tutorial

Looking for an in-depth tutorial around pytest? LambdaTest covers the detailed pytest tutorial that has everything related to the pytest, from setting up the pytest framework to automation testing. Delve deeper into pytest testing by exploring advanced use cases like parallel testing, pytest fixtures, parameterization, executing multiple test cases from a single file, and more.

Chapters

  1. What is pytest
  2. Pytest installation: Want to start pytest from scratch? See how to install and configure pytest for Python automation testing.
  3. Run first test with pytest framework: Follow this step-by-step tutorial to write and run your first pytest script.
  4. Parallel testing with pytest: A hands-on guide to parallel testing with pytest to improve the scalability of your test automation.
  5. Generate pytest reports: Reports make it easier to understand the results of pytest-based test runs. Learn how to generate pytest reports.
  6. Pytest Parameterized tests: Create and run your pytest scripts while avoiding code duplication and increasing test coverage with parameterization.
  7. Pytest Fixtures: Check out how to implement pytest fixtures for your end-to-end testing needs.
  8. Execute Multiple Test Cases: Explore different scenarios for running multiple test cases in pytest from a single file.
  9. Stop Test Suite after N Test Failures: See how to stop your test suite after n test failures in pytest using the @pytest.mark.incremental decorator and maxfail command-line option.

YouTube

Skim our below pytest tutorial playlist to get started with automation testing using the pytest framework.

https://www.youtube.com/playlist?list=PLZMWkkQEwOPlcGgDmHl8KkXKeLF83XlrP

Run Pytest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful