-
Notifications
You must be signed in to change notification settings - Fork 1
/
karnaughmap.py
475 lines (355 loc) · 14.6 KB
/
karnaughmap.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
from math import *
import traceback
from multiprocessing import Process, Queue, Manager
class KarnaughNode(object):
def __init__(self):
self.values = []
self.numberOfItems = 0
self.flag = False
class JoinNode(object):
def __init__(self, newblocks, removeblocks):
self.newblocks = newblocks
self.removeblocks = removeblocks
class JoinTask(Process):
def __init__ (self, parent, blocks, a, i):
Process.__init__(self)
self.daemon = False
self.status = -1
self.parent = parent
self.blocks = blocks
#self.newblocks = []
self.a = a
self.i = i
#self.resultQueue = resultQueue
#self.process_counter = process_counter
def Join(self, blocks, a, i):
CompBlocks = [block for block in blocks if self.parent.IsJoinable(a.values, block.values )]
for b in CompBlocks:
## if( (a.numberOfItems == pow(2.0, i-1)) &
## (b.numberOfItems == pow(2.0, i-1)) ):
x=self.parent.IsJoinable(a.values, b.values )
if(x>0):
#/* If they can be joined make a new block with 2 in the place
#of the one bit where they a and b are different */
n = KarnaughNode()
n.numberOfItems=a.numberOfItems*2
n.flag = False
for j in range(0, len(a.values) ):
if(j!=(x-1)):
n.values.append(a.values[j] )
else:
n.values.append( 2 )
#/* Mark that a node is part of a larger node */
a.flag=True
b.flag=True
#/* Check if that block already exists in the list */
exist=False
for c in self.parent.blocks:
if(n.values==c.values):
exist=True
if(not exist):
self.parent.blocks.append(n )
def run(self):
try:
self.Join(self.blocks, self.a, self.i)
## removeblocks = [block for block in self.blocks if (block.flag==True) ]
## self.resultQueue.put(JoinNode(self.newblocks,removeblocks))
except:
## print "****************process_counter : %s****************" % self.process_counter
traceback.print_exc()
pass
class KarnaughMap(object):
def __init__(self, n, MaxProcess=16384):
#self.blocks = Manager().list()
self.blocks = []
self.kmap = {}
self.kmapDCare = {}
self.kmapValues = {}
self.MaxProcess = MaxProcess
print "MaxProcess %d" % MaxProcess
self.completion = 0
# Set number of variables
self.numberOfVariables=n
self.numberOfDCares=0
# Determine width and height from n. of vars
self.width=int(pow(2, ceil(n/2.0)))
self.height=int(pow(2, floor(n/2.0)))
# Fill map with 0s and clear the list of KarnaughNodes
self.Reset()
# Fill map kmapValues with values that each cell in the map
# has. Look here for rules:
# http:#www.allaboutcircuits.com/vol_4/chpt_8/3.html
if(self.numberOfVariables>2):
for i in range(0,self.height):
for j in range(0,self.width):
if(i%2 ==0 ):
self.kmapValues[(j, i)]=self.GrayEncode(j+((i)*self.width))
else:
self.kmapValues[(j, i)]=self.GrayEncode(self.width-1-j+((i)*self.width))
else:
if(self.numberOfVariables==2):
self.kmapValues[(0, 0)]=0
self.kmapValues[(1, 0)]=1
self.kmapValues[(0, 1)]=2
self.kmapValues[(1, 1)]=3
if(self.numberOfVariables==1):
self.kmapValues[(0, 0)]=0
self.kmapValues[(1, 0)]=1
def Reset(self):
""" Fills map with zeros and deletes all nodes from the solution list """
for i in range(0,self.height):
for j in range(0,self.width):
self.Set(j, i, 0 )
self.blocks=Manager().list()
def Solve(self, completion):
""" Iterates through all possible ways that 'Don't cares' can be
arranged, and finds one with fewest number of nodes in the solution
(bestc). If there are more ways that give the same number of nodes
in the solution choose the one with biggest nodes (bestsc) """
best = []
bestc=-1
bestsc=0
#for i in range(0, int(pow(2.0, self.numberOfDCares )) ):
for i in range(0, 1 ):
b = []
j=i
while(j>0):
b.insert(0, (j%2) )
j=j/2
for j in range(len(b), self.numberOfDCares):
b.insert(0, 0 )
#self.blocks= Manager().list()
self.blocks= []
c=0
for k in range(0, self.height):
for l in range(0, self.width):
if(self.kmapDCare[(l, k)]==1):
self.kmap[(l, k)]=1
#if(b[c]==1):
# self.kmap[(l, k)]=1
#else:
# self.kmap[(l, k)]=0;
c += 1
self.Solve2( completion )
if( (bestc==-1) | (len(self.blocks)<=bestc) ):
sc=0
for iter in self.blocks:
for k in range(0,len(iter.values) ):
if(iter.values[k]==2):
sc += 1
if( (bestc==-1) | (len(self.blocks)<bestc) ):
best=self.blocks
bestc=len(best)
bestsc=sc
else:
if( sc>bestsc ):
best=self.blocks
bestc=len(best)
bestsc=sc
self.blocks=best
def Solve2(self, completion):
def Join(a,i):
CompBlocks = [block for block in blocks if self.IsJoinable(a.values, block.values )]
for b in CompBlocks:
x=self.IsJoinable(a.values, b.values )
if(x>0):
#/* If they can be joined make a new block with 2 in the place
#of the one bit where they a and b are different */
n = KarnaughNode()
n.numberOfItems=a.numberOfItems*2
n.flag = False
for j in range(0, len(a.values) ):
if(j!=(x-1)):
n.values.append(a.values[j] )
else:
n.values.append( 2 )
#/* Mark that a node is part of a larger node */
a.flag=True
b.flag=True
#/* Check if that block already exists in the list */
exist=False
for c in self.blocks:
if(n.values==c.values):
exist=True
if(not exist):
self.blocks.append(n )
def CleanProcess():
for process in ProcessList:
process.join()
for process in ProcessList:
jn = resultQueue.get()
for n in jn.newblocks:
exist = False
for c in self.blocks:
if(n.values==c.values):
exist=True
if(not exist):
self.blocks.append(n )
for b in jn.removeblocks:
for c in self.blocks:
if(b.values==c.values):
self.blocks.remove(c)
""" Check for special case that all cells in the map are the same """
a=1
for i in range(0,self.height):
if(a==0):
break
for j in range(0,self.width):
if( self.kmap[(j, i)]!=self.kmap[(0, 0)] ):
a=0
break
if(a==1):
#/* Clear the list so that all those nodes with one item are deleted */
#self.blocks=Manager().list()
self.blocks=[]
# If there are only zeros in the map there's nothing to solve
if (self.kmap[(0, 0)]==0):
return
else:
# If there are only ones, solution is one element as big as the map
n=KarnaughNode()
n.numberOfItems = self.width*self.height
for j in range(0,self.numberOfVariables):
n.values.append( 2 )
self.blocks.append(n )
return
#/* Put all blocks with 1 element in list */
for i in range(0, self.height):
for j in range(0, self.width):
if(self.kmap[(j, i)]==1):
n=KarnaughNode()
n.numberOfItems=1
n.flag=False
n.values=self.GetMapBoolValue(j, i )
self.blocks.append(n )
max = int(log(self.width*self.height )/log(2)+1)
# Joining blocks into blocks with 2^i elements
for sizeloop in range( 1, max ):
#/* Check every block with every other block and see if they can be joined
#into a bigger block */
blocks = [block for block in self.blocks if (block.numberOfItems == pow(2.0, sizeloop-1)) ]
## resultQueue = Queue()
ProcessList = []
for index, a in enumerate(blocks):
self.completion = int((1.0*(index+1)/len(blocks)*1.0*1/max+(sizeloop-1.0)/max)*100)
completion.value = self.completion
Join(a,sizeloop)
## processblocks = list(blocks)
## process = JoinTask(self, processblocks , a, i)
## ProcessList.append(process)
## #process.run()
## process.start()
## while len(ProcessList) >= self.MaxProcess:
## for process in ProcessList:
## process.join(1)
## if not process.is_alive():
## ProcessList.remove(process)
## while ProcessList:
## for process in ProcessList:
## process.join(10)
## if not process.is_alive():
## ProcessList.remove(process)
## else:
## print 'wait for process ...' % process.name
# Flag block include in other block
a_blocks = [block for block in self.blocks if (block.flag==False and block.numberOfItems < pow(2.0, sizeloop)) ]
for a_block in a_blocks:
b_blocks = [block for block in self.blocks if (block!=a_block and block.numberOfItems > a_block.numberOfItems) ]
for b_block in b_blocks:
flag_block = True
for index in range(len(b_block.values)):
if a_block.values[index] != b_block.values[index] and b_block.values[index] != 2:
flag_block = False
break
if flag_block:
self.blocks.remove(a_block)
break
#/* Deletes nodes that are cointained in larger nodes */
blocks = [block for block in self.blocks if (block.flag==True) ]
for a in blocks:
self.blocks.remove(a)
# Delete nodes that are Don't care only ones
blocks = self.blocks
for block in blocks:
DCareblock = True
for i in range(0,self.height):
for j in range(0,self.width):
if(self.IsAtCell(j, i, block.values)):
if self.kmapDCare[(j, i)]!=1:
DCareblock = False
if DCareblock:
self.blocks.remove(block)
#/* Deletes unneeded nodes. Draws a temp map with all nodes but one
#and if that map is same as the main map, node that wasn't drawn can be deleted */
temp = {}
blocks = self.blocks
for a in blocks:
for i in range(0,self.height):
for j in range(0,self.width):
temp[(j, i)]=0
for b in blocks:
if(a!=b):
for i in range(0,self.height):
for j in range(0,self.width):
if(self.IsAtCell(j, i, b.values)):
temp[(j, i)]=1
del_var=1
for i in range(0,self.height):
for j in range(0,self.width):
if(temp[(j, i)]!=self.kmap[(j, i)]) and self.kmapDCare[(j, i)] != 1 :
del_var=0
break
if(not del_var):
break
if(del_var):
self.blocks.remove(a )
def IsAtCell(self, x, y, a):
b=self.GetMapBoolValue(x, y )
for i in range(0, len(a) ):
if( (a[i]!=b[i]) & (a[i]!=2) ): return 0
return 1
def GetMapBoolValue(self, x, y):
b = []
i=self.GetMapValue(x, y )
while(i>0):
b.insert(0, i%2 )
i=i/2
for j in range(len(b), self.numberOfVariables):
b.insert(0, 0 )
return b
def IsJoinable(self, a, b):
""" Checks if 2 karnaugh nodes with values a and b are joinable (only differ in one bit),
and if they are returns (place where they differ + 1), otherwise returns 0 """
c=0
for i in range(0,len(a)):
if(a[i]!=b[i]):
c += 1
x=i
if(c==1):
return x+1
else:
return 0
def GrayEncode(self, g):
return int(g) ^ (int(g) >> 1 )
def Set(self, x, y, value):
self.kmap[(x, y)]=value
if(value==2) :
self.kmapDCare[(x, y)]=1
self.numberOfDCares += 1
else:
self.kmapDCare[(x, y)]=0
def Get(self, x, y):
if(not self.kmapDCare[(x,y)]):
return self.kmap[(x,y)]
else:
return 2
def GetMapValue(self, x, y):
return self.kmapValues[(x,y)]
def GetWidth(self):
return self.width
def GetHeight(self):
return self.height
def GetSolutions(self):
return self.blocks
def GetNumberOfVars(slef):
return self.numberOfVariables