'Merge results with identical title and authors or an identical
identifier'

def merge_metadata_results(self, merge_on_identifiers=False):

    groups = {}
    for result in self.results:
        title = lower((result.title if result.title else u''))
        key = (title, tuple([lower(x) for x in result.authors]))
        if (key not in groups):
            groups[key] = []
        groups[key].append(result)
    if (len(groups) != len(self.results)):
        self.results = []
        for rgroup in groups.itervalues():
            rel = [r.average_source_relevance for r in rgroup]
            if (len(rgroup) > 1):
                result = self.merge(rgroup, None, do_asr=False)
                result.average_source_relevance = (sum(rel) / len(rel))
            else:
                result = rgroup[0]
            self.results.append(result)
    if merge_on_identifiers:
        (groups, empty) = ({}, [])
        for result in self.results:
            key = set()
            for (typ, val) in result.identifiers.iteritems():
                if (typ and val):
                    key.add((typ, val))
            if key:
                key = frozenset(key)
                match = None
                for candidate in list(groups):
                    if candidate.intersection(key):
                        match = candidate.union(key)
                        results = groups.pop(candidate)
                        results.append(result)
                        groups[match] = results
                        break
                if (match is None):
                    groups[key] = [result]
            else:
                empty.append(result)
        if (len(groups) != len(self.results)):
            self.results = []
            for rgroup in groups.itervalues():
                rel = [r.average_source_relevance for r in rgroup]
                if (len(rgroup) > 1):
                    result = self.merge(rgroup, None, do_asr=False)
                    result.average_source_relevance = (sum(rel) / len(rel))
                elif rgroup:
                    result = rgroup[0]
                self.results.append(result)
        if empty:
            self.results.extend(empty)
    self.results.sort(key=attrgetter(u'average_source_relevance'))
