Newer
Older
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
errorVal += math.sqrt(float(segEdgeMismatch) / numEdges) + \
math.sqrt(float(elabelMismatch) / numEdges)
if numNodes > 0:
errorVal += float(nlabelMismatch) / numNodes
errorVal = errorVal / 3.0
eerror = ("D_E(%)", errorVal)
# Compile metrics
metrics = metrics + [ aerror, cerror, lerror, rerror, serror, \
eerror, \
("nNodes",numNodes), ("nEdges", numEdges), \
("nSegRelEdges", nSegRelEdges), \
("dPairs",incorrectPairs),("segPairErrors",segPairErrors),
("nodeCorrect", numNodes - len(nodeError)) ]
metrics = metrics + segmentMetrics
return (metrics, nodeconflicts, edgeconflicts, segDiffs, correctSegs,\
segRelDiffs)
##################################
# Manipulation/'Mutation'
##################################
def separateTreeEdges(self):
"""Return a list of root nodes, and two lists of edges corresponding to
tree/forest edges, and the remaining edges."""
# First, obtain segments; perform extraction on edges over segments.
(segmentPrimitiveMap, primitiveSegmentMap, noparentSegments, \
segmentEdges) = self.segmentGraph()
# Collect parents and children for each node; identify root nodes.
# (NOTE: root nodes provided already as noparentSegments)
nodeParentMap = {}
nodeChildMap = {}
rootNodes = set(list(segmentPrimitiveMap))
for (parent, child) in segmentEdges:
if not child in list(nodeParentMap):
nodeParentMap[ child ] = [ parent ]
rootNodes.remove( child )
else:
nodeParentMap[ child ] += [ parent ]
if not parent in list(nodeChildMap):
nodeChildMap[ parent ] = [ child ]
else:
nodeChildMap[ parent ] += [ child ]
# Separate non-tree edges, traversing from the root.
fringe = list(rootNodes)
# Filter non-tree edges.
nonTreeEdges = set([])
while len(fringe) > 0:
nextNode = fringe.pop(0)
# Skip leaf nodes.
if nextNode in list(nodeChildMap):
children = copy.deepcopy(nodeChildMap[ nextNode ])
for child in children:
numChildParents = len( nodeParentMap[ child ] )
# Filter edges to children that have more than
# one parent (i.e. other than nextNode)
if numChildParents == 1:
# Child in the tree found, put on fringe.
fringe += [ child ]
else:
# Shift edge to non-tree status.
nonTreeEdges.add((nextNode, child))
nodeChildMap[ nextNode ].remove(child)
nodeParentMap[ child ].remove(nextNode)
# Generate the tree edges from remaining child relationships.
treeEdges = []
for node in nodeChildMap:
for child in nodeChildMap[ node ]:
treeEdges += [ (node, child) ]
return (list(rootNodes), treeEdges, list(nonTreeEdges))
def removeAbsent(self):
"""Remove any absent edges from both graphs, and empty the fields
recording empty objects."""
for absEdge in self.absentEdges:
del self.elabels[ absEdge ]
for absNode in self.absentNodes:
del self.nlabels[ absNode ]
self.absentNodes = set([])
self.absentEdges = set([])
def addAbsent(self, lg2):
"""Identify edges in other graph but not the current one."""
selfNodes = set(list(self.nlabels))
lg2Nodes = set(list(lg2.nlabels))
self.absentNodes = lg2Nodes.difference(selfNodes)
# WARN about absent nodes/edges; indicate that there is an error.
if len(self.absentNodes) > 0:
sys.stderr.write(' !! Inserting ABSENT nodes for:\n ' \
+ self.file + ' vs.\n ' + lg2.file + '\n ' \
+ str(sorted(list(self.absentNodes))) + '\n')
self.error = True
# Add "absent" nodes.
# NOTE: all edges to/from "absent" nodes are unlabeled.
for missingNode in self.absentNodes:
self.nlabels[ missingNode ] = { 'ABSENT': 1.0 }
def matchAbsent(self, lg2):
"""Add all missing primitives and edges between this graph and
the passed graph. **Modifies both the object and argument graph lg2."""
self.removeAbsent()
self.addAbsent(lg2)
lg2.removeAbsent()
lg2.addAbsent(self)
##################################
# Routines for missing/unlabeled
# edges.
##################################
# Returns NONE: modifies in-place.
def labelMissingEdges(self):
for node1 in list(self.nlabels):
for node2 in list(self.nlabels):
if not node1 == node2:
if not (node1, node2) in list(self.elabels):
self.elabels[(node1, node2)] = {'_' : 1.0 }
# Returns NONE: modifies in-place.
def hideUnlabeledEdges(self):
"""Move all missing/unlabeled edges to the hiddenEdges field."""
# Move all edges labeled '_' to the hiddenEdges field.
for edge in list(self.elabels):
if set( list(self.elabels[ edge ]) ) == \
set( [ '_' ] ):
self.hiddenEdges[ edge ] = self.elabels[ edge ]
del self.elabels[ edge ]
def restoreUnlabeledEdges(self):
"""Move all edges in the hiddenEdges field back to the set of
edges for the graph."""
for edge in list(self.hiddenEdges):
self.elabels[ edge ] = self.hiddenEdges[ edge ]
del self.hiddenEdges[ edge ]
##################################
# Merging graphs
##################################
# RETURNS None (modifies 'self' in-place.)
def merge(self, lg2, ncombfn, ecombfn):
"""New node/edge labels are added from lg2 with common primitives. The
value for common node/edge labels updated using ncombfn and
ecombfn respectiveley: each function is applied to current values to
obtain the new value (i.e. v1' = fn(v1,v2))."""
# Deal with non-common primitives/nodes.
# DEBUG: make sure that all absent edges are treated as
# 'hard' decisions (i.e. label ('_',1.0))
self.matchAbsent(lg2)
#self.labelMissingEdges()
# Merge node and edgelabels.
mergeMaps(self.nlabels, self.gweight, lg2.nlabels, lg2.gweight, \
ncombfn)
mergeMaps(self.elabels, self.gweight, lg2.elabels, lg2.gweight,\
ecombfn)
# RETURNS None: modifies in-place.
def addWeightedLabelValues(self,lg2):
"""Merge two graphs, adding the values for each node/edge label."""
def addValues( v1, w1, v2, w2 ):
return w1 * v1 + w2 * v2
self.merge(lg2, addValues, addValues)
# RETURNS None: modifies in-place.
# HM: Added for IJDAR CROHME draft; invoke to filter a graph.
# (currenly not used by default).
def keepOnlyCorrectLab(self, gt):
"""Keep only correct labels compared with the gt. Use the
label ERROR_N and ERROR_E for node and edges errors. Use the
compareTools to compare the labels with ground truth."""
allNodes = set(list(gt.nlabels)).union(list(self.nlabels))
self.matchAbsent(gt)
for nid in allNodes:
(cost,_) = self.cmpNodes(list(self.nlabels[nid]),list(gt.nlabels[nid]))
#if there is some error
if cost > 0:
self.nlabels[ nid ] = {'ERROR_N' : 1.0}
else:
self.nlabels[ nid ] = gt.nlabels[nid]
for (graph,oGraph) in [ (self,gt), (gt,self) ]:
for npair in list(graph.elabels):
cost = 0;
if not npair in oGraph.elabels:
(cost,errL) = self.cmpEdges(list(graph.elabels[npair]),['_'])
else:
(cost,errL) = self.cmpEdges(list(graph.elabels[npair]),list(oGraph.elabels[npair]))
if cost > 0:
self.elabels[ npair ] = {'ERROR_E' : 1.0}
else:
if npair in gt.elabels:
self.elabels[ npair ] = gt.elabels[npair]
else:
self.elabels[ npair ] = {'_' : 1.0}
# RETURNS None: modifies in-place.
def selectMaxLabels(self):
"""Filter for labels with maximum confidence. NOTE: this will
keep all maximum value labels found in each map, e.g. if two
classifications have the same likelihood for a node."""
for object in list(self.nlabels):
max = -1.0
maxPairs = {}
for (label, value) in self.nlabels[object].items():
if value > max:
max = value
maxPairs = { label : value }
elif value == max:
maxPairs[label] = value
self.nlabels[ object ] = maxPairs
for edge in list(self.elabels):
max = -1.0
maxPairs = {}
for (label, value) in self.elabels[edge].items():
if value > max:
max = value
maxPairs = { label : value }
elif value == max:
maxPairs[label] = value
self.elabels[ edge ] = maxPairs
# RETURNS NONE: modifies in-place.
def invertValues(self):
"""Substract all node and edge label values from 1.0, to
invert the values. Attempting to invert a value outside [0,1] will
set the error flag on the object."""
for node in list(self.nlabels):
for label in self.nlabels[ node ]:
currentValue = self.nlabels[ node ][ label ]
if currentValue < 0.0 or currentValue > 1.0:
sys.stderr.write('\n !! Attempted to invert node: ' \
+ node + ' label \"' \
+ label + '\" with value ' + str(currentValue) + '\n')
self.error = True
else:
self.nlabels[ node ][ label ] = 1.0 - currentValue
for edge in list(self.elabels):
for label in self.elabels[ edge ]:
currentValue = self.elabels[ edge ][ label ]
if currentValue < 0.0 or currentValue > 1.0:
sys.stderr.write('\n !! Attempted to invert edge: ' + \
str(edge) + ' label \"' \
+ label + '\" with value ' + str(currentValue) + '\n')
self.error = True
else:
self.elabels[ edge ][ label ] = 1.0 - currentValue
def subStructIterator(self, nodeNumbers):
""" Return an iterator which gives all substructures with n nodes
n belonging to the list depths"""
if(isinstance(nodeNumbers, int)):
nodeNumbers = [nodeNumbers]
subStruct = []
# Init the substruct with isolated nodes
for n in list(self.nlabels):
subStruct.append(set([n]))
if 1 in nodeNumbers:
yield SmallGraph([(n, "".join(list(self.nlabels[n])))], [])
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
for d in range(2,max(nodeNumbers)+1):
#add one node to each substructure
newSubsS = set([])
newSubsL = []
for sub in subStruct:
le = getEdgesToNeighbours(sub,list(self.elabels))
for (f,to) in le:
new = sub.union([to])
lnew = list(new)
lnew.sort()
snew = ",".join(lnew)
if(not snew in newSubsS):
newSubsS.add(snew)
newSubsL.append(new)
if d in nodeNumbers:
yield self.getSubSmallGraph(new)
# ??? BUG ???
subStruct = newSubsL
def getSubSmallGraph(self, nodelist):
"""Return the small graph with the primitives in nodelist and all edges
between them. The used label is the merged list of labels from nodes/edges"""
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
for n in nodelist:
sg.nodes[n] = list(self.nlabels[n])
for e in getEdgesBetweenThem(nodelist,list(self.elabels)):
sg.edges[e] = list(self.elabels[e])
return sg
# Compare the substructure
def compareSubStruct(self, olg, depths):
"""Return the list of couple of substructure which disagree
the substructure from self are used as references"""
allerrors = []
for struc in olg.subStructIterator(depths):
sg1 = self.getSubSmallGraph(list(struc.nodes))
if(not (struc == sg1)):
allerrors.append((struc,sg1))
return allerrors
def compareSegmentsStruct(self, lgGT,depths):
"""Compute the number of differing segments, and record disagreements
in a list.
The primitives in each subgraph should be of the same number and names
(identifiers). Nodes are merged that have identical (label,value) pairs
on nodes and all identical incoming and outgoing edges. If used for
classification evaluation, the ground-truth should be lgGT. The first
key value of the matrix is the lgGT obj structure, which gives the
structure of the corresponding primitives which is the key to get the
error structure in self."""
(sp1, ps1, _, sre1) = self.segmentGraph()
(spGT, psGT, _, sreGT) = lgGT.segmentGraph()
segDiffs = set()
correctSegments = set()
for primitive in list(psGT):
# Make sure to skip primitives that were missing ('ABSENT'),
# as in that case the graphs disagree on all non-identical node
# pairs for this primitive, and captured in self.absentEdges.
# RZ: Assuming one level of structure here; modifying for
# new data structures accomodating multiple structural levels.
obj1Id = ps1[primitive][ list(ps1[primitive])[0] ]
obj2Id = psGT[primitive][ list(psGT[primitive])[0] ]
if not 'ABSENT' in self.nlabels[primitive] and \
not 'ABSENT' in lgGT.nlabels[primitive]:
# Obtain sets of primitives sharing a segment for the current
# primitive for both graphs.
# Each of sp1/spGT are a map of ( {prim_set}, label ) pairs.
segPrimSet1 = sp1[ obj1Id ][0]
segPrimSet2 = spGT[ obj2Id ][0]
# Only create an entry where there are disagreements.
if segPrimSet1 != segPrimSet2:
segDiffs.add( ( obj2Id, obj1Id) )
else:
correctSegments.add( obj2Id )
# DEBUG: don't record differences for a single node.
elif len(list(self.nlabels)) > 1:
# If node was missing in this graph or the other, treat
# this graph as having a missing segment
# do not count the segment in graph with 1 primitive
segDiffs.add(( obj2Id, obj1Id ) )
# now check if the labels are identical
for seg in correctSegments:
# Get label for the first primtives (all primitives have identical
# labels in a segment).
# DEBUG: use only the set of labels, not confidence values.
firstPrim = list(spGT[seg][0])[0]
(cost, diff) = self.cmpNodes(list(self.nlabels[ firstPrim ]),list(lgGT.nlabels[ firstPrim ]))
segId1 = ps1[firstPrim][ list(ps1[ firstPrim ])[0] ]
segId2 = psGT[firstPrim][ list(psGT[ firstPrim ])[0] ]
if (0,[]) != (cost, diff):
segDiffs.add(( segId2, segId1) )
allSegWithErr = set([p for (p,_) in segDiffs])
# start to build the LG at the object level
# add nodes for object with the labels from the first prim
lgObj = Lg()
for (sid,lprim) in spGT.items():
lgObj.nlabels[sid] = lgGT.nlabels[list(lprim[0])[0]]
# Compute the specific 'segment-level' graph edges that disagree, at the
# level of primitive-pairs. This means that invalid segmentations may
# still have valid layouts in some cases.
# Add also the edges in the smallGraph
segEdgeErr = set()
for thisPair in list(sreGT):
# TODO : check if it is sp1[thisPair[0]] instead of sp1[thisPair[0]][0]
thisParentIds = set(spGT[ thisPair[0] ][0])
thisChildIds = set(spGT[thisPair[1] ][0])
lgObj.elabels[thisPair] = lgGT.elabels[ (list(thisParentIds)[0], list(thisChildIds)[0])]
# A 'correct' edge has the same label between all primitives
# in the two segments.
# NOTE: we are not checking the consitency of label in each graph
# ie if all labels from thisParentIds to thisChildIds in self are
# the same
for parentId in thisParentIds:
for childId in thisChildIds:
# DEBUG: compare only label sets, not values.
if not (parentId, childId) in list(self.elabels) or \
(0,[]) != self.cmpEdges(list(self.elabels[ (parentId, childId) ]), list(lgGT.elabels[ (parentId, childId) ])):
segEdgeErr.add(thisPair)
continue
listOfAllError = []
for smg in lgObj.subStructIterator(depths):
#if one segment is in the segment error set
showIt = False
if len(set(list(smg.nodes)).intersection(allSegWithErr)) > 0:
showIt = True
for pair in list(smg.edges):
if pair in segEdgeErr:
showIt = True
continue
if showIt:
#build the smg for the prim from lgGT
allPrim = []
for s in list(smg.nodes):
allPrim.extend(spGT[s][0])
smgPrim1 = self.getSubSmallGraph(allPrim)
smgPrimGT = lgGT.getSubSmallGraph(allPrim)
listOfAllError.append((smg,smgPrimGT,smgPrim1))
return listOfAllError
################################################################
# Utility functions
################################################################
def mergeLabelLists(llist1, weight1, llist2, weight2, combfn):
"""Combine values in two label lists according to the passed combfn
function, and passed weights for each label list."""
# Combine values for each label in lg2 already in self.
allLabels = set(llist1.items())\
.union(set(llist2.items()))
# have to test whether labels exist
# in one or both list.
for (label, value) in allLabels:
if label in list(llist1) and \
label in list(llist2):
llist1[ label ] = \
combfn( llist1[label], weight1,\
llist2[label], weight2 )
elif label in list(llist2):
llist1[ label ] = \
weight2 * llist2[label]
else:
llist1[ label ] = \
weight1 * llist1[label]
def mergeMaps(map1, weight1, map2, weight2, combfn):
"""Combine values in two maps according to the passed combfn
function, and passed weights for each map."""
# Odds are good that there are built-in function for this
# operation.
objects1 = list(map1)
objects2 = list(map2)
allObjects = set(objects1).union(set(objects2))
for object in allObjects:
if object in objects1 and object in objects2:
# Combine values for each label in lg2 already in self.
mergeLabelLists(map1[object],weight1, map2[object], weight2, combfn )
# DEBUG: no relationship ('missing') edges should
# be taken as certain (value 1.0 * weight) where not explicit.
elif object in objects2:
# Use copy to avoid aliasing problems.
# Use appropriate weight to update value.
map1[ object ] = copy.deepcopy( map2[ object ] )
for (label, value) in map1[object].items():
map1[object][label] = weight2 * value
map1[object]['_'] = weight1
else:
# Only in current map: weight value appropriately.
for (label, value) in map1[object].items():
map1[object][label] = weight1 * value
map1[object]['_'] = weight2
def getEdgesToNeighbours(nodes,edges):
"""return all edges which are coming from one of the nodes to out of these nodes"""
neigb = set([])
for (n1,n2) in edges:
if (n1 in nodes and not n2 in nodes):
neigb.add((n1,n2))
return neigb
def getEdgesBetweenThem(nodes,edges):
"""return all edges which are coming from one of the nodes to out of these nodes"""
edg = set([])
for (n1,n2) in edges:
if (n1 in nodes and n2 in nodes):
edg.add((n1,n2))
return edg