Debian Codegraph @

src/CedarBackup3/knapsack.py

raw
1 # vim: set ft=python ts=4 sw=4 expandtab:
2 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
3 #
4 # C E D A R
5 # S O L U T I O N S "Software done right."
6 # S O F T W A R E
7 #
8 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
9 #
10 # Copyright (c) 2004-2005,2010,2015 Kenneth J. Pronovici.
11 # All rights reserved.
12 #
13 # This program is free software; you can redistribute it and/or
14 # modify it under the terms of the GNU General Public License,
15 # Version 2, as published by the Free Software Foundation.
16 #
17 # This program is distributed in the hope that it will be useful,
18 # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
20 #
21 # Copies of the GNU General Public License are available from
22 # the Free Software Foundation website, http://www.gnu.org/.
23 #
24 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
25 #
26 # Author : Kenneth J. Pronovici <[email protected]>
27 # Language : Python 3
28 # Project : Cedar Backup, release 3
29 # Purpose : Provides knapsack algorithms used for "fit" decisions
30 #
31 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
32
33 ########
34 # Notes
35 ########
36
37 """
38 Provides the implementation for various knapsack algorithms.
39
40 Knapsack algorithms are "fit" algorithms, used to take a set of "things" and
41 decide on the optimal way to fit them into some container. The focus of this
42 code is to fit files onto a disc, although the interface (in terms of item,
43 item size and capacity size, with no units) is generic enough that it can
44 be applied to items other than files.
45
46 All of the algorithms implemented below assume that "optimal" means "use up as
47 much of the disc's capacity as possible", but each produces slightly different
48 results. For instance, the best fit and first fit algorithms tend to include
49 fewer files than the worst fit and alternate fit algorithms, even if they use
50 the disc space more efficiently.
51
52 Usually, for a given set of circumstances, it will be obvious to a human which
53 algorithm is the right one to use, based on trade-offs between number of files
54 included and ideal space utilization. It's a little more difficult to do this
55 programmatically. For Cedar Backup's purposes (i.e. trying to fit a small
56 number of collect-directory tarfiles onto a disc), worst-fit is probably the
57 best choice if the goal is to include as many of the collect directories as
58 possible.
59
60 :author: Kenneth J. Pronovici <[email protected]>
61 """
62
63 #######################################################################
64 # Public functions
65 #######################################################################
66
67 ######################
68 # firstFit() function
69 ######################
70
71
72 def firstFit(items, capacity):
73 """
74 Implements the first-fit knapsack algorithm.
75
76 The first-fit algorithm proceeds through an unsorted list of items until
77 running out of items or meeting capacity exactly. If capacity is exceeded,
78 the item that caused capacity to be exceeded is thrown away and the next one
79 is tried. This algorithm generally performs more poorly than the other
80 algorithms both in terms of capacity utilization and item utilization, but
81 can be as much as an order of magnitude faster on large lists of items
82 because it doesn't require any sorting.
83
84 The "size" values in the items and capacity arguments must be comparable,
85 but they are unitless from the perspective of this function. Zero-sized
86 items and capacity are considered degenerate cases. If capacity is zero,
87 no items fit, period, even if the items list contains zero-sized items.
88
89 The dictionary is indexed by its key, and then includes its key. This
90 seems kind of strange on first glance. It works this way to facilitate
91 easy sorting of the list on key if needed.
92
93 The function assumes that the list of items may be used destructively, if
94 needed. This avoids the overhead of having the function make a copy of the
95 list, if this is not required. Callers should pass ``items.copy()`` if they
96 do not want their version of the list modified.
97
98 The function returns a list of chosen items and the unitless amount of
99 capacity used by the items.
100
101 Args:
102 items (dictionary, keyed on item, of ``item, size`` tuples, item as string and size as integer): Items to operate on
103 capacity (integer): Capacity of container to fit to
104 Returns:
105 Tuple ``(items, used)`` as described above
106 """
107
108 # Use dict since insert into dict is faster than list append
109 included = {}
110
111 # Search the list as it stands (arbitrary order)
112 used = 0
113 remaining = capacity
114 for key in list(items.keys()):
115 if remaining == 0:
116 break
117 if remaining - items[key][1] >= 0:
118 included[key] = None
119 used += items[key][1]
120 remaining -= items[key][1]
121
122 # Return results
123 return (list(included.keys()), used)
124
125
126 #####################
127 # bestFit() function
128 #####################
129
130
131 def bestFit(items, capacity):
132 """
133 Implements the best-fit knapsack algorithm.
134
135 The best-fit algorithm proceeds through a sorted list of items (sorted from
136 largest to smallest) until running out of items or meeting capacity exactly.
137 If capacity is exceeded, the item that caused capacity to be exceeded is
138 thrown away and the next one is tried. The algorithm effectively includes
139 the minimum number of items possible in its search for optimal capacity
140 utilization. For large lists of mixed-size items, it's not ususual to see
141 the algorithm achieve 100% capacity utilization by including fewer than 1%
142 of the items. Probably because it often has to look at fewer of the items
143 before completing, it tends to be a little faster than the worst-fit or
144 alternate-fit algorithms.
145
146 The "size" values in the items and capacity arguments must be comparable,
147 but they are unitless from the perspective of this function. Zero-sized
148 items and capacity are considered degenerate cases. If capacity is zero,
149 no items fit, period, even if the items list contains zero-sized items.
150
151 The dictionary is indexed by its key, and then includes its key. This
152 seems kind of strange on first glance. It works this way to facilitate
153 easy sorting of the list on key if needed.
154
155 The function assumes that the list of items may be used destructively, if
156 needed. This avoids the overhead of having the function make a copy of the
157 list, if this is not required. Callers should pass ``items.copy()`` if they
158 do not want their version of the list modified.
159
160 The function returns a list of chosen items and the unitless amount of
161 capacity used by the items.
162
163 Args:
164 items (dictionary, keyed on item, of ``item, size`` tuples, item as string and size as integer): Items to operate on
165 capacity (integer): Capacity of container to fit to
166 Returns:
167 Tuple ``(items, used)`` as described above
168 """
169
170 # Use dict since insert into dict is faster than list append
171 included = {}
172
173 # Sort the list from largest to smallest
174 itemlist = list(items.items())
175 itemlist.sort(key=lambda x: x[1][1], reverse=True) # sort descending
176 keys = []
177 for item in itemlist:
178 keys.append(item[0])
179
180 # Search the list
181 used = 0
182 remaining = capacity
183 for key in keys:
184 if remaining == 0:
185 break
186 if remaining - items[key][1] >= 0:
187 included[key] = None
188 used += items[key][1]
189 remaining -= items[key][1]
190
191 # Return the results
192 return (list(included.keys()), used)
193
194
195 ######################
196 # worstFit() function
197 ######################
198
199
200 def worstFit(items, capacity):
201 """
202 Implements the worst-fit knapsack algorithm.
203
204 The worst-fit algorithm proceeds through an a sorted list of items (sorted
205 from smallest to largest) until running out of items or meeting capacity
206 exactly. If capacity is exceeded, the item that caused capacity to be
207 exceeded is thrown away and the next one is tried. The algorithm
208 effectively includes the maximum number of items possible in its search for
209 optimal capacity utilization. It tends to be somewhat slower than either
210 the best-fit or alternate-fit algorithm, probably because on average it has
211 to look at more items before completing.
212
213 The "size" values in the items and capacity arguments must be comparable,
214 but they are unitless from the perspective of this function. Zero-sized
215 items and capacity are considered degenerate cases. If capacity is zero,
216 no items fit, period, even if the items list contains zero-sized items.
217
218 The dictionary is indexed by its key, and then includes its key. This
219 seems kind of strange on first glance. It works this way to facilitate
220 easy sorting of the list on key if needed.
221
222 The function assumes that the list of items may be used destructively, if
223 needed. This avoids the overhead of having the function make a copy of the
224 list, if this is not required. Callers should pass ``items.copy()`` if they
225 do not want their version of the list modified.
226
227 The function returns a list of chosen items and the unitless amount of
228 capacity used by the items.
229
230 Args:
231 items (dictionary, keyed on item, of ``item, size`` tuples, item as string and size as integer): Items to operate on
232 capacity (integer): Capacity of container to fit to
233 Returns:
234 Tuple ``(items, used)`` as described above
235 """
236
237 # Use dict since insert into dict is faster than list append
238 included = {}
239
240 # Sort the list from smallest to largest
241 itemlist = list(items.items())
242 itemlist.sort(key=lambda x: x[1][1]) # sort ascending
243 keys = []
244 for item in itemlist:
245 keys.append(item[0])
246
247 # Search the list
248 used = 0
249 remaining = capacity
250 for key in keys:
251 if remaining == 0:
252 break
253 if remaining - items[key][1] >= 0:
254 included[key] = None
255 used += items[key][1]
256 remaining -= items[key][1]
257
258 # Return results
259 return (list(included.keys()), used)
260
261
262 ##########################
263 # alternateFit() function
264 ##########################
265
266
267 def alternateFit(items, capacity):
268 """
269 Implements the alternate-fit knapsack algorithm.
270
271 This algorithm (which I'm calling "alternate-fit" as in "alternate from one
272 to the other") tries to balance small and large items to achieve better
273 end-of-disk performance. Instead of just working one direction through a
274 list, it alternately works from the start and end of a sorted list (sorted
275 from smallest to largest), throwing away any item which causes capacity to
276 be exceeded. The algorithm tends to be slower than the best-fit and
277 first-fit algorithms, and slightly faster than the worst-fit algorithm,
278 probably because of the number of items it considers on average before
279 completing. It often achieves slightly better capacity utilization than the
280 worst-fit algorithm, while including slighly fewer items.
281
282 The "size" values in the items and capacity arguments must be comparable,
283 but they are unitless from the perspective of this function. Zero-sized
284 items and capacity are considered degenerate cases. If capacity is zero,
285 no items fit, period, even if the items list contains zero-sized items.
286
287 The dictionary is indexed by its key, and then includes its key. This
288 seems kind of strange on first glance. It works this way to facilitate
289 easy sorting of the list on key if needed.
290
291 The function assumes that the list of items may be used destructively, if
292 needed. This avoids the overhead of having the function make a copy of the
293 list, if this is not required. Callers should pass ``items.copy()`` if they
294 do not want their version of the list modified.
295
296 The function returns a list of chosen items and the unitless amount of
297 capacity used by the items.
298
299 Args:
300 items (dictionary, keyed on item, of ``item, size`` tuples, item as string and size as integer): Items to operate on
301 capacity (integer): Capacity of container to fit to
302 Returns:
303 Tuple ``(items, used)`` as described above
304 """
305
306 # Use dict since insert into dict is faster than list append
307 included = {}
308
309 # Sort the list from smallest to largest
310 itemlist = list(items.items())
311 itemlist.sort(key=lambda x: x[1][1]) # sort ascending
312 keys = []
313 for item in itemlist:
314 keys.append(item[0])
315
316 # Search the list
317 used = 0
318 remaining = capacity
319
320 front = keys[0 : len(keys) // 2]
321 back = keys[len(keys) // 2 : len(keys)]
322 back.reverse()
323
324 i = 0
325 j = 0
326
327 while remaining > 0 and (i < len(front) or j < len(back)):
328 if i < len(front):
329 if remaining - items[front[i]][1] >= 0:
330 included[front[i]] = None
331 used += items[front[i]][1]
332 remaining -= items[front[i]][1]
333 i += 1
334 if j < len(back):
335 if remaining - items[back[j]][1] >= 0:
336 included[back[j]] = None
337 used += items[back[j]][1]
338 remaining -= items[back[j]][1]
339 j += 1
340
341 # Return results
342 return (list(included.keys()), used)