def assert_sanity (val, validators): """ Use validators for assertion. This actually works much like `sanitize` other than converting errors to AssertionErrors and serving as a signal of intent in code. Note that this accepts a single value - If you want to sanitize a whole list in the same way, use a list comprehension. For example:: >>> assert_sanity (1, int) 1 >>> from konval import IsEqualOrMore, ToLength >>> x = assert_sanity ('2', [float, IsEqualOrMore(1)]) >>> x 2.0 >>> assert_sanity (['a', 'b'], [ToLength(), float, IsEqualOrMore(3)]) Traceback (most recent call last): ... AssertionError: 2.0 is lower than 3 """ try: return sanitize (val, validators) except exceptions.Exception as err: raise exceptions.AssertionError (str (err)) except: raise exceptions.AssertionError ("an error occurred when sanitizing '%s'" % val)
def success(self, err, h): beta = 0.0 alpha = 1.0 / 8.0 - beta * 0.2 safe = 0.9 minscale = 0.333 maxscale = 6.0 if np.isnan(h): raise exceptions.AssertionError('stepsize is NaN') if err <= 1.0: if err == 0.0: scale = maxscale else: scale = safe * np.power(err, -alpha) * np.power(err, beta) if scale < minscale: scale = minscale if scale > maxscale: scale = maxscale if self.reject: self.hnext = h * min(scale, 1.0) else: self.hnext = h * scale self.errold = max(err, 1.0e-4) self.reject = False if DEBUG: print 'Accept, ', h return (True, h) else: scale = max(safe * np.power(err, -alpha), minscale) h *= scale if DEBUG: print 'Reject, ', h self.reject = True return (False, h)
def test_exception_message_deprecated(): import exceptions x = exceptions.AssertionError() with OutputCatcher() as output: x.message expected = "" Assert(expected in output.stderr, output.stderr)
def test_exception_message_deprecated(): import exceptions x = exceptions.AssertionError() with OutputCatcher() as output: x.message expected = "DeprecationWarning: BaseException.message has been deprecated as of Python 2.6" Assert(expected in output.stderr)
def test_creation_failure_with_invalid_flag_argument(self): id_ = 'i{0}'.format(uuid.uuid4()) try: self.put_deployment( blueprint_file_name='deployment_with_source_plugin.yaml', blueprint_id=id_, deployment_id=id_, skip_plugins_validation='invalid_arg') raise exceptions.AssertionError("Expected CloudifyClientError") except CloudifyClientError, e: self.assertEqual(400, e.status_code) self.assertEqual( manager_exceptions.BadParametersError. BAD_PARAMETERS_ERROR_CODE, e.error_code)
def successful(self): """ Return whether the call completed without raising an exception. Will raise AssertionError if the result is not ready. """ if not self.ready(): raise exceptions.AssertionError("Function is not ready") res = self._q.get() self._q.put(res) if isinstance(res, Exception): return False return True
def test_creation_failure_when_plugin_not_found_host_agent(self): from cloudify_rest_client.exceptions import DeploymentPluginNotFound id_ = 'i{0}'.format(uuid.uuid4()) try: self.put_deployment(blueprint_file_name='deployment_' 'with_source_plugin_host_agent.yaml', blueprint_id=id_, deployment_id=id_) raise exceptions.AssertionError( "Expected DeploymentPluginNotFound error") except DeploymentPluginNotFound, e: self.assertEqual(400, e.status_code) self.assertEqual( manager_exceptions.DeploymentPluginNotFound.ERROR_CODE, e.error_code)
def dialect_impl(self, dialect): try: return self.impl_dict[dialect] except: # see if the dialect has an adaptation of the TypeDecorator itself adapted_decorator = dialect.type_descriptor(self) if adapted_decorator is not self: result = adapted_decorator.dialect_impl(dialect) self.impl_dict[dialect] = result return result typedesc = dialect.type_descriptor(self.impl) tt = self.copy() if not isinstance(tt, self.__class__): raise exceptions.AssertionError( "Type object %s does not properly implement the copy() method, it must return an object of type %s" % (self, self.__class__)) tt.impl = typedesc self.impl_dict[dialect] = tt return tt
def __init__(self, *args, **kwargs): if not hasattr(self.__class__, 'impl'): raise exceptions.AssertionError( "TypeDecorator implementations require a class-level variable 'impl' which refers to the class of type being decorated" ) self.impl = self.__class__.impl(*args, **kwargs)
def Ellipse_Circle(a, b, N): """ Function for calculating the potential and added mass coefficients for an ellipse where a is the half major axis and b is the half minor axis. When a=b we have a circle. """ print if a == b: print('For a circle with radius R0 = %.2f' % a) print elif a > b: print( 'For an ellipse with half major axis a0 = %.2f' '\n' 'and half minor axis b0 = %.2f' % (a, b)) print else: raise exceptions.AssertionError( 'The major axis a must be larger than the minor axis b') # As required in the text for the assignment # Values for the potential and the added mass coefficients. achieved from # different choice of N that needs to be stored in lists for later use phi11_ = [] Exact_phi_ = [] m11_ = [] m22_ = [] m66_ = [] for N in N_list: print 'With %d segments we have:' % N # Matrix for storing values achieved from the lhs of the equation A = zeros((N, N)) # Array(vector) for storing values for the rhs of the equation B11 = zeros(N) B22 = zeros(N) B66 = zeros(N) dtheta = linspace(0, 2 * pi, N + 1) # division into N segments # Evaluation points x = a * cos( dtheta) # the x position of the start/end point of a segment y = b * sin( dtheta) # the y position of the start/end point of a segment # Collocation points # Centroid of each segment S(i) xbar = (x[1:] + x[:-1]) / 2.0 ybar = (y[1:] + y[:-1]) / 2.0 # Length of each segment dS = sqrt(d(x0,y0)^2 - d(x1,y1)^2) # (x,y) position - next (x,y) position dS = linalg.norm(array([x[1:], y[1:]]) - array([x[:-1], y[:-1]]), axis=0) # Normal vector components of the segments n1 = -(y[1:] - y[:-1]) / dS # -dy/dS n2 = (x[1:] - x[:-1]) / dS # dx/dS n6 = (xbar * n2 - ybar * n1) # x*n2 - y*n1 for i in range(N): # Array transpose to get [x,y] position of a point on the circumference r1 = linalg.norm(array([x[:-1], y[:-1]]).T - array([xbar[i], ybar[i]]), axis=1) r2 = linalg.norm(array([x[1:], y[1:]]).T - array([xbar[i], ybar[i]]), axis=1) # Opening angle of segment S(i) theta = -arccos((dS**2 - r2**2 - r1**2) / (-2 * r2 * r1)) theta[isnan(theta)] = 0 #Calculates the right-hand side of the integral eq.(24) h11 = (log(r1) + log(r2)) * 0.5 * dS h22 = (log(r1) + log(r2)) * 0.5 * dS h66 = (log(r1) + log(r2)) * 0.5 * dS #Adds the angles to the matrix A A[i] = theta # N matrices that are NxN fill_diagonal(A, -pi) #replace diagonal entries with -pi #Adds rhs to the B-arrays B11[i] = sum(n1 * h11) B22[i] = sum(n2 * h22) B66[i] = sum(n6 * h66) # Calculates phi for the three directions # Solve the linear matrix equation A*phi=B phi11 = linalg.solve(A, B11) phi11_.append(phi11) phi22 = linalg.solve(A, B22) phi66 = linalg.solve(A, B66) # Calculates the added mass coefficients m11 = sum(phi11 * n1 * dS) m11_.append(m11) m22 = sum(phi22 * n2 * dS) m22_.append(m22) m66 = sum(phi66 * n6 * dS) m66_.append(m66) if a > b: Exact_m11 = pi * b**2 Error_m11 = Exact_m11 - m11 plot(N, Error_m11, 'r*', markersize=6, label='m_{11}') hold(True) print('The error in the added mass coefficient m11 is %.5f' % Error_m11) Exact_m22 = pi * a**2 Error_m22 = Exact_m22 - m22 plot(N, Error_m22, 'k^', markersize=6, label='m_{22}') hold(True) print('The error in the added mass coefficient m22 is %.5f' % Error_m22) Exact_m66 = (1.0 / 8.0) * pi * ((a**2) - (b**2))**2 Error_m66 = Exact_m66 - m66 plot(N, Error_m66, 'gs', markersize=6, label='m_{66}') hold(True) print('The error in the added mass coefficient m66 is %.5f' % Error_m66) print if a == b: Exact_phi = -(a**2 * xbar) / (xbar**2 + ybar**2) Exact_phi_.append(Exact_phi) Error_phi = abs(Exact_phi - phi11).max() print( 'The maximum error between the exact and the numerical potential is %.5f' % Error_phi) Exact_m11 = pi * a**2 Error_m11 = Exact_m11 - m11 print( 'The maximum error between the exact and the numerical added mass coefficient m11 is %.5f' % Error_m11) print if N == 20: legend(loc='best', numpoints=1) title('Error as a function of the resolution') xlabel('Number of segments N') ylabel('Error in the computed values compared to the exact ones') xlim((0, 1600)) ylim((-10, 600)) show() return m11_, m22_, m66_, Exact_m11, Exact_m22, Exact_m66 # in case of an ellipse
def dy(self, h, RHS_class): # dy estimator. Like RK5, but more -- 12 stages! ytemp = self.gen_array() y = self.y dydx = self.dydx x = self.x if not (y is self.y and dydx is self.dydx and x is self.x): raise exceptions.AssertionError('Oh noes!') # 1 ytemp[:] = self.y + h * dc.a21 * self.dydx[:] # 2 RHS_class.deriv(x + dc.c2 * h, ytemp, self.k2) ytemp[:] = y + h * (dc.a31 * dydx + dc.a32 * self.k2) # 3 RHS_class.deriv(x + dc.c3 * h, ytemp, self.k3) ytemp[:] = y + h * (dc.a41 * dydx + dc.a43 * self.k3) # 4 RHS_class.deriv(x + dc.c4 * h, ytemp, self.k4) ytemp[:] = y + h * (dc.a51 * dydx + dc.a53 * self.k3 + dc.a54 * self.k4) # 5 RHS_class.deriv(x + dc.c5 * h, ytemp, self.k5) ytemp[:] = y + h * (dc.a61 * dydx + dc.a64 * self.k4 + dc.a65 * self.k5) # 6 RHS_class.deriv(x + dc.c6 * h, ytemp, self.k6) ytemp[:] = y + h * (dc.a71 * dydx + dc.a74 * self.k4 + dc.a75 * self.k5 + dc.a76 * self.k6) # 7 RHS_class.deriv(x + dc.c7 * h, ytemp, self.k7) ytemp[:] = y + h * (dc.a81 * dydx + dc.a84 * self.k4 + dc.a85 * self.k5 + dc.a86 * self.k6 + dc.a87 * self.k7) # 8 RHS_class.deriv(x + dc.c8 * h, ytemp, self.k8) ytemp[:] = y + h * (dc.a91 * dydx + dc.a94 * self.k4 + dc.a95 * self.k5 + dc.a96 * self.k6 + dc.a97 * self.k7 + dc.a98 * self.k8) # 9 RHS_class.deriv(x + dc.c9 * h, ytemp, self.k9) ytemp[:] = y + h * (dc.a101 * dydx + dc.a104 * self.k4 + dc.a105 * self.k5 + dc.a106 * self.k6 + dc.a107 * self.k7 + dc.a108 * self.k8 + dc.a109 * self.k9) # 10 RHS_class.deriv(x + dc.c10 * h, ytemp, self.k10) ytemp[:] = y + h * (dc.a111 * dydx + dc.a114 * self.k4 + dc.a115 * self.k5 + dc.a116 * self.k6 + dc.a117 * self.k7 + dc.a118 * self.k8 + dc.a119 * self.k9 + dc.a1110 * self.k10) # 11 RHS_class.deriv(x + dc.c11 * h, ytemp, self.k2) xph = x + h ytemp[:] = y + h * ( dc.a121 * dydx + dc.a124 * self.k4 + dc.a125 * self.k5 + dc.a126 * self.k6 + dc.a127 * self.k7 + dc.a128 * self.k8 + dc.a129 * self.k9 + dc.a1210 * self.k10 + dc.a1211 * self.k2) # 12 RHS_class.deriv(xph, ytemp, self.k3) self.k4[:] = dc.b1 * dydx + dc.b6 * self.k6 + dc.b7 * self.k7 + dc.b8 * self.k8 + dc.b9 * self.k9 + dc.b10 * self.k10 + dc.b11 * self.k2 + dc.b12 * self.k3 # yout: self.yout = y + h * self.k4 # Two error estimators: self.yerr[:] = self.k4 - dc.bhh1 * dydx - dc.bhh2 * self.k9 - dc.bhh3 * self.k3 self.yerr2[:] = dc.er1 * dydx + dc.er6 * self.k6 + dc.er7 * self.k7 + dc.er8 * self.k8 + dc.er9 * self.k9 + dc.er10 * self.k10 + dc.er11 * self.k2 + dc.er12 * self.k3