Best Python code snippet using pandera_python
graph.py
Source:graph.py
...46 deps.append(d)47 return deps48 49def addDependency(master,slave,dep={},invdep={}):50 #print master.__hash__() , " => ", slave.__hash__(), " ", master , " => ", slave51 if master in dep:52 dep[master].add(slave)53 else:54 dep[master]= set([slave])55 if slave in invdep:56 invdep[slave].add(master)57 else:58 invdep[slave] = set([master])59 60def addDependencies(master,slaves,dep={},invdep={}):61 for slave in slaves:62 addDependency(master,slave,dep = dep,invdep = invdep)63 for slave in slaves:64 dependencyGraph(slave,dep = dep,invdep = invdep)65def dependencyGraph(s,dep = {},invdep = {}):66 if isinstance(s,SX):67 addDependencies(s,list(s.data()),dep = dep,invdep = invdep)68 elif isinstance(s,SXElement):69 if not(s.isLeaf()):70 addDependencies(s,getDeps(s),dep = dep,invdep = invdep)71 elif isinstance(s,MX):72 addDependencies(s,getDeps(s),dep = dep,invdep = invdep)73 return (dep,invdep)74 75class DotArtist:76 sparsitycol = "#eeeeee"77 def __init__(self,s,dep={},invdep={},graph=None,artists={}):78 self.s = s79 self.dep = dep80 self.invdep = invdep81 self.graph = graph82 self.artists = artists83 84 def hasPorts(self):85 return False86 87 def drawSparsity(self,s,id=None,depid=None,graph=None,nzlabels=None):88 if id is None:89 id = str(s.__hash__())90 if depid is None:91 depid = str(s.getDep(0).__hash__())92 if graph is None:93 graph = self.graph94 sp = s.sparsity()95 deps = getDeps(s)96 if nzlabels is None:97 nzlabels = map(str,range(sp.size()))98 nzlabelcounter = 099 if s.size()==s.numel():100 graph.add_node(pydot.Node(id,label="%d x %d" % (s.size1(),s.size2()),shape='rectangle',color=self.sparsitycol,style="filled"))101 else:102 label = '<<TABLE BORDER="0" CELLBORDER="1" CELLSPACING="0">'103 label+="<TR><TD COLSPAN='%d'><font color='#666666'>%s</font></TD></TR>" % (s.size2(), s.dimString())104 for i in range(s.size1()):105 label+="<TR>"106 for j in range(s.size2()):107 k = sp.getNZ_const(i,j)108 if k==-1:109 label+="<TD>.</TD>"110 else:111 label+="<TD PORT='f%d' BGCOLOR='%s'>%s</TD>" % (k,self.sparsitycol,nzlabels[nzlabelcounter])112 nzlabelcounter +=1113 label+="</TR>"114 label+="</TABLE>>"115 graph.add_node(pydot.Node(id,label=label,shape='plaintext'))116 graph.add_edge(pydot.Edge(depid,id))117 118class MXSymbolicArtist(DotArtist):119 def hasPorts(self):120 return True121 122 def draw(self):123 s = self.s124 graph = self.graph125 sp = s.sparsity()126 row = sp.row()127 col = "#990000"128 if s.size() == s.numel() and s.size()==1:129 # The Matrix grid is represented by a html table with 'ports'130 graph.add_node(pydot.Node(str(self.s.__hash__())+":f0",label=s.getName(),shape='rectangle',color=col))131 else:132 # The Matrix grid is represented by a html table with 'ports'133 label = '<<TABLE BORDER="0" CELLBORDER="1" CELLSPACING="0" COLOR="%s">' % col134 label+="<TR><TD COLSPAN='%d'>%s: <font color='#666666'>%s</font></TD></TR>" % (s.size2(),s.getName(), s.dimString())135 for i in range(s.size1()):136 label+="<TR>"137 for j in range(s.size2()):138 k = sp.getNZ_const(i,j)139 if k==-1:140 label+="<TD>.</TD>"141 else:142 label+="<TD PORT='f%d' BGCOLOR='#eeeeee'> <font color='#666666'>(%d,%d | %d)</font> </TD>" % (k,i,j,k)143 label+="</TR>"144 label+="</TABLE>>"145 graph.add_node(pydot.Node(str(self.s.__hash__()),label=label,shape='plaintext'))146 147# class MXMappingArtist(DotArtist):148# def draw(self):149# s = self.s150# graph = self.graph151# sp = s.sparsity()152# row = sp.row()153 154 155# # Note: due to Mapping restructuring, this is no longer efficient code156# deps = getDeps(s)157 158# depind = s.getDepInd()159# nzmap = sum([s.mapping(i) for i in range(len(deps))])160 161# for k,d in enumerate(deps):162# candidates = map(hash,filter(lambda i: i.isMapping(),self.invdep[d]))163# candidates.sort()164# if candidates[0] == hash(s):165# graph.add_edge(pydot.Edge(str(d.__hash__()),"mapinput" + str(d.__hash__())))166 167# graph = pydot.Cluster('clustertest' + str(s.__hash__()), rank='max', label='Mapping')168# self.graph.add_subgraph(graph)169 170 171# colors = ['#eeeecc','#ccccee','#cceeee','#eeeecc','#eeccee','#cceecc']172 173# for k,d in enumerate(deps):174# spd = d.sparsity()175# #ipdb.set_trace()176# # The Matrix grid is represented by a html table with 'ports'177# candidates = map(hash,filter(lambda i: i.isMapping(),self.invdep[d]))178# candidates.sort()179# if candidates[0] == hash(s):180# label = '<<TABLE BORDER="0" CELLBORDER="1" CELLSPACING="0" COLOR="#0000aa">'181# if not(d.numel()==1 and d.numel()==d.size()): 182# label+="<TR><TD COLSPAN='%d' BGCOLOR='#dddddd'><font>%s</font></TD></TR>" % (d.size2(), d.dimString())183# for i in range(d.size1()):184# label+="<TR>"185# for j in range(d.size2()):186# kk = spd.getNZ_const(i,j)187# if kk==-1:188# label+="<TD>.</TD>"189# else:190# label+="<TD PORT='f%d' BGCOLOR='%s'> <font color='#666666'>%d</font> </TD>" % (kk,colors[k],kk)191# label+="</TR>"192# label+="</TABLE>>"193# graph.add_node(pydot.Node("mapinput" + str(d.__hash__()),label=label,shape='plaintext'))194# graph.add_edge(pydot.Edge("mapinput" + str(d.__hash__()),str(s.__hash__())))195 196# # The Matrix grid is represented by a html table with 'ports'197# label = '<<TABLE BORDER="0" CELLBORDER="1" CELLSPACING="0">'198# if not(s.numel()==1 and s.numel()==s.size()): 199# label+="<TR><TD COLSPAN='%d'><font color='#666666'>%s</font></TD></TR>" % (s.size2(), s.dimString())200# for i in range(s.size1()):201# label+="<TR>"202# for j in range(s.size2()):203# k = sp.getNZ_const(i,j)204# if k==-1:205# label+="<TD>.</TD>"206# else:207# label+="<TD PORT='f%d' BGCOLOR='%s'> <font color='#666666'>%d</font> </TD>" % (k,colors[depind[k]],nzmap[k])208# label+="</TR>"209# label+="</TABLE>>"210# graph.add_node(pydot.Node(str(self.s.__hash__()),label=label,shape='plaintext'))211 212 213class MXEvaluationArtist(DotArtist):214 def draw(self):215 s = self.s216 graph = self.graph217 sp = s.sparsity()218 row = sp.row()219 220 221 deps = getDeps(s)222 223 f = s.getFunction()224 225 for k,d in enumerate(deps):226 graph.add_edge(pydot.Edge(str(d.__hash__()),"funinput" + str(s.__hash__())+ ":f%d" % k,rankdir="LR"))227 228 graph = pydot.Cluster(str(s.__hash__()), rank='max', label='Function:\n %s' % f.getOption("name"))229 self.graph.add_subgraph(graph)230 231 s = (" %d inputs: |" % f.getNumInputs()) + " | ".join("<f%d> %d" % (i,i) for i in range(f.getNumInputs()))232 graph.add_node(pydot.Node("funinput" + str(self.s.__hash__()),label=s,shape='Mrecord'))233 s = (" %d outputs: |" % f.getNumOutputs())+ " | ".join("<f%d> %d" % (i,i) for i in range(f.getNumOutputs()))234 graph.add_node(pydot.Node(str(self.s.__hash__()),label=s,shape='Mrecord'))235 236 237class MXConstantArtist(DotArtist):238 def hasPorts(self):239 return True240 def draw(self):241 s = self.s242 graph = self.graph243 sp = s.sparsity()244 row = sp.row()245 M = s.getMatrixValue()246 col = "#009900"247 if s.size() == s.numel() and s.size() == 1:248 graph.add_node(pydot.Node(str(self.s.__hash__())+":f0",label=M[0,0],shape='rectangle',color=col))249 else:250 # The Matrix grid is represented by a html table with 'ports'251 label = '<<TABLE BORDER="0" CELLBORDER="1" CELLSPACING="0" COLOR="%s">' % col252 label+="<TR><TD COLSPAN='%d'><font color='#666666'>%s</font></TD></TR>" % (s.size2(), s.dimString())253 for i in range(s.size1()):254 label+="<TR>"255 for j in range(s.size2()):256 k = sp.getNZ_const(i,j)257 if k==-1:258 label+="<TD>.</TD>"259 else:260 label+="<TD PORT='f%d' BGCOLOR='#eeeeee'> %s </TD>" % (k,M[i,j])261 label+="</TR>"262 label+="</TABLE>>"263 graph.add_node(pydot.Node(str(self.s.__hash__()),label=label,shape='plaintext'))264class MXGenericArtist(DotArtist):265 def draw(self):266 k = self.s267 graph = self.graph268 dep = getDeps(k)269 show_sp = not(all([d.sparsity()==k.sparsity() for d in dep]))270 271 if show_sp:272 op = "op"273 self.drawSparsity(k,depid=op + str(k.__hash__()))274 else:275 op = ""276 277 if len(dep)>1:278 # Non-commutative operators are represented by 'record' shapes.279 # The dependencies have different 'ports' where arrows should arrive.280 s = getOperatorRepresentation(self.s,["| <f%d> | " %i for i in range(len(dep))])281 if s.startswith("(|") and s.endswith("|)"):282 s=s[2:-2]283 284 graph.add_node(pydot.Node(op + str(k.__hash__()),label=s,shape='Mrecord'))285 for i,n in enumerate(dep):286 graph.add_edge(pydot.Edge(str(n.__hash__()),op + str(k.__hash__())+":f%d" % i))287 else:288 s = getOperatorRepresentation(k,["."])289 self.graph.add_node(pydot.Node(op + str(k.__hash__()),label=s,shape='oval'))290 for i,n in enumerate(dep):291 self.graph.add_edge(pydot.Edge(str(n.__hash__()),op + str(k.__hash__())))292class MXGetNonzerosArtist(DotArtist):293 def draw(self):294 s = self.s295 graph = self.graph296 n = getDeps(s)[0]297 298 299 show_sp = not(s.size() == s.numel() and s.size() == 1)300 301 if show_sp:302 op = "op"303 self.drawSparsity(s,depid=op + str(s.__hash__()))304 else:305 op = ""306 307 sp = s.sparsity()308 row = sp.row()309 M = s.mapping()310 col = "#333333"311 if s.size() == s.numel() and s.size() == 1:312 graph.add_node(pydot.Node(op+str(s.__hash__())+":f0",label="[%s]" % str(M[0,0]),shape='rectangle',style="filled",fillcolor='#eeeeff'))313 else:314 # The Matrix grid is represented by a html table with 'ports'315 label = '<<TABLE BORDER="0" CELLBORDER="1" CELLSPACING="0" COLOR="%s">' % col316 label+="<TR><TD COLSPAN='%d' PORT='entry'>getNonzeros</TD></TR>" % (s.size2())317 for i in range(s.size1()):318 label+="<TR>"319 for j in range(s.size2()):320 k = sp.getNZ_const(i,j)321 if k==-1:322 label+="<TD>.</TD>"323 else:324 label+="<TD PORT='f%d' BGCOLOR='#eeeeff'> %s </TD>" % (k,M[i,j])325 label+="</TR>"326 label+="</TABLE>>"327 graph.add_node(pydot.Node(op+str(s.__hash__()),label=label,shape='plaintext'))328 self.graph.add_edge(pydot.Edge(str(n.__hash__()),op+str(s.__hash__())))329class MXSetNonzerosArtist(DotArtist):330 def draw(self):331 s = self.s332 graph = self.graph333 entry = getDeps(s)[0]334 target = getDeps(s)[1]335 336 337 show_sp = not(all([d.sparsity()==s.sparsity() for d in getDeps(s)]))338 339 if show_sp:340 op = "op"341 self.drawSparsity(s,depid=op + str(s.__hash__()))342 else:343 op = ""344 345 sp = target.sparsity()346 row = sp.row()347 M = list(s.mapping())348 Mk = 0 349 col = "#333333"350 # The Matrix grid is represented by a html table with 'ports'351 label = '<<TABLE BORDER="0" CELLBORDER="1" CELLSPACING="0" COLOR="%s">' % col352 label+="<TR><TD COLSPAN='%d' PORT='entry'>setNonzeros</TD></TR>" % (s.size2())353 for i in range(s.size1()):354 label+="<TR>"355 for j in range(s.size2()):356 k = entry.sparsity().getNZ_const(i,j)357 if k==-1 or Mk>= len(M) or k != M[Mk]:358 label+="<TD>.</TD>"359 if Mk< len(M)-1 and M[Mk]==-1 and k!=-1: Mk+=1360 else:361 label+="<TD PORT='f%d' BGCOLOR='#eeeeff'> %s </TD>" % (Mk,Mk)362 Mk+=1 363 label+="</TR>"364 label+="</TABLE>>"365 graph.add_node(pydot.Node(op+str(s.__hash__()),label=label,shape='plaintext'))366 self.graph.add_edge(pydot.Edge(str(entry.__hash__()),op+str(s.__hash__())+':entry'))367 self.graph.add_edge(pydot.Edge(str(target.__hash__()),op+str(s.__hash__())))368class MXAddNonzerosArtist(DotArtist):369 def draw(self):370 s = self.s371 graph = self.graph372 entry = getDeps(s)[0]373 target = getDeps(s)[1]374 show_sp = not(all([d.sparsity()==s.sparsity() for d in getDeps(s)]))375 376 if show_sp:377 op = "op"378 self.drawSparsity(s,depid=op + str(s.__hash__()))379 else:380 op = ""381 382 sp = target.sparsity()383 row = sp.row()384 M = list(s.mapping())385 Mk = 0 386 col = "#333333"387 # The Matrix grid is represented by a html table with 'ports'388 label = '<<TABLE BORDER="0" CELLBORDER="1" CELLSPACING="0" COLOR="%s">' % col389 label+="<TR><TD COLSPAN='%d' PORT='entry'>addNonzeros</TD></TR>" % (s.size2())390 for i in range(s.size1()):391 label+="<TR>"392 for j in range(s.size2()):393 k = sp.getNZ_const(i,j)394 if k==-1 or Mk>= len(M) or k != M[Mk]:395 label+="<TD>.</TD>"396 if Mk< len(M)-1 and M[Mk]==-1 and k!=-1: Mk+=1397 else:398 label+="<TD PORT='f%d' BGCOLOR='#eeeeff'> %s </TD>" % (Mk,Mk)399 Mk+=1 400 label+="</TR>"401 label+="</TABLE>>"402 graph.add_node(pydot.Node(op+str(s.__hash__()),label=label,shape='plaintext'))403 self.graph.add_edge(pydot.Edge(str(entry.__hash__()),op+str(s.__hash__())+':entry'))404 self.graph.add_edge(pydot.Edge(str(target.__hash__()),op+str(s.__hash__())))405 406 407class MXOperationArtist(DotArtist):408 def draw(self):409 k = self.s410 graph = self.graph411 dep = getDeps(k)412 413 show_sp = True414 415 if k.isUnary() and dep[0].sparsity()==k.sparsity():416 show_sp = False417 if k.isBinary() and dep[0].sparsity()==k.sparsity() and dep[1].sparsity()==k.sparsity():418 show_sp = False419 420 if show_sp:421 op = "op"422 self.drawSparsity(k,depid=op + str(k.__hash__()))423 else:424 op = ""425 426 if not(k.isCommutative()):427 # Non-commutative operators are represented by 'record' shapes.428 # The dependencies have different 'ports' where arrows should arrive.429 s = getOperatorRepresentation(self.s,["| <f0> | ", " | <f1> |"])430 if s.startswith("(|") and s.endswith("|)"):431 s=s[2:-2]432 433 graph.add_node(pydot.Node(op + str(k.__hash__()),label=s,shape='Mrecord'))434 for i,n in enumerate(dep):435 graph.add_edge(pydot.Edge(str(n.__hash__()),op + str(k.__hash__())+":f%d" % i))436 else: 437 # Commutative operators can be represented more compactly as 'oval' shapes.438 s = getOperatorRepresentation(k,[".", "."])439 if s.startswith("(.") and s.endswith(".)"):440 s=s[2:-2]441 if s.startswith("(") and s.endswith(")"):442 s=s[1:-1]443 self.graph.add_node(pydot.Node(op + str(k.__hash__()),label=s,shape='oval'))444 for i,n in enumerate(dep):445 self.graph.add_edge(pydot.Edge(str(n.__hash__()),op + str(k.__hash__())))446class MXIfTestArtist(DotArtist):447 def draw(self):448 k = self.s449 graph = self.graph450 dep = getDeps(k)451 452 show_sp = True453 454 s = "<f0> ? | <f1> true"455 456 graph.add_node(pydot.Node(str(k.__hash__()),label=s,shape='Mrecord'))457 for i,n in enumerate(dep):458 graph.add_edge(pydot.Edge(str(n.__hash__()),str(k.__hash__())+":f%d" % i))459 460class MXDensificationArtist(DotArtist):461 def draw(self):462 k = self.s463 graph = self.graph464 dep = getDeps(k)465 466 self.graph.add_node(pydot.Node(str(k.__hash__()),label="densify(.)",shape='oval'))467 self.graph.add_edge(pydot.Edge(str(dep[0].__hash__()),str(k.__hash__())))468class MXNormArtist(DotArtist):469 def draw(self):470 k = self.s471 graph = self.graph472 dep = getDeps(k)473 s = getOperatorRepresentation(k,[".", "."])474 self.graph.add_node(pydot.Node(str(k.__hash__()),label=s,shape='oval'))475 self.graph.add_edge(pydot.Edge(str(dep[0].__hash__()),str(k.__hash__())))476 477class MXEvaluationOutputArtist(DotArtist):478 def draw(self):479 k = self.s480 self.drawSparsity(k,depid=str(hash(k.getDep(0))) + ":f%d" % k.getEvaluationOutput())481 482 483class MXMultiplicationArtist(DotArtist):484 def draw(self):485 k = self.s486 graph = self.graph487 dep = getDeps(k)488 # Non-commutative operators are represented by 'record' shapes.489 # The dependencies have different 'ports' where arrows should arrive.490 s = "mul(| <f0> | , | <f1> | )"491 graph.add_node(pydot.Node(str(k.__hash__()),label=s,shape='Mrecord'))492 for i,n in enumerate(dep):493 graph.add_edge(pydot.Edge(str(n.__hash__()),str(k.__hash__())+":f%d" % i))494 495class SXArtist(DotArtist):496 def draw(self):497 s = self.s498 graph = self.graph499 sp = s.sparsity()500 row = sp.row()501 502 # The Matrix grid is represented by a html table with 'ports'503 label = '<<TABLE BORDER="0" CELLBORDER="1" CELLSPACING="0">'504 for i in range(s.size1()):505 label+="<TR>"506 for j in range(s.size2()):507 k = sp.getNZ_const(i,j)508 if k==-1:509 label+="<TD>.</TD>"510 else:511 sx = s.at(k)512 if self.shouldEmbed(sx):513 label+="<TD BGCOLOR='#eeeeee'>%s</TD>" % str(sx)514 else:515 self.graph.add_edge(pydot.Edge(str(sx.__hash__()),"%s:f%d" % (str(self.s.__hash__()), k)))516 label+="<TD PORT='f%d' BGCOLOR='#eeeeee'> <font color='#666666'>(%d,%d|%d)</font> </TD>" % (k,i,j,k)517 label+="</TR>"518 label+="</TABLE>>"519 graph.add_node(pydot.Node(str(self.s.__hash__()),label=label,shape='plaintext'))520 521 def shouldEmbed(self,sx):522 return len(self.invdep[sx]) == 1 and sx.isLeaf()523 524class SXLeafArtist(DotArtist):525 def draw(self):526 if len(self.invdep[self.s]) == 1:527 master = list(self.invdep[self.s])[0]528 if hasattr(self.artists[master],'shouldEmbed'):529 if self.artists[master].shouldEmbed(self.s):530 return531 style = "solid" # Symbolic nodes are represented box'es532 if self.s.isConstant():533 style = "bold" # Constants are represented by bold box'es534 self.graph.add_node(pydot.Node(str(self.s.__hash__()),label=str(self.s),shape="box",style=style)) 535class SXNonLeafArtist(DotArtist):536 def draw(self):537 k = self.s538 graph = self.graph539 dep = getDeps(k)540 if not(k.isCommutative()):541 # Non-commutative operators are represented by 'record' shapes.542 # The dependencies have different 'ports' where arrows should arrive.543 s = getOperatorRepresentation(self.s,["| <f0> | ", " | <f1> |"])544 if s.startswith("(|") and s.endswith("|)"):545 s=s[2:-2]546 547 graph.add_node(pydot.Node(str(k.__hash__()),label=s,shape='Mrecord'))548 for i,n in enumerate(dep):549 graph.add_edge(pydot.Edge(str(n.__hash__()),str(k.__hash__())+":f%d" % i))550 else: 551 # Commutative operators can be represented more compactly as 'oval' shapes.552 s = getOperatorRepresentation(k,[".", "."])553 if s.startswith("(.") and s.endswith(".)"):554 s=s[2:-2]555 if s.startswith("(") and s.endswith(")"):556 s=s[1:-1]557 self.graph.add_node(pydot.Node(str(k.__hash__()),label=s,shape='oval'))558 for i,n in enumerate(dep):559 self.graph.add_edge(pydot.Edge(str(n.__hash__()),str(k.__hash__())))560 561 562 563def createArtist(node,dep={},invdep={},graph=None,artists={}):564 if isinstance(node,SX):565 return SXArtist(node,dep=dep,invdep=invdep,graph=graph,artists=artists)566 elif isinstance(node,SXElement):567 if node.isLeaf():568 return SXLeafArtist(node,dep=dep,invdep=invdep,graph=graph,artists=artists)569 else:570 return SXNonLeafArtist(node,dep=dep,invdep=invdep,graph=graph,artists=artists)571 elif isinstance(node,MX):572 if node.isSymbolic():573 return MXSymbolicArtist(node,dep=dep,invdep=invdep,graph=graph,artists=artists)574 elif node.isBinary() or node.isUnary():575 return MXOperationArtist(node,dep=dep,invdep=invdep,graph=graph,artists=artists)576 elif node.isConstant():577 return MXConstantArtist(node,dep=dep,invdep=invdep,graph=graph,artists=artists)578 elif node.isEvaluation():579 return MXEvaluationArtist(node,dep=dep,invdep=invdep,graph=graph,artists=artists)580 elif node.isEvaluationOutput():581 return MXEvaluationOutputArtist(node,dep=dep,invdep=invdep,graph=graph,artists=artists)582 elif node.isNorm():583 return MXNormArtist(node,dep=dep,invdep=invdep,graph=graph,artists=artists)584 elif node.isOperation(C.OP_GETNONZEROS):585 return MXGetNonzerosArtist(node,dep=dep,invdep=invdep,graph=graph,artists=artists)586 elif node.isOperation(C.OP_SETNONZEROS):587 return MXSetNonzerosArtist(node,dep=dep,invdep=invdep,graph=graph,artists=artists)588 elif node.isOperation(C.OP_ADDNONZEROS):589 return MXAddNonzerosArtist(node,dep=dep,invdep=invdep,graph=graph,artists=artists)590 else:591 return MXGenericArtist(node,dep=dep,invdep=invdep,graph=graph,artists=artists)592 else:593 raise Exception("Cannot create artist for %s" % str(type(s)))594 595def dotgraph(s,direction="BT"):596 """597 Creates and returns a pydot graph structure that represents an SXElement or SX.598 599 direction one of "BT", "LR", "TB", "RL"600 """601 602 # Get the dependencies and inverse dependencies in a dict603 dep, invdep = dependencyGraph(s,{},{})604 605 allnodes = set(dep.keys()).union(set(invdep.keys()))606 607 #print "a", set(dep.keys()), [i.__hash__() for i in dep.keys()]608 #print "b", set(invdep.keys()), [i.__hash__() for i in invdep.keys()]609 #print "allnodes", allnodes, [i.__hash__() for i in allnodes]610 611 #return None612 613 artists = {}614 615 graph = pydot.Dot('G', graph_type='digraph',rankdir=direction)616 617 for node in allnodes:618 artists[node] = createArtist(node,dep=dep,invdep=invdep,graph=graph,artists=artists)619 620 for artist in artists.itervalues():621 if artist is None: continue622 artist.draw()623 ...
alcqObj.py
Source:alcqObj.py
...17 def __repr__(self):18 return f"CS({self.name!r})"19 def __eq__(self, other):20 return isinstance(other, Constant) and self.name == other.name21 def __hash__(self):22 return hash(self.__repr__())23class Concept(object):24 def __init__(self, name: str):25 self.name = name26 def __repr__(self):27 return f"Concept({self.name!r})"28 def __call__(self, obj: Constant, *args, **kwargs):29 return ConceptAssertion(self, obj)30 def __hash__(self):31 return hash(self.__repr__())32class Formula(object):33 def __init__(self):34 pass35 def __call__(self, obj: Constant, *args, **kwargs):36 return ComplexAssertion(self, obj)37 def __hash__(self):38 return hash(self.__repr__())39class PrimitiveConcept(Concept, Formula):40 def __init__(self, name: str):41 Concept.__init__(self, name)42 def __repr__(self):43 return f"PC({self.name!r})"44 def __eq__(self, other):45 return isinstance(other, PrimitiveConcept) and self.name == other.name46 def __hash__(self):47 return Concept.__hash__(self)48class Relation(object):49 def __init__(self, name: str):50 self.name = name51 def __repr__(self):52 return f"R({self.name!r})"53 def __call__(self, obj1: Constant, obj2: Constant, *args, **kwargs):54 return RelationAssertion(self, obj1, obj2)55 def __eq__(self, other):56 return isinstance(other, Relation) and self.name == other.name57 def __hash__(self):58 return hash(self.__repr__())59class Operator(Formula):60 def __init__(self, name: str):61 super().__init__()62 self.name = name63 def __hash__(self):64 return hash(self.__repr__())65# class Formula(object):66# def __init__(self, content: Union[PrimitiveConcept, Operator]):67# self.content = content68#69# def __repr__(self):70# return f"{self.content!r}"71class DefinedConcept(Concept, Formula):72 def __init__(self, name: str, defn: Formula):73 Concept.__init__(self, name)74 self.definition = defn75 def __repr__(self):76 return f"DC({self.name}: {self.definition})"77 def __eq__(self, other):78 return isinstance(other, DefinedConcept) and self.definition == other.definition79 def __hash__(self):80 return Concept.__hash__(self)81class And(Operator):82 def __init__(self, param1: Formula, param2: Formula):83 Operator.__init__(self, "And")84 self.param1 = param185 self.param2 = param286 def __repr__(self):87 return f"And({self.param1!r}, {self.param2!r})"88 def __eq__(self, other):89 return isinstance(other, And) and ((self.param1 == other.param1 and self.param2 == other.param2) or (90 self.param1 == other.param2 and self.param2 == other.param1))91 def __hash__(self):92 return Operator.__hash__(self)93class Or(Operator):94 def __init__(self, param1: Formula, param2: Formula):95 Operator.__init__(self, "Or")96 self.param1 = param197 self.param2 = param298 def __repr__(self):99 return f"Or({self.param1!r}, {self.param2!r})"100 def __eq__(self, other):101 return isinstance(other, Or) and ((self.param1 == other.param1 and self.param2 == other.param2) or (102 self.param1 == other.param2 and self.param2 == other.param1))103 def __hash__(self):104 return Operator.__hash__(self)105class Not(Operator):106 def __init__(self, param: Formula):107 Operator.__init__(self, "Not")108 self.param = param109 def __repr__(self):110 return f"Not({self.param!r})"111 def __eq__(self, other):112 return isinstance(other, Not) and self.param == other.param113 def __hash__(self):114 return Operator.__hash__(self)115class ForAll(Operator):116 def __init__(self, relation: Relation, concept: Union[Concept, Formula]):117 Operator.__init__(self, "ForAll")118 self.relation = relation119 if not isinstance(self.relation, Relation):120 raise ValueError121 self.concept = concept122 def __repr__(self):123 return f"ForAll({self.relation!r}, {self.concept!r})"124 def __eq__(self, other):125 return isinstance(other, ForAll) and self.relation == other.relation and self.concept == other.concept126 def __hash__(self):127 return Operator.__hash__(self)128class Exists(Operator):129 def __init__(self, relation: Relation, concept: Union[Concept, Formula]):130 Operator.__init__(self, "Exists")131 self.relation = relation132 self.concept = concept133 def __repr__(self):134 return f"Exists({self.relation!r}, {self.concept!r})"135 def __eq__(self, other):136 return isinstance(other, Exists) and self.relation == other.relation and self.concept == other.concept137 def __hash__(self):138 return Operator.__hash__(self)139class AtLeast(Operator):140 def __init__(self, n: int, relation: Relation, concept: Union[Concept, Formula]):141 Operator.__init__(self, "AtLeast")142 if n < 0:143 raise ValueError("invalid n")144 self.n = n145 self.relation = relation146 self.concept = concept147 def __repr__(self):148 return f"AtLeast[{self.n!r}]({self.relation!r}, {self.concept!r})"149 def __eq__(self, other):150 return isinstance(other,151 AtLeast) and self.n == other.n and self.relation == other.relation and self.concept == other.concept152 def __hash__(self):153 return hash(self.__repr__())154class AtMost(Operator):155 def __init__(self, n: int, relation: Relation, concept: Union[Concept, Formula]):156 Operator.__init__(self, "AtMost")157 if n < 0:158 raise ValueError("invalid n")159 self.n = n160 self.relation = relation161 self.concept = concept162 def __repr__(self):163 return f"AtMost[{self.n!r}]({self.relation!r}, {self.concept!r})"164 def __eq__(self, other):165 return isinstance(other,166 AtMost) and self.n == other.n and self.relation == other.relation and self.concept == other.concept167 def __hash__(self):168 return hash(self.__repr__())169class Assertion(object):170 def __init__(self):171 pass172 def __hash__(self):173 return hash(self.__repr__())174class ConceptAssertion(Assertion):175 def __init__(self, concept: Concept, obj: Constant):176 Assertion.__init__(self)177 self.concept = concept178 self.obj = obj179 def __repr__(self):180 return f"CA[{self.concept!r}:({self.obj!r})]"181 def __eq__(self, other):182 return isinstance(other, ConceptAssertion) and self.concept == other.concept and self.obj == other.obj183 def __hash__(self):184 return Assertion.__hash__(self)185class RelationAssertion(Assertion):186 def __init__(self, relation: Relation, obj1: Constant, obj2: Constant):187 Assertion.__init__(self)188 self.relation = relation189 self.obj1 = obj1190 self.obj2 = obj2191 def __repr__(self):192 return f"RA[{self.relation!r}:({self.obj1!r},{self.obj2!r})]"193 def __eq__(self, other):194 return isinstance(other,195 RelationAssertion) and self.relation == other.relation and self.obj1 == other.obj1 and self.obj2 == other.obj2196 def __hash__(self):197 return Assertion.__hash__(self)198ABox = Set[Assertion]199TBox = List[Concept]200class ComplexAssertion(Assertion):201 def __init__(self, formula: Formula, obj: Constant):202 super().__init__()203 self.formula = formula204 self.obj = obj205 def __repr__(self):206 return f"XA[{self.formula!r}({self.obj!r})]"207 def __eq__(self, other):208 return isinstance(other, ComplexAssertion) and self.formula == other.formula and self.obj == other.obj209 def __hash__(self):210 return Assertion.__hash__(self)211class InequalityAssertion(Assertion):212 def __init__(self, obj1: Constant, obj2: Constant):213 super().__init__()214 self.obj1 = obj1215 self.obj2 = obj2216 def __repr__(self):217 return f"NEQ[{self.obj1!r}, {self.obj2!r}]"218 def __eq__(self, other):219 return isinstance(other, InequalityAssertion) and ((self.obj1 == other.obj1 and self.obj2 == other.obj2)220 or (self.obj1 == other.obj2 and self.obj2 == other.obj1))221 # TODO: x1=x2, x2=x1? AND/OR also has a similar problem?222 __hash__ = Assertion.__hash__223def ne(obj1: Constant, obj2: Constant) -> InequalityAssertion:224 """...
invalid_hash_returned.py
Source:invalid_hash_returned.py
...3import six4from missing import Missing5class FirstGoodHash(object):6 """__hash__ returns <type 'int'>"""7 def __hash__(self):8 return 19class SecondGoodHash(object):10 """__hash__ returns <type 'int'>"""11 def __hash__(self):12 return 013class HashMetaclass(type):14 def __hash__(cls):15 return 116@six.add_metaclass(HashMetaclass)17class ThirdGoodHash(object):18 """Hash through the metaclass."""19class FirstBadHash(object):20 """ __hash__ returns a dict """21 def __hash__(self): # [invalid-hash-returned]22 return {}23class SecondBadHash(object):24 """ __hash__ returns str """25 def __hash__(self): # [invalid-hash-returned]26 return "True"27class ThirdBadHash(object):28 """ __hash__ returns a float"""29 def __hash__(self): # [invalid-hash-returned]30 return 1.1131class FourthBadHash(object):32 """ __hash__ returns node which does not have 'value' in AST """33 def __hash__(self): # [invalid-hash-returned]34 return lambda: 335class AmbigousHash(object):36 """ Uninferable return value """37 __hash__ = lambda self: Missing38class AnotherAmbiguousHash(object):39 """Potential uninferable return value"""40 def __hash__(self):...
builtin_hash.py
Source:builtin_hash.py
...9 hash([])10except TypeError:11 print("TypeError")12class A:13 def __hash__(self):14 return 12315 def __repr__(self):16 return "a instance"17print(hash(A()))18print({A():1})19# all user-classes have default __hash__20class B:21 pass22hash(B())23# if __eq__ is defined then default __hash__ is not used24class C:25 def __eq__(self, another):26 return True27try:28 hash(C())29except TypeError:30 print("TypeError")31# __hash__ must return an int32class D:33 def __hash__(self):34 return None35try:36 hash(D())37except TypeError:38 print("TypeError")39# __hash__ returning a bool should be converted to an int40class E:41 def __hash__(self):42 return True43print(hash(E()))44# __hash__ returning a large number should be truncated45class F:46 def __hash__(self):47 return 1 << 70 | 1...
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!