How to use shrunk method in hypothesis

Best Python code snippet using hypothesis

xBrepFace_tryGetPrimitiveShape.py

Source:xBrepFace_tryGetPrimitiveShape.py Github

copy

Full Screen

1"""2190521,22: Import-related update.3190523-24: Added some functions.4190529: Removed a function.5190530-31: Improved printed output.6190605: Fixed a minor bug.7190617: Improved efficiency of a function.8190619: Added a function.9190721: Argument name change.10190722-24: Refactoring. Changed output of some functions.11190730: More feedback is now returned from a function.12190731: Removed some debug prints.13190809-10: Corrected the default return value in a function.14190822: Modified a comment.15191118-19: Import-related update.16"""1718import Rhino19import Rhino.Geometry as rg20import scriptcontext as sc2122import xPlaneSurface23import xPrimitiveShape242526def tryGetPlane(rgFace0, bMatchToShrunkFace=True, fTolerance=sc.doc.ModelAbsoluteTolerance, bDebug=False):27 28 if bMatchToShrunkFace:29 rgBrep_1Face_Shrunk = rgFace0.DuplicateFace(False)30 rgBrep_1Face_Shrunk.Faces.ShrinkFaces()31 rgFace_Shrunk = rgBrep_1Face_Shrunk.Faces[0]32 rgSrfs_ToTry = rgFace0.UnderlyingSurface(), rgFace_Shrunk.UnderlyingSurface()33 else:34 rgSrfs_ToTry = rgFace0.UnderlyingSurface(),35 36 for i_NotShrunk_Shrunk, rgSrf_ToTry in enumerate(rgSrfs_ToTry):37 rc = xPrimitiveShape.Surface.tryGetPlane(38 rgSrf_ToTry,39 fTolerance=fTolerance,40 bDebug=bDebug)41 if rc[0]:42 if bMatchToShrunkFace: rgBrep_1Face_Shrunk.Dispose()43 rgPlane_Found, fTol_PlaneFound = rc44 if not rgPlane_Found.IsValid:45 return None, "Plane is not valid."46 bShrunkUsed = bool(i_NotShrunk_Shrunk)47 return (rgPlane_Found, fTol_PlaneFound, bShrunkUsed), None48 49 if bMatchToShrunkFace: rgBrep_1Face_Shrunk.Dispose()50 51 return None, "Plane not found within tolerance of {:.2e}.".format(fTolerance)525354def tryGetRoundPrimitive(rgFace0, bMatchToShrunkFace=True, bCylinder=True, bCone=True, bSphere=True, bTorus=True, fTolerance=sc.doc.ModelAbsoluteTolerance, bDebug=False):55 """56 Round primitives are Cone, Cylinder, Sphere, and Torus.57 """58 59 if bDebug:60 reload(xPrimitiveShape)61 62 if bMatchToShrunkFace:63 rgBrep_1Face_Shrunk = rgFace0.DuplicateFace(False)64 rgBrep_1Face_Shrunk.Faces.ShrinkFaces()65 rgFace_Shrunk = rgBrep_1Face_Shrunk.Faces[0]66 rgFaces_ToTest = rgFace0, rgFace_Shrunk67 rgSrfs_ToTry = rgFace0.UnderlyingSurface(), rgFace_Shrunk.UnderlyingSurface()68 else:69 rgSrfs_ToTry = rgFace0.UnderlyingSurface(),70 71 for i_NotShrunk_Shrunk, rgSrf_ToTry in enumerate(rgSrfs_ToTry):72 rc = xPrimitiveShape.Surface.tryGetRoundPrimitive(73 rgSrf0=rgSrf_ToTry,74 bCylinder=bCylinder,75 bCone=bCone,76 bSphere=bSphere,77 bTorus=bTorus,78 fTolerance=fTolerance,79 bDebug=bDebug)80 if rc[0]:81 if bMatchToShrunkFace: rgBrep_1Face_Shrunk.Dispose()82 rgShape_Found, fTol_ShapeFound = rc83 if not rgShape_Found.IsValid:84 return None, "{} is not valid.".format(rgShape_Found.GetType().Name)85 bShrunkUsed = bool(i_NotShrunk_Shrunk)86 return (rgShape_Found, fTol_ShapeFound, bShrunkUsed), None87 88 if bMatchToShrunkFace: rgBrep_1Face_Shrunk.Dispose()89 90 return None, "Round primitive not found within tolerance of {:.2e}.".format(fTolerance)919293def tryGetPlaneSurface(rgFace0, bMatchToShrunkFace=True, fTolerance=0.1*sc.doc.ModelAbsoluteTolerance, bDebug=False):94 """95 Return on success:96 PlaneSurface at a size relative to the BrepFace97 fTol_Used98 bShrunkUsed99 Return on fail:100 None101 String: Log statement.102 """103 104 rgSrf_Face0 = rgFace0.UnderlyingSurface()105 106 if isinstance(rgSrf_Face0, rg.PlaneSurface):107 return None, "Surface is already a PlaneSurface."108 109 rc = tryGetPlane(110 rgFace0,111 bMatchToShrunkFace=bMatchToShrunkFace,112 fTolerance=fTolerance,113 bDebug=bDebug)114 if rc[0] is None:115 return rc116 else:117 rgPlane1, fTol_Used, bShrunkUsed = rc[0]118 119 rgSrf1 = xPlaneSurface.createFromPlaneAndObjectSize(120 rgPlane=rgPlane1,121 obj_ForSize=rgFace0,122 bDebug=bDebug)123 if rgSrf1 is None:124 return None, "createFromPlaneAndObjectSize fail."125 126 return (rgSrf1, fTol_Used, bShrunkUsed), None127128129def tryGetRevSurfaceOfPrimitiveShape(rgFace0, bMatchToShrunkFace=True, bCylinder=True, bCone=True, bSphere=True, bTorus=True, fTolerance=0.1*sc.doc.ModelAbsoluteTolerance, bDebug=False):130 """131 """132 rgSrf0 = rgFace0.UnderlyingSurface()133 134 rc = tryGetRoundPrimitive(135 rgFace0=rgFace0,136 bMatchToShrunkFace=bMatchToShrunkFace,137 bCylinder=bCylinder,138 bCone=bCone,139 bSphere=bSphere,140 bTorus=bTorus,141 fTolerance=fTolerance,142 bDebug=bDebug)143 if rc[0] is None: return None, "No matching primitive shape found."144 145 rgShape1, fTol_PrimitiveMatch, bFoundUsingShunkFace = rc[0]146 147 if isinstance(rgSrf0, rg.RevSurface):148 if isinstance(rgShape1, rg.Cylinder) or isinstance(rgShape1, rg.Cone):149 if rgSrf0.IsClosed(0) or rgSrf0.IsClosed(1):150 return None, "Surface is already a RevSurface of {} shape.".format(rgShape1.GetType().Name)151 152 if isinstance(rgShape1, rg.Sphere) or isinstance(rgShape1, rg.Torus):153 if rgSrf0.IsClosed(0) and rgSrf0.IsClosed(1):154 return None, "Surface is already a RevSurface of {} shape.".format(rgShape1.GetType().Name)155 156 typeShape1 = rgShape1.GetType()157 if not rgShape1.IsValid:158 return None, "{} is not valid.".format(typeShape1)159 160 if typeShape1 == rg.Plane:161 rgPlane = rgShape1162 sType = "Plane"163 rgSrf_Converted = xPlaneSurface.createFromPlaneAndObjectSize(164 rgPlane, rgFace0)165 if rgSrf_Converted is not None:166 return (rgSrf_Converted, fTol_PrimitiveMatch, bFoundUsingShunkFace), None167 else:168 sPrint = 'rgSrf_Converted'169 return None, sPrint + ':', eval(sPrint)170 171 elif typeShape1 == rg.Cylinder:172 rgCyl = rgShape1173 sType = "Cylinder"174 # Fix cylinder that is infinite (has 0 height).175 if not rgCyl.IsFinite:176 if bDebug: print "Making cylinder finite..."177 rgBbox_Face = rgFace0.GetBoundingBox(True)178 fAddLen = 1.1 * rgBbox_Face.Min.DistanceTo(rgBbox_Face.Max)179 rgCyl.Height1 = -fAddLen180 rgCyl.Height2 = fAddLen181 182 183 # for sAttr in dir(rgCyl):184 # if (sAttr != 'Unset' and sAttr != '__doc__' and185 # not callable(getattr(rgCyl, sAttr))):186 # sPrint = 'rgCyl.' + sAttr; print sPrint + ':', eval(sPrint)187 188 # sPrint = 'dir(rgCyl)'; print sPrint + ':', eval(sPrint)189 #sPrint = 'rgCyl.Unset'; print sPrint + ':', eval(sPrint)190 # for sAttr in dir(rgCyl):191 # if (sAttr != 'Unset' and sAttr != '__doc__' and192 # not callable(getattr(rgCyl, sAttr))):193 # sPrint = 'rgShape1.' + sAttr; print sPrint + ':', eval(sPrint)194 195 elif rgCyl.TotalHeight < 2.0*sc.doc.ModelAbsoluteTolerance:196 if bDebug:197 print "Resultant height of cylinder is {}.".format(198 rgCyl.TotalHeight)199 print "Using 100 times model's absolute tolerance."200 rgCyl.Height1 = -100.0*sc.doc.ModelAbsoluteTolerance201 rgCyl.Height2 = 100.0*sc.doc.ModelAbsoluteTolerance202 else:203 # Increase length of cylinder so that surface is always larger than trim.204 rgBbox_Face = rgFace0.GetBoundingBox(False)205 rgLines = rgBbox_Face.GetEdges()206 fMaxLen = 0207 for rgLine in rgLines:208 if rgLine.Length > fMaxLen: fMaxLen = rgLine.Length209 fAddLen = 1.1 * fMaxLen210 #fAddLen = 1.1 * rgBbox_Face.Min.DistanceTo(rgBbox_Face.Max)211 rgCyl.Height1 = -fAddLen212 rgCyl.Height2 = fAddLen213 214 rgSrf_Converted = rgCyl.ToRevSurface()215 if rgSrf_Converted is not None:216 return (rgSrf_Converted, fTol_PrimitiveMatch, bFoundUsingShunkFace), None217 else:218 return None, "RevSurface could not be obtained from Cylinder."219 220 elif typeShape1 == rg.Cone:221 rgCone = rgShape1222 sType = "Cone"223 rgSrf_Converted = rgCone.ToRevSurface()224 if rgSrf_Converted is not None:225 return (rgSrf_Converted, fTol_PrimitiveMatch, bFoundUsingShunkFace), None226 else:227 return None, "RevSurface could not be obtained from Cone."228 229 # Increase length of cone so that surface is always larger than trim.230 xf = rg.Transform.Scale(rgCone.ApexPoint, 1.1)231 rgSrf_Converted.Transform(xf)232 233 elif typeShape1 == rg.Sphere:234 rgSphere = rgShape1235 sType = "Sphere"236 rgSrf_Converted = rgSphere.ToRevSurface()237 if rgSrf_Converted is not None:238 return (rgSrf_Converted, fTol_PrimitiveMatch, bFoundUsingShunkFace), None239 else:240 return None, "RevSurface could not be obtained from Sphere."241 242 elif typeShape1 == rg.Torus:243 rgTorus = rgShape1244 sType = "Torus"245 rgSrf_Converted = rgTorus.ToRevSurface()246 if rgSrf_Converted is not None:247 return (rgSrf_Converted, fTol_PrimitiveMatch, bFoundUsingShunkFace), None248 else:249 return None, "RevSurface could not be obtained from Torus."250 251 return None, "What happened?"252 253 s = " {} found".format(sType)254 s += " matching {} underlying surface".format(255 "shrunk" if bFoundUsingShunkFace else "full")256 s += " at a tolerance of {}.".format(fTol_PrimitiveMatch)257 258 return (rgSrf_Converted, fTol_PrimitiveMatch, bFoundUsingShunkFace), s259260261def tryGetPrimitiveShape(rgFace0, bMatchToShrunkFace=True, bPlane=True, bCylinder=True, bCone=True, bSphere=True, bTorus=True, fTolerance=1e-9, bDebug=False):262 """263 Updated in May of 2019. Based on hasPrimitiveShape.264 265 Returns:266 On Success (regardless if primitive is found):267 tuple:268 (269 tuple: (rg.Plane or rg.Cylinder or rg.Cone or rg.Sphere or rg.Torus,270 float of tolerance used to find shape,271 'shrunk' or 'not shrunk')272 ,273 str: (Fail log)274 )275 On fail: None, None276 """277 rgSrf_Face0 = rgFace0.UnderlyingSurface()278 279280 if bPlane:281 rc = tryGetPlane(282 rgFace0,283 bMatchToShrunkFace=bMatchToShrunkFace,284 fTolerance=fTolerance,285 bDebug=bDebug)286 if rc[0] is not None:287 return rc288289 if bCylinder or bCone or bSphere or bTorus:290 rc = tryGetRoundPrimitive(291 rgFace0=rgFace0,292 bMatchToShrunkFace=bMatchToShrunkFace,293 bCylinder=bCylinder,294 bCone=bCone,295 bSphere=bSphere,296 bTorus=bTorus,297 fTolerance=fTolerance,298 bDebug=bDebug)299 if rc[0] is not None:300 return rc301 302 return None, None ...

