Skip to content

Instantly share code, notes, and snippets.

@Tix3Dev
Created October 3, 2024 17:22
Show Gist options
  • Save Tix3Dev/22b12ebf467617c23bb16e14b010be92 to your computer and use it in GitHub Desktop.
Save Tix3Dev/22b12ebf467617c23bb16e14b010be92 to your computer and use it in GitHub Desktop.
def spider(g: BaseGraph[VT,ET], matches: List[MatchSpiderType[VT]]) -> RewriteOutputType[VT,ET]:
'''Performs spider fusion given a list of matchings from ``match_spider(_parallel)``
'''
rem_verts: List[VT] = []
etab: Dict[Tuple[VT,VT],List[int]] = dict()
for m in matches:
if g.row(m[0]) == 0:
v0, v1 = m[1], m[0]
else:
v0, v1 = m[0], m[1]
ground = g.is_ground(v0) or g.is_ground(v1)
if ground:
g.set_phase(v0, 0)
g.set_ground(v0)
elif g.type(v0) == VertexType.Z_BOX or g.type(v1) == VertexType.Z_BOX:
if g.type(v0) == VertexType.Z:
z_to_z_box(g, [v0])
if g.type(v1) == VertexType.Z:
z_to_z_box(g, [v1])
g.set_phase(v0, 0)
set_z_box_label(g, v0, get_z_box_label(g, v0) * get_z_box_label(g, v1))
else:
g.add_to_phase(v0, g.phase(v1))
if g.track_phases:
g.fuse_phases(v0,v1)
# always delete the second vertex in the match
rem_verts.append(v1)
# MY ADDITION: add all new key/values from v1 to v0, however currently
# if both have the same key, then just the one from v0 is preserved
v0_vdata_keys = g.vdata_keys(v0)
v1_vdata_keys = g.vdata_keys(v1)
new_vdata_dict = {key: g.vdata(v0, key) for key in v0_vdata_keys}
for key in v1_vdata_keys:
if key in new_vdata_dict:
# TODO: could raise special error
# print("Error could be raised here")
continue
else:
new_vdata_dict[key] = g.vdata(v1, key)
for key, val in new_vdata_dict.items():
g.set_vdata(v0, key, val)
# edges from the second vertex are transferred to the first
for e in g.incident_edges(v1):
source, target = g.edge_st(e)
if source != v1:
other_vertex = source
elif target != v1:
other_vertex = target
else: #self-loop
other_vertex = v0
new_e = (v0, other_vertex)
if new_e not in etab: etab[new_e] = [0,0]
etab[new_e][g.edge_type(e)-1] += 1
etab[(v0,v0)][0] = 0 # remove simple edge loops
return (etab, rem_verts, [], True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment