Debian Codegraph @

cluster/matrix.py

raw symbols SCIP
1 #
2 # This is part of "python-cluster". A library to group similar items together.
3 # Copyright (C) 2006 Michel Albert
4 #
5 # This library is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU Lesser General Public License as published by the
7 # Free Software Foundation; either version 2.1 of the License, or (at your
8 # option) any later version.
9 # This library is distributed in the hope that it will be useful, but WITHOUT
10 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
12 # for more details.
13 # You should have received a copy of the GNU Lesser General Public License
14 # along with this library; if not, write to the Free Software Foundation,
15 # Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 #
17
18
19 import logging
20 from multiprocessing import Process, Queue, current_process
21
22
23 logger = logging.getLogger(__name__)
24
25 def _encapsulate_item_for_combinfunc(item):
26 """
27 This function has been extracted in order to
28 make Github issue #28 easier to investigate.
29 It replaces the following two lines of code,
30 which occur twice in method genmatrix, just
31 before the invocation of combinfunc.
32 if not hasattr(item, '__iter__') or isinstance(item, tuple):
33 item = [item]
34 Logging was added to the original two lines
35 and shows that the outcome of this snippet
36 has changed between Python2.7 and Python3.5.
37 This logging showed that the difference in
38 outcome consisted of the handling of the builtin
39 str class, which was encapsulated into a list in
40 Python2.7 but returned naked in Python3.5.
41 Adding a test for this specific class to the
42 set of conditions appears to give correct behaviour
43 under both versions.
44 """
45 encapsulated_item = None
46 if (
47 not hasattr(item, '__iter__') or
48 isinstance(item, tuple) or
49 isinstance(item, str)
50 ):
51 encapsulated_item = [item]
52 else:
53 encapsulated_item = item
54 logging.debug(
55 "item class:%s encapsulated as:%s ",
56 item.__class__.__name__,
57 encapsulated_item.__class__.__name__
58 )
59 return encapsulated_item
60
61
62 class Matrix(object):
63 """
64 Object representation of the item-item matrix.
65 """
66
67 def __init__(self, data, combinfunc, symmetric=False, diagonal=None):
68 """
69 Takes a list of data and generates a 2D-matrix using the supplied
70 combination function to calculate the values.
71
72 :param data: the list of items.
73 :param combinfunc: the function that is used to calculate teh value in a
74 cell. It has to cope with two arguments.
75 :param symmetric: Whether it will be a symmetric matrix along the
76 diagonal. For example, if the list contains integers, and the
77 combination function is ``abs(x-y)``, then the matrix will be
78 symmetric.
79 :param diagonal: The value to be put into the diagonal. For some
80 functions, the diagonal will stay constant. An example could be the
81 function ``x-y``. Then each diagonal cell will be ``0``. If this
82 value is set to None, then the diagonal will be calculated.
83 """
84 self.data = data
85 self.combinfunc = combinfunc
86 self.symmetric = symmetric
87 self.diagonal = diagonal
88
89 def worker(self):
90 """
91 Multiprocessing task function run by worker processes
92 """
93 tasks_completed = 0
94 for task in iter(self.task_queue.get, 'STOP'):
95 col_index, item, item2 = task
96 if not hasattr(item, '__iter__') or isinstance(item, tuple):
97 item = [item]
98 if not hasattr(item2, '__iter__') or isinstance(item2, tuple):
99 item2 = [item2]
100 result = (col_index, self.combinfunc(item, item2))
101 self.done_queue.put(result)
102 tasks_completed += 1
103 logger.info("Worker %s performed %s tasks",
104 current_process().name,
105 tasks_completed)
106
107 def genmatrix(self, num_processes=1):
108 """
109 Actually generate the matrix
110
111 :param num_processes: If you want to use multiprocessing to split up the
112 work and run ``combinfunc()`` in parallel, specify
113 ``num_processes > 1`` and this number of workers will be spun up,
114 the work is split up amongst them evenly.
115 """
116 use_multiprocessing = num_processes > 1
117 if use_multiprocessing:
118 self.task_queue = Queue()
119 self.done_queue = Queue()
120
121 self.matrix = []
122 logger.info("Generating matrix for %s items - O(n^2)", len(self.data))
123 if use_multiprocessing:
124 logger.info("Using multiprocessing on %s processes!", num_processes)
125
126 if use_multiprocessing:
127 logger.info("Spinning up %s workers", num_processes)
128 processes = [Process(target=self.worker) for i in range(num_processes)]
129 [process.start() for process in processes]
130
131 for row_index, item in enumerate(self.data):
132 logger.debug("Generating row %s/%s (%0.2f%%)",
133 row_index,
134 len(self.data),
135 100.0 * row_index / len(self.data))
136 row = {}
137 if use_multiprocessing:
138 num_tasks_queued = num_tasks_completed = 0
139 for col_index, item2 in enumerate(self.data):
140 if self.diagonal is not None and col_index == row_index:
141 # This is a cell on the diagonal
142 row[col_index] = self.diagonal
143 elif self.symmetric and col_index < row_index:
144 # The matrix is symmetric and we are "in the lower left
145 # triangle" - fill this in after (in case of multiprocessing)
146 pass
147 # Otherwise, this cell is not on the diagonal and we do indeed
148 # need to call combinfunc()
149 elif use_multiprocessing:
150 # Add that thing to the task queue!
151 self.task_queue.put((col_index, item, item2))
152 num_tasks_queued += 1
153 # Start grabbing the results as we go, so as not to stuff all of
154 # the worker args into memory at once (as Queue.get() is a
155 # blocking operation)
156 if num_tasks_queued > num_processes:
157 col_index, result = self.done_queue.get()
158 row[col_index] = result
159 num_tasks_completed += 1
160 else:
161 # Otherwise do it here, in line
162 """
163 if not hasattr(item, '__iter__') or isinstance(item, tuple):
164 item = [item]
165 if not hasattr(item2, '__iter__') or isinstance(item2, tuple):
166 item2 = [item2]
167 """
168 # See the comment in function _encapsulate_item_for_combinfunc
169 # for details of why the lines above have been replaced
170 # by function invocations
171 item = _encapsulate_item_for_combinfunc(item)
172 item2 = _encapsulate_item_for_combinfunc(item2)
173 row[col_index] = self.combinfunc(item, item2)
174
175 if self.symmetric:
176 # One more iteration to get symmetric lower left triangle
177 for col_index, item2 in enumerate(self.data):
178 if col_index >= row_index:
179 break
180 # post-process symmetric "lower left triangle"
181 row[col_index] = self.matrix[col_index][row_index]
182
183 if use_multiprocessing:
184 # Grab the remaining worker task results
185 while num_tasks_completed < num_tasks_queued:
186 col_index, result = self.done_queue.get()
187 row[col_index] = result
188 num_tasks_completed += 1
189
190 row_indexed = [row[index] for index in range(len(self.data))]
191 self.matrix.append(row_indexed)
192
193 if use_multiprocessing:
194 logger.info("Stopping/joining %s workers", num_processes)
195 [self.task_queue.put('STOP') for i in range(num_processes)]
196 [process.join() for process in processes]
197
198 logger.info("Matrix generated")
199
200 def __str__(self):
201 """
202 Returns a 2-dimensional list of data as text-string which can be
203 displayed to the user.
204 """
205 # determine maximum length
206 maxlen = 0
207 colcount = len(self.data[0])
208 for col in self.data:
209 for cell in col:
210 maxlen = max(len(str(cell)), maxlen)
211 format = " %%%is |" % maxlen
212 format = "|" + format * colcount
213 rows = [format % tuple(row) for row in self.data]
214 return "\n".join(rows)