Full Screen

Full Screen

bigauto.py

Source:bigauto.py Github

copy

Full Screen

1#!/usr/bin/env python2# Copyright © 1997, 1999, 2000 Progiciels Bourbeau-Pinard inc.3# François Pinard <pinard@iro.umontreal.ca>, 1997.4"""\5Produce statistics from the results of the bigauto check.6Usage: bigauto [RECODE_OPTION]... [CHARSET_OPTION]...7This script makes a simple analysis for the connectivity of the various8charsets and produce a report on standard output. The reports include9statistics about the number of steps before and after optimisation.10The option `-hNAME' would affect the resulting output, because there are11more merging rules when this option is in effect. Other options affect12the result: `-d', `-g' and, notably, `-s'.13All non-option arguments are interpreted as charset names. If any is given,14the study is limited to those recodings having any of the given charsets15both as a starting and ending points. If there is no such non-option16argument, all possible possible recodings are considered.17"""18import os, string, sys19def main(*arguments):20 recode_options = []21 charset_options = []22 for argument in arguments:23 if arguments[0] == '-':24 recode_options.append(argument)25 else:26 charset_options.append(argument)27 work_name = '/tmp/bigauto-data'28 if os.path.exists(work_name):29 os.remove(work_name)30 create_data(work_name, recode_options, charset_options)31 report = Report()32 report.digest_data(open(work_name).readline)33 report.produce_report(sys.stdout.write)34 os.remove(work_name)35def create_data(name, recode_options, charset_options):36 # Get the list of charsets.37 if charset_options:38 charsets = charset_options39 else:40 charsets = []41 for line in os.popen('recode -l').readlines():42 charset = string.split(line)[0]43 if charset[0] in ':/':44 continue45 charsets.append(charset)46 # Do the work, calling a subshell once per `before' value.47 recode_call = 'recode </dev/null -v %s' % string.join(recode_options)48 for before in charsets:49 if before in ('count-characters', 'dump-with-names',50 'flat', 'Texinfo'):51 continue52 sys.stderr.write("Before charset: %s\n" % before)53 write = os.popen('sh >>%s 2>&1' % name, 'w').write54 write('export LANGUAGE; LANGUAGE=C\n'55 'export LANG; LANG=C\n'56 'export LC_ALL; LC_ALL=C\n')57 for after in charsets:58 if after != before:59 write("%s '%s..%s'\n" % (recode_call, before, after))60class Report:61 def __init__(self):62 self.recode_calls = 063 self.original_count = {}64 self.original_example = {}65 self.original_total = 066 self.shrunk_count = {}67 self.shrunk_example = {}68 self.shrunk_total = 069 def digest_data(self, readline):70 lensep = len(os.linesep)71 line = readline()72 while line:73 type, request = string.split(line[:-lensep], ':', 1)74 if type == 'Request':75 steps = self.get_steps(request)76 self.count_original_request(steps, request)77 line = readline()78 if line:79 if len(string.split(line[:-lensep], ':', 1)) != 2:80 print '*', line,81 type, shrunk_to = string.split(line[:-lensep], ':', 1)82 if type == 'Shrunk to':83 steps = self.get_steps(shrunk_to)84 self.count_shrunk_request(steps, shrunk_to)85 line = readline()86 else:87 self.count_shrunk_request(steps, request)88 else:89 self.count_shrunk_request(steps, request)90 else:91 sys.stderr.write('Unrecognized line: ' + line)92 line = readline()93 def get_steps(self, text):94 if text == '*mere copy*':95 return 096 if text[-1] == '/':97 text = text[:-1]98 text = string.replace(text, '/..', '..')99 count = 0100 for fragment in string.split(text, '..'):101 count = count + len(string.split(fragment, '/'))102 return count - 1103 def count_original_request(self, steps, text):104 self.recode_calls = self.recode_calls + 1105 if self.original_count.has_key(steps):106 self.original_count[steps] = self.original_count[steps] + 1107 else:108 self.original_count[steps] = 1109 self.original_example[steps] = string.strip(text)110 if self.original_total == 0:111 self.original_minimum = self.original_maximum = steps112 else:113 if steps < self.original_minimum:114 self.original_minimum = steps115 if steps > self.original_maximum:116 self.original_maximum = steps117 self.original_total = self.original_total + steps118 def count_shrunk_request(self, steps, text):119 if self.shrunk_count.has_key(steps):120 self.shrunk_count[steps] = self.shrunk_count[steps] + 1121 else:122 self.shrunk_count[steps] = 1123 self.shrunk_example[steps] = string.strip(text)124 if self.shrunk_total == 0:125 self.shrunk_minimum = self.shrunk_maximum = steps126 else:127 if steps < self.shrunk_minimum:128 self.shrunk_minimum = steps129 if steps > self.shrunk_maximum:130 self.shrunk_maximum = steps131 self.shrunk_total = self.shrunk_total + steps132 def produce_report(self, write):133 if self.recode_calls == 0:134 sys.stderr.write("No call to report\n")135 return136 write("\n"137 "Optimisation Original Shrunk\n"138 " .-------------------\n"139 "Minimum | %2d %2d\n"140 "Maximum | %2d %2d\n"141 "Average | %4.1f %4.1f\n"142 % (self.original_minimum, self.shrunk_minimum,143 self.original_maximum, self.shrunk_maximum,144 float(self.original_total) / float(self.recode_calls),145 float(self.shrunk_total) / float(self.recode_calls)))146 write("\n"147 "Histogram for original requests\n")148 for steps in range(self.original_minimum, self.original_maximum+1):149 if self.original_count.has_key(steps):150 write("%5d steps, %5d times %s\n"151 % (steps, self.original_count[steps],152 self.original_example[steps]))153 write("\n"154 "Histogram for shrunk requests\n")155 for steps in range(self.shrunk_minimum, self.shrunk_maximum+1):156 if self.shrunk_count.has_key(steps):157 write("%5d steps, %5d times %s\n"158 % (steps, self.shrunk_count[steps],159 self.shrunk_example[steps]))160if __name__ == '__main__':...

