Merging with HEAD
[nepi.git] / src / nepi / util / settools / classify.py
1 import setclusters
2 import collections
3 import itertools
4 import operator
5
6 def classify(requests, partition):
7     """
8     Takes an iterable over requests and a classification, and classifies the requests
9     returning a mapping from their classification (bitmap of applicable partitions) to
10     lists of requests.
11     
12     Params:
13     
14         requests: iterable over sets of viable candidates for a request
15         
16         partition: sequence of sets of candidates that forms a partition
17             over all available candidates.
18     
19     Returns:
20         
21         { str : [requests] }
22     """
23     rv = collections.defaultdict(list)
24     
25     for request in requests:
26         rv[getClass(request, partition)].append(request)
27     
28     return dict(rv)
29
30 def getClass(set, partition):
31     return "".join(
32         map("01".__getitem__, [
33             bool(set & part)
34             for part in partition
35         ])
36     )
37     
38
39 def isSubclass(superclass, subclass):
40     """
41     Returns True iff 'superclass' includes all elements of 'subclass'
42     
43     >>> isSubclass("1100","1000")
44     True
45     >>> isSubclass("1100","1100")
46     True
47     >>> isSubclass("0000","0001")
48     False
49     """
50     for superbit, subbit in itertools.izip(superclass, subclass):
51         if subbit and not superbit:
52             return False
53     else:
54         return True
55
56 def classContains(clz, partIndex):
57     return clz[partIndex] == "1"
58
59 def classCardinality(clz, partition = None):
60     if not partition:
61         return sum(itertools.imap("1".__eq__, clz))
62     else:
63         return sum(len(part) for bit,part in zip(clz,partition) 
64                    if bit == "1" )
65
66 def classMembers(clz, partition):
67     return reduce(operator.or_, classComponents(clz, partition))
68
69 def classComponents(clz, partition):
70     return [
71         partition[i]
72         for i,bit in enumerate(clz)
73         if bit == "1"
74     ]
75
76