MCPcopy Create free account
hub / github.com/DEAP/deap / SortingNetwork

Class SortingNetwork

doc/code/tutorials/part_4/sortingnetwork.py:29–127  ·  view source on GitHub ↗

Sorting network class. From Wikipedia : A sorting network is an abstract mathematical model of a network of wires and comparator modules that is used to sort a sequence of numbers. Each comparator connects two wires and sort the values by outputting the smaller value to one wire, an

Source from the content-addressed store, hash-verified

27 yield tuple(prod)
28
29class SortingNetwork(list):
30 """Sorting network class.
31
32 From Wikipedia : A sorting network is an abstract mathematical model
33 of a network of wires and comparator modules that is used to sort a
34 sequence of numbers. Each comparator connects two wires and sort the
35 values by outputting the smaller value to one wire, and a larger
36 value to the other.
37 """
38 def __init__(self, dimension, connectors = []):
39 self.dimension = dimension
40 for wire1, wire2 in connectors:
41 self.addConnector(wire1, wire2)
42
43 def addConnector(self, wire1, wire2):
44 """Add a connector between wire1 and wire2 in the network."""
45 if wire1 == wire2:
46 return
47
48 if wire1 > wire2:
49 wire1, wire2 = wire2, wire1
50
51 try:
52 last_level = self[-1]
53 except IndexError:
54 # Empty network, create new level and connector
55 self.append({wire1: wire2})
56 return
57
58 for wires in last_level.items():
59 if wires[1] >= wire1 and wires[0] <= wire2:
60 self.append({wire1: wire2})
61 return
62
63 last_level[wire1] = wire2
64
65 def sort(self, values):
66 """Sort the values in-place based on the connectors in the network."""
67 for level in self:
68 for wire1, wire2 in level.items():
69 if values[wire1] > values[wire2]:
70 values[wire1], values[wire2] = values[wire2], values[wire1]
71
72 def assess(self, cases=None):
73 """Try to sort the **cases** using the network, return the number of
74 misses. If **cases** is None, test all possible cases according to
75 the network dimensionality.
76 """
77 if cases is None:
78 cases = product(range(2), repeat=self.dimension)
79
80 misses = 0
81 ordered = [[0]*(self.dimension-i) + [1]*i for i in range(self.dimension+1)]
82 for sequence in cases:
83 sequence = list(sequence)
84 self.sort(sequence)
85 misses += (sequence != ordered[sum(sequence)])
86 return misses

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…