Full Screen

Full Screen

explore_funcs.py

Source:explore_funcs.py Github

copy

Full Screen

1import numpy as np 2import pandas as pd 3import scipy as sp4import seaborn as sns5import matplotlib.pyplot as plt6from functools import partial7from jwpy.betabinom import betabinom8def summarize_df(df, head=5, dropna=False):9 '''10 Quick summary of a pandas DataFrame.11 Args:12 df:13 head:14 dropna:15 '''16 # show variable types and numbers of unique levels17 summ = pd.DataFrame(18 [df.dtypes, df.nunique(dropna=dropna), df.isnull().mean(0)],19 index=['dtype', 'nunique', '%missing'])20 # append head21 summ = pd.concat([summ, df.head(head)], axis=0)22 print('{} rows x {} columns'.format(*df.shape))23 return summ24def shrink(values, a, b):25 '''26 Apply empirical Bayes shrinkage to binomial counts for a given Beta prior.27 Args:28 values:29 a:30 b: 31 '''32 zeros, ones = ((values==0).sum(), (values==1).sum())33 return (a + ones)/(a + b + zeros + ones)34def aov_xtab(values, index, columns, figsize=(13, 8), **kwargs):35 '''36 Exploratory plot for pairs of categorical predictors/features.37 Args:38 values:39 index:40 columns:41 figsize:42 kwargs:43 '''44 # group the variables into a DataFrame45 dat = pd.DataFrame({46 'values': values,47 'index': index,48 'columns': columns})49 # fit the beta-binomial model50 endog = pd.DataFrame({51 'k': dat.groupby(['index', 'columns'])['values'].sum(),52 'n': dat.groupby(['index', 'columns'])['values'].count()})53 a, b = betabinom(endog=endog).fit(**kwargs).params54 m = a / (a + b)55 # compute the shrunken cell means and sort the matrix by row/column means56 shrunk = pd.pivot_table(dat, values='values', index='index',57 columns='columns',58 aggfunc=partial(shrink, a=a, b=b), fill_value=m)59 new_index = shrunk.index[shrunk.mean(1).argsort()[::-1]]60 new_columns = shrunk.columns[shrunk.mean(0).argsort()[::-1]]61 shrunk = shrunk.reindex_axis(new_index, axis=0)62 shrunk = shrunk.reindex_axis(new_columns, axis=1)63 # compute the numbers of obs. per cell and sort by the same means as above64 annot = pd.crosstab(dat['index'], dat['columns'])65 annot = annot.reindex_axis(new_index, axis=0)66 annot = annot.reindex_axis(new_columns, axis=1)67 # print stuff68 print('SD of row means: {}'.format(shrunk.mean(1).std()))69 print('SD of column means: {}'.format(shrunk.mean(0).std()))70 interaction = shrunk.sub(shrunk.mean(1), axis=0).sub(shrunk.mean(0), axis=1)71 print('SD of row*column interaction: {}'.format(interaction.stack().std()))72 # plot!73 fig, ax = plt.subplots(figsize=figsize)74 return sns.heatmap(shrunk, annot=annot, fmt='.0f');75def shrink_1d(target, group, sort=True, **kwargs):76 '''77 Exploratory plot for pairs of categorical predictors/features.78 Args:79 target: binary (integer or boolean) DV80 group: grouping factor81 sort:82 kwargs:83 '''84 # group the variables into a DataFrame85 dat = pd.DataFrame({86 'target': target,87 'group': group})88 # fit the beta-binomial model89 endog = pd.DataFrame({90 'k': dat.groupby('group')['target'].sum(),91 'n': dat.groupby('group')['target'].count()})92 a, b = betabinom(endog=endog).fit(**kwargs).params93 m = a / (a + b)94 # compute the shrunken cell means and sort the matrix by row/column means95 shrunk = pd.pivot_table(dat, values='values', index='index',96 columns='columns', aggfunc=partial(shrink, a=a, b=b), fill_value=m)97 new_index = shrunk.index[shrunk.mean(1).argsort()[::-1]]98 new_columns = shrunk.columns[shrunk.mean(0).argsort()[::-1]]99 shrunk = shrunk.reindex_axis(new_index, axis=0)100 shrunk = shrunk.reindex_axis(new_columns, axis=1)101 # compute the numbers of obs. per cell and sort by the same means as above102 annot = pd.crosstab(dat['index'], dat['columns'])103 annot = annot.reindex_axis(new_index, axis=0)104 annot = annot.reindex_axis(new_columns, axis=1)105 # print stuff106 print('SD of row means: {}'.format(shrunk.mean(1).std()))107 print('SD of column means: {}'.format(shrunk.mean(0).std()))108 interaction = shrunk.sub(shrunk.mean(1), axis=0).sub(shrunk.mean(0), axis=1)109 print('SD of row*column interaction: {}'.format(interaction.stack().std()))110 # plot!111 fig, ax = plt.subplots(figsize=figsize)...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run hypothesis 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