-
Notifications
You must be signed in to change notification settings - Fork 1
/
blamframe.py
1474 lines (1243 loc) · 55.9 KB
/
blamframe.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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import wx
from wx import Notebook
from wx import grid
from wx import TreeCtrl
from wx import SpinCtrl
from wx import Config
import os
from time import sleep, time
import sys
import math
import truthtable
from kmap import *
from karnaughmap import *
from perfTableparser import perfTableParser
from ReduceBoolExpression import ReduceSol
#from DataThread import SolveTask
import traceback
import multiprocessing as mp
from multiprocessing import Process, Lock, Queue, Manager, Pool, cpu_count, Value
from Queue import Empty
import logging
from thread import start_new_thread
from threading import Thread
import blamframe
[Resize, wxID_STATUSBAR,
Menu_File_Load, Menu_File_Save, Menu_File_SaveTo,Menu_File_SaveSolution ,
Menu_File_Quit, Menu_File_About, Menu_Language_Croatian,
Menu_Language_Default, Menu_Cell_Adresses, Menu_Show_Zeros,
Vars_Count, Outputs_Count, Truth_Table,
Function_Button, Paste_Button,
Solve_Button, Sol_Txt, Sol_Tree, Equ_Txt, Equ_Tree, Solution_Type] = [wx.NewId() for __init__ in range(23)]
MAXOUTPUTS = 20
class MyStatusBar(wx.StatusBar):
""" Displays information about the current view. Also global stats/
progress bar etc. """
def __init__(self, *_args, **_kwargs):
wx.StatusBar.__init__(self, _kwargs['parent'], _kwargs['id'], style=wx.ST_SIZEGRIP)
self.progress_bar = wx.Gauge(self, -1, style=wx.GA_HORIZONTAL|wx.GA_SMOOTH)
self.SetFieldsCount(3)
self.ProgressBarSize()
def ProgressBarSize(self):
rect = self.GetFieldRect(1)
#self.progress_bar.SetPosition((rect.x+2, rect.y+2))
#self.progress_bar.SetSize((rect.width-4, rect.height-4))
self.progress_bar.SetDimensions(rect.x+1, rect.y+1, rect.width -2, rect.height -2)
class TaskKarnaughMap(KarnaughMap):
def __init__(self, numberOfOutputs, out, NbWorkers):
KarnaughMap.__init__(self, numberOfOutputs, int(NbWorkers))
self.out = out
def __call__(self, completion):
return self.Solve(completion)
def __str__(self):
return '%s * %s' % (self.out, self.out)
class Worker(Process):
def __init__(self, work_queue, result_queue, completion):
# base class initialization
Process.__init__(self)
# job management stuff
self.work_queue = work_queue
self.result_queue = result_queue
self.kill_received = False
self.completion = completion
self.Kmap = None
def run(self):
while not self.kill_received:
# get a task
#job = self.work_queue.get_nowait()
try:
self.Kmap = self.work_queue.get(True,0.1)
except Empty:
break
except:
traceback.print_exc()
pass
# the actual processing
print("Starting " + str(self.Kmap.out) + " ...")
self.Kmap(self.completion)
# store the result
self.result_queue.put(self.Kmap)
class SolveTask(Thread):
def __init__ (self,parent):
Thread.__init__(self)
self.daemon = True
self.parent = parent
def Solve(self):
# Mutlti Processing
NbWorkers = cpu_count()-1
mp.log_to_stderr()
logger = mp.get_logger()
logger.setLevel(logging.INFO)
outs = self.parent.numberOfOutputs.GetValue()
KmapList = []
numberOfVariables = self.parent.numberOfVariables.GetValue()
for out in range(0, outs):
#if ('' == self.parent.solution[out].GetItemText(self.parent.solution[out].GetRootItem())):
if (not self.parent.solution[out].GetRootItem().IsOk()) or ('' == self.parent.solution[out].GetItemText(self.parent.solution[out].GetRootItem())):
self.parent.solution[out].DeleteAllItems()
self.parent.kmap[out].ClearSolutions()
K = TaskKarnaughMap(numberOfVariables, out, NbWorkers)
for i in range(0, self.parent.kmap[out].GetNumberRows()) :
for j in range(0, self.parent.kmap[out].GetNumberCols()) :
if(self.parent.solveSOP):
if(self.parent.kmap[out].GetCellValue(i, j)==("1")):
K.Set(j,i, 1)
if(self.parent.kmap[out].GetCellValue(i, j)==("0")):
K.Set(j,i, 0)
if(self.parent.kmap[out].GetCellValue(i, j)==("?")):
K.Set(j,i, 2)
else :
if(self.parent.kmap[out].GetCellValue(i, j)==("1")):
K.Set(j,i, 0)
if( (self.parent.kmap[out].GetCellValue(i, j)==("0")) | (self.parent.kmap[out].GetCellValue(i, j)==(""))):
K.Set(j,i, 1)
if(self.parent.kmap[out].GetCellValue(i, j)==("?")):
K.Set(j,i, 2)
self.parent.work_queue.put(K)
KmapList.append(K)
if self.parent.work_queue.qsize() < NbWorkers:
NbWorkers = self.parent.work_queue.qsize()
self.parent.WorkerList = []
for i in range(NbWorkers):
completion = Value('i', 0)
worker = Worker(self.parent.work_queue, self.parent.result_queue, completion)
self.parent.WorkerList.append((worker, completion))
worker.start()
#worker.run()
# Wait for all job finish
while self.parent.WorkerList:
for (worker, completion) in self.parent.WorkerList:
worker.join(10)
if not worker.is_alive():
self.parent.WorkerList.remove((worker,completion))
else:
print 'Solver->%s %s%% complete' % (worker.name, completion.value )
## # remove all workers
## for worker in self.parent.WorkerList:
## worker.kill_received = True
## self.parent.WorkerList.remove(worker)
def run(self):
self.Solve()
class UpdateThread(Thread):
def __init__ (self,parent, parser, start, end, MAX):
Thread.__init__(self)
self.daemon = False
self.parent = parent
self.completion = 0
self.parser = parser
self.startindex = int(start)
self.endindex = int(end)
self.MAX = MAX
def loop(self):
parser = self.parser
start = self.startindex
end = self.endindex
vars = len(parser.sweepVarNames)
outs = len(parser.variablesList) - vars
for row in range(start, end):
self.completion = int( 100*(row-start)/(end-start) )
rowbit=[]
conv = row
for index in range(0,vars):
rowbit.append(conv%2)
conv = conv /2
rowbit.reverse()
line = [line for line in parser.myArray if self.parent.SameBitCode(rowbit, line)]
try:
line = line[0]
except IndexError:
raise Exception( 'Probably undefine value for row : %s' % rowbit )
#for col in range(0,vars):
# self.truthTable.SetCellValueEvent(row, col, str(int(colbit[col])))
col = vars
if self.MAX > 2:
# MAX = 2 can not be perform as it is the don't care state
value = line[-1]
if type(value) == str or type(value) == unicode :
self.parent.truthTable.SetCellValueEvent(row, vars+outs, value)
else:
self.parent.truthTable.SetCellValueEvent(row, vars+outs, str(int(value)))
else:
valueList = list(line[vars:])
valueList.reverse()
value = 0
if 2.0 in valueList or outs <2:
# Don't care ...
for value in line[vars:]:
self.parent.truthTable.SetCellValueEvent(row, col, str(int(value)))
col += 1
else:
for powerindex, valbit in enumerate(valueList):
value += valbit*pow(2,powerindex)
self.parent.truthTable.SetCellValueEvent(row, vars+outs, str(int(value)))
def run(self):
try:
self.loop()
except:
traceback.print_exc()
def walk_branches(tree,root):
""" a generator that recursively yields child nodes of a wx.TreeCtrl """
if root.IsOk():
item, cookie = tree.GetFirstChild(root)
while item.IsOk():
yield item
if tree.ItemHasChildren(item):
walk_branches(tree,item)
item,cookie = tree.GetNextChild(root,cookie)
class blamFrame(wx.Frame):
def __init__(self, title, pos, size, locale=None ):
parent=None
wx.Frame.__init__(self, parent, -1, title, pos, size)
# ##### Variable initialization ****/
self.solveSOP=1
self.Reduce = None
self.WorkerList = []
self.work_queue = Queue()
self.result_queue = Queue()
self.solvethread = None
self.UpdateLock = Lock()
self.LastTime = None
self.SolveLeft = 0
# ##### Icon *****/
appdir = os.path.dirname(sys.argv[0])
if appdir == '':
appdir = '.'
icon = wx.Icon( appdir + os.sep +'wxwin.ico', wx.BITMAP_TYPE_ICO)
self.SetIcon(icon)
# ##### Menu *****/
menuFile = wx.Menu()
menuFile.Append(Menu_File_Load, ("&Load"), ("Load from file"))
self.Bind(wx.EVT_MENU, self.OnLoad, id=Menu_File_Load)
menuFile.Append(Menu_File_Save, ("&Save"), ("Save to file"))
self.Bind(wx.EVT_MENU, self.OnSave, id=Menu_File_Save)
menuFile.Append(Menu_File_SaveTo, ("Save to ..."), ("Save to new file"))
self.Bind(wx.EVT_MENU, self.OnSaveTo, id=Menu_File_SaveTo)
menuFile.Append(Menu_File_SaveSolution, ("Save Solution to ..."), ("Save solution to file"))
self.Bind(wx.EVT_MENU, self.OnSaveSol, id=Menu_File_SaveSolution)
# wxBitmap aboutBitmap(wxT("about.xpm"), wxBITMAP_TYPE_XPM )
menuFile.Append(Menu_File_About, ("&About"), ("About the program"))
self.Bind(wx.EVT_MENU, self.OnAbout, id=Menu_File_About)
# about.SetBitmap(aboutBitmap)
menuFile.AppendSeparator()
# wxBitmap exitBitmap(wxT("exit.xpm"), wxBITMAP_TYPE_XPM )
menuFile.Append(Menu_File_Quit, ("E&xit"), ("Exit the program"))
self.Bind(wx.EVT_MENU, self.OnQuit, id=Menu_File_Quit)
# exit.SetBitmap(exitBitmap)
# Settings menu
menuSettings = wx.Menu()
menuLanguage = wx.Menu()
menuLanguage.Append(Menu_Language_Default, ("English (default)"), ("Set language to english"), wx.ITEM_RADIO)
self.Bind(wx.EVT_MENU, self.OnLangDefault, id=Menu_Language_Default)
menuSettings.AppendMenu(-1, u'Language', menuLanguage, u'Set language (requires restart)')
menuSettings.AppendSeparator()
#showZeros= wx.MenuItem(0, Menu_Show_Zeros, ("Show zeros"), ("Show / hide zero values"), wx.ITEM_CHECK)
showZeros= wx.MenuItem(menuSettings, Menu_Show_Zeros, ("Show zeros"), ("Show / hide zero values"), wx.ITEM_CHECK)
self.Bind(wx.EVT_MENU, self.OnShowZeros, id=Menu_Show_Zeros)
showAdress=wx.MenuItem(menuSettings, Menu_Cell_Adresses, ("Show cell adresses"), ("Show / hide cell adresses in the K-map"), wx.ITEM_CHECK)
self.Bind(wx.EVT_MENU, self.OnCellAdresses, id=Menu_Cell_Adresses)
menuSettings.AppendItem( showZeros )
menuSettings.AppendItem( showAdress )
menuBar = wx.MenuBar()
menuBar.Append( menuFile, ( "&Program" ) )
menuBar.Append( menuSettings, ( "&Settings" ) )
self.SetMenuBar( menuBar )
# ##### Status Bar *****/
self.statusbar = MyStatusBar(id=wxID_STATUSBAR,
name='statusBar', parent=self, style=0)
self.SetStatusBar(self.statusbar)
#self.statusbar = self.CreateStatusBar()
self.statusbar.SetFieldsCount(3)
self.statusbar.SetStatusWidths([-3, -1, -2])
self.SetStatusText( ( "Welcome to Karnaugh Map Minimizer!" ),0 )
# Progress Bar
self.progress_bar = self.statusbar.progress_bar
#self.ProgressBarSize()
self.progress_bar.Hide()
# ##### Main panel initialization *****/
mainPanel= wx.Panel(self, -1, wx.DefaultPosition, wx.DefaultSize)
# ##### Spliter #####/
mainSpliter = wx.SplitterWindow(mainPanel, -1, style=wx.SP_LIVE_UPDATE)
mainLeftPanel = wx.Panel(mainSpliter)
mainLeftPanel.SetMinSize(wx.Size(300, 400))
mainRightPanel = wx.Panel(mainSpliter)
mainRightPanel.SetMinSize(wx.Size(100, 400))
mainSpliter.SplitVertically(mainLeftPanel, mainRightPanel, sashPosition=0)
#mainSpliter.Fit()
# ##### Notebook control initialization *****/
self.methodBook = wx.Notebook(mainRightPanel, -1, style=wx.BK_DEFAULT|wx.NB_MULTILINE)
# ##### Sizers initialization *****/
panelSizer = wx.BoxSizer(wx.HORIZONTAL)
mainSizer = wx.BoxSizer(wx.VERTICAL)
leftSizer = wx.StaticBoxSizer( wx.StaticBox(mainLeftPanel, -1, ("Truth table")), wx.VERTICAL)
rightSizer = wx.BoxSizer(wx.VERTICAL)
rightSizerTop = wx.BoxSizer(wx.HORIZONTAL)
rightSizerBottom = wx.BoxSizer(wx.HORIZONTAL)
# Layout
mainSizer.Add(rightSizerTop, 0, wx.EXPAND | wx.BOTTOM, 10)
panelSizer.Add(mainPanel, 1, wx.EXPAND)
rightSizer.Add(rightSizerBottom, 2, wx.EXPAND)
mainSizer.Add(mainSpliter, 1, wx.EXPAND | wx.ALL, 0)
# ##### Controls *****/
# ##### Trouth table *****/
self.truthTable = truthtable.TruthTable(mainLeftPanel, Truth_Table, 4, 1, wx.DefaultPosition, wx.Size(170,200), wx.SIMPLE_BORDER, wx.PanelNameStr)
leftSizer.Add(self.truthTable, 1, wx.EXPAND | wx.ALL, 5)
leftSizer.Add( wx.Button(mainLeftPanel, Function_Button, ("Fill from function")), 0, wx.EXPAND | wx.ALL, 5)
leftSizer.Add( wx.Button(mainLeftPanel, Paste_Button, ("Paste from clipboard")), 0, wx.EXPAND | wx.LEFT | wx.BOTTOM | wx.RIGHT, 5)
# ##### Karnaugh Map Notebook page *****/
self.kmap = []
self.solution = []
self.solutionTxt = []
self.AddPage(0)
# ##### Equations tree control *****/
self.EquationsTxt = wx.StaticText(mainRightPanel, Equ_Txt, ("Equations:"))
rightSizer.Add( self.EquationsTxt, 0, wx.EXPAND | wx.TOP, 0)
self.EquationsTxt.Hide()
self.Equations = wx.TreeCtrl(mainRightPanel, Equ_Tree, wx.DefaultPosition, wx.DefaultSize, wx.SIMPLE_BORDER | wx.TR_HAS_BUTTONS | wx.TR_HIDE_ROOT | wx.TR_MULTIPLE )
self.Equations.Hide()
#rightSizer.Add(self.solution, 1, wx.EXPAND | wx.TOP, 5)
rightSizer.Add(self.Equations, 1, wx.EXPAND | wx.TOP, 5)
# ##### Solve Button ****/
Solve_Button_wx = wx.Button(mainRightPanel, Solve_Button, ("Solve"))
rightSizer.Add( Solve_Button_wx, 0, wx.ALIGN_RIGHT | wx.TOP, 10)
rightSizerBottom.Add(self.methodBook, 1, wx.EXPAND | wx.BOTTOM, 10)
# ##### Settings controls ****/
rightSizerTop.Add( wx.StaticText(mainPanel, -1, ("Number of variables: ")), 0, wx.CENTER | wx.RIGHT, 10)
self.numberOfVariables = wx.SpinCtrl(mainPanel, Vars_Count, ("4"), wx.DefaultPosition, wx.Size(50,-1))
self.numberOfVariables.SetRange(1, 15)
rightSizerTop.Add(self.numberOfVariables, 0, wx.CENTER)
rightSizerTop.Add( wx.StaticText(mainPanel, -1, ("Number of outputs: ")), 0, wx.CENTER | wx.RIGHT, 10)
self.numberOfOutputs = wx.SpinCtrl(mainPanel, Outputs_Count, ("1"), wx.DefaultPosition, wx.Size(50,-1))
self.numberOfOutputs.SetRange(1, MAXOUTPUTS)
rightSizerTop.Add(self.numberOfOutputs, 0, wx.CENTER)
rightSizerTop.Add( wx.StaticText(mainPanel, -1, ("Type of solution: ")), 0, wx.CENTER | wx.LEFT | wx.RIGHT, 10)
solutionType = wx.Choice(mainPanel, Solution_Type)
solutionType.Append(("Sum of products"))
solutionType.Append(("Product of sums"))
solutionType.SetSelection(0)
rightSizerTop.Add(solutionType, 1, wx.CENTER)
# ##### Set sizers *****/
mainPanel.SetSizer(mainSizer)
mainSizer.SetSizeHints(mainPanel)
mainLeftPanel.SetSizer(leftSizer)
mainRightPanel.SetSizer(rightSizer)
self.SetSizerAndFit(panelSizer)
panelSizer.SetSizeHints(self)
self.SetAutoLayout(1)
mainLeftPanel.Layout()
mainRightPanel.Layout()
# Event
self.Bind(wx.EVT_SIZE, self.OnSize, self, id=Resize)
self.Bind(wx.EVT_SPINCTRL, self.OnVarsChange, id=Vars_Count)
self.Bind(wx.EVT_SPINCTRL, self.OnOutsChange, id=Outputs_Count)
self.Bind(grid.EVT_GRID_CMD_CELL_CHANGE, self.OnTruthTChange, id=Truth_Table)
self.Bind(grid.EVT_GRID_CMD_LABEL_LEFT_CLICK, self.OnTruthTLabelChange, id=Truth_Table)
self.Bind(grid.EVT_GRID_CMD_LABEL_RIGHT_CLICK, self.OnTruthTLabelChange, id=Truth_Table)
self.Bind(wx.EVT_BUTTON, self.OnSolve, id=Solve_Button)
self.Bind(wx.EVT_BUTTON, self.OnFunction, id=Function_Button)
self.Bind(wx.EVT_BUTTON, self.OnPaste, id=Paste_Button)
self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSolSelect, id=Sol_Tree)
self.Bind(wx.EVT_CHOICE, self.OnSolutionTypeChange, id=Solution_Type)
self.Bind(wx.EVT_IDLE, self.OnIdle)
# ##### Load configuration ****/
config = wx.Config(("Karnaugh Map Minimizer"))
## if ( config.Read(("Language"), lang) ) :
## if(lang==("")): menuLanguage.Check(Menu_Language_Default, 1)
## if(lang==("hr")): menuLanguage.Check(Menu_Language_Croatian, 1)
if config.HasEntry('Cell_Adresses') :
adresses = config.Read(("Cell_Adresses"), 'yes')
if(adresses==("no")) :
menuSettings.Check(Menu_Cell_Adresses, 0)
self.kmap[0].SetCellAdresses(0)
else :
menuSettings.Check(Menu_Cell_Adresses, 1)
self.kmap[0].SetCellAdresses(1)
else :
menuSettings.Check(Menu_Cell_Adresses, 1)
self.kmap[0].SetCellAdresses(1)
if config.HasEntry('Show_Zeros') :
zeros = config.Read('Show_Zeros', 'yes' )
if(zeros=="no") :
menuSettings.Check(Menu_Show_Zeros, 0)
self.kmap[0].SetShowZeros(0)
self.truthTable.SetShowZeros(0)
else :
menuSettings.Check(Menu_Show_Zeros, 1)
self.kmap[0].SetShowZeros(1)
self.truthTable.SetShowZeros(1)
else :
menuSettings.Check(Menu_Show_Zeros, 0)
self.kmap[0].SetShowZeros(0)
self.truthTable.SetShowZeros(0)
argv = sys.argv[1:]
if len(argv) == 1 and type(argv[0]) == str and argv[0][0] in ['"', "'"]:
argv[0] = eval(argv[0])
if len(argv) == 1 and (os.path.isfile(argv[0]) or os.path.islink(argv[0] )):
print "Loading %s ..." % argv[0]
self.LoadFile(argv[0])
self.currentFileName = argv[0]
config.Write('CurrentFileName', self.currentFileName)
elif config.HasEntry('CurrentFileName') :
self.currentFileName = config.Read('CurrentFileName', '' )
if self.currentFileName != '' and (os.path.isfile(self.currentFileName) or os.path.islink(self.currentFileName) ) :
print "Loading %s ..." % self.currentFileName
self.LoadFile(self.currentFileName)
else:
self.currentFileName = None
else :
self.currentFileName = None
del config
def OnSize(self, event):
self.ProgressBarSize()
self.Layout()
def ProgressBarSize(self):
rect = self.statusbar.GetFieldRect(1)
#self.progress_bar.SetPosition((rect.x+2, rect.y+2))
#self.progress_bar.SetSize((rect.width-4, rect.height-4))
self.progress_bar.SetDimensions(rect.x+1, rect.y+1, rect.width -2, rect.height -2)
def OnLoad( self, event):
filters = 'kmap files (*.kmap)|*.kmap|All files (*.*)|*.*'
if self.currentFileName:
StartDirectory = os.path.dirname(self.currentFileName)
else:
StartDirectory = '.'
dialog = wx.FileDialog ( None, message = 'Save Table to File',
defaultDir=StartDirectory ,
wildcard = filters, style = wx.OPEN )
if dialog.ShowModal() == wx.ID_OK:
filePath = dialog.GetPath()
else:
filePath = []
dialog.Destroy()
if filePath:
config = wx.Config('Karnaugh Map Minimizer')
config.Write('CurrentFileName', filePath)
self.currentFileName = filePath
self.LoadFile(filePath)
def LoadFile( self, filePath):
parser = perfTableParser()
if parser.parseFile(self, filePath):
self.UpdateData(parser)
self.SetStatusText( os.path.basename(filePath),2 )
def OnSave( self, event):
if (self.currentFileName != None):
self.truthTable.Write(self.currentFileName)
else:
self.OnSaveTo(event)
def OnSaveTo( self, event=None):
filters = 'kmap files (*.kmap)|*.kmap|All files (*.*)|*.*'
if self.currentFileName:
StartDirectory = os.path.dirname(self.currentFileName)
else:
StartDirectory = '.'
dialog = wx.FileDialog ( None, message = 'Save Table to File',
defaultDir=StartDirectory ,
wildcard = filters, style = wx.SAVE )
if dialog.ShowModal() == wx.ID_OK:
selected = dialog.GetPath()
FileNameExt = dialog.GetFilename().split('.').pop()
else:
selected = []
dialog.Destroy()
if selected:
if FileNameExt != 'kmap':
file = selected + '.kmap'
else:
file = selected
self.truthTable.Write(file)
self.currentFileName = file
self.SetStatusText( os.path.basename(file),2 )
def OnSaveSol(self, event):
filters = 'kmapSolultion files (*.ksol)|*.ksol|All files (*.*)|*.*'
if self.currentFileName:
StartDirectory = os.path.dirname(self.currentFileName)
else:
StartDirectory = '.'
dialog = wx.FileDialog ( None, message = 'Save Solution to File',
defaultDir=StartDirectory ,
wildcard = filters, style = wx.SAVE )
if dialog.ShowModal() == wx.ID_OK:
selected = dialog.GetPath()
FileNameExt = dialog.GetFilename().split('.').pop()
else:
selected = []
dialog.Destroy()
if selected:
if FileNameExt != 'ksol':
file = selected + '.ksol'
else:
file = selected
self.WriteSol(file)
def OnVarsChange( self, event ):
for solution in self.solution:
solution.DeleteAllItems()
for solutionTxt in self.solutionTxt:
solutionTxt.SetLabel('Solution:')
for kmap in self.kmap:
kmap.ClearSolutions()
self.truthTable.SetVars(self.numberOfVariables.GetValue())
for kmap in self.kmap:
kmap.SetVars(self.numberOfVariables.GetValue())
def OnOutsChange( self, event ):
outs = self.numberOfOutputs.GetValue()
self.truthTable.SetOuts(outs)
nbpages = self.methodBook.GetPageCount()
if(nbpages<outs):
while nbpages<outs:
self.AddPage(outs-1)
nbpages = self.methodBook.GetPageCount()
if(nbpages>outs):
while nbpages>outs:
self.methodBook.DeletePage(nbpages-1)
del self.kmap[nbpages-1]
del self.solution[nbpages-1]
del self.solutionTxt[nbpages-1]
nbpages = self.methodBook.GetPageCount()
def OnFunction( self, event ):
None
def OnPaste( self, event ):
if not wx.TheClipboard.IsOpened(): # may crash, otherwise
do = wx.TextDataObject()
wx.TheClipboard.Open()
success = wx.TheClipboard.GetData(do)
wx.TheClipboard.Close()
if success:
parser = perfTableParser()
if parser.parseClipboard(self, do.GetText()):
parser.sweepVarNames = parser.variablesList[:-1]
MAX = max([value[-1] for value in parser.myArray if type(value[-1]) == float])
NbOutputs = int(ceil(log(MAX+1)/log(2)))
if NbOutputs >= 2:
savevar = parser.variablesList[-1]
parser.variablesList = parser.variablesList[:-1]
for index in range(NbOutputs-1,-1,-1):
newVar = (savevar[0]+'<'+str(index)+'>', float, 1)
parser.variablesList.append(newVar)
self.UpdateData(parser)
else:
return
def ClearInterface(self):
for solution in self.solution:
solution.DeleteAllItems()
for solutionTxt in self.solutionTxt:
solutionTxt.SetLabel('Solution:')
if self.Reduce:
self.Equations.DeleteAllItems()
self.EquationsTxt.Hide()
self.Equations.Hide()
self.Layout()
self.Reduce = []
def UpdateData (self, parser):
for kmap in self.kmap:
kmap.ClearSolutions()
self.ClearInterface()
# Update True Table and Karnaugh
vars = len(parser.sweepVarNames)
outs = len(parser.variablesList) - vars
self.numberOfVariables.SetValue(vars)
self.numberOfOutputs.SetValue(outs)
# Update the number of Karnaugh table
nbpages = self.methodBook.GetPageCount()
if(nbpages<outs):
while(nbpages<outs):
self.AddPage(nbpages)
nbpages = self.methodBook.GetPageCount()
if(nbpages>outs):
while(nbpages>outs):
self.methodBook.DeletePage(nbpages-1)
del self.kmap[nbpages-1]
del self.solution[nbpages-1]
del self.solutionTxt[nbpages-1]
nbpages = self.methodBook.GetPageCount()
# Update Karnaugh Table Label
for pagenb in range(0, self.methodBook.GetPageCount()):
self.methodBook.SetPageText(outs-1-pagenb,("Karnaugh map %s") % parser.variablesList[vars+pagenb][0])
# Update True Table Size
self.truthTable.SetVars(vars, UpdateGrid = False)
self.truthTable.SetOuts(outs)
for kmap in self.kmap:
kmap.SetVars(vars)
# Update True Table Columns Label
col = 0
for Varname, Type, Size in parser.variablesList:
self.truthTable.SetColLabelValue(col,Varname)
self.truthTable.SetColLabelSizefromLabel(col)
col += 1
# Update True Table data
MAX = max([value[-1] for value in parser.myArray if type(value[-1]) == float])
ThreadList = []
ref = vars-1
paquet = pow(2,ref)
# TODO: PB with threading this so set ref = 0
ref = 0
if ref<=1 :
thread = UpdateThread(self, parser, 0, int(pow(2,vars)), MAX )
thread.run()
#thread.start()
ThreadList.append( thread )
else:
for paquet_index in range(0, int(pow(2, vars-ref))):
start = 0+paquet_index*pow(2, ref)
end = pow(2, ref)+paquet_index*pow(2, ref)
thread = UpdateThread(self, parser,start, end, MAX)
#thread.run()
thread.start()
ThreadList.append( thread )
## while ThreadList:
## for thread in ThreadList:
## thread.join(10)
## if not thread.is_alive():
## ThreadList.remove(thread)
## else:
## print 'Main %s %s%% complete' % (thread.getName(), thread.completion )
def SameBitCode(self, a, b):
for abit,bbit in zip(a,b):
if abit != bbit:
if abit != 'X' and bbit != 'X':
return False
return True
def OutputName(self, out):
vars=self.numberOfVariables.GetValue()
outs=self.numberOfOutputs.GetValue()
Name = self.truthTable.GetColLabelValue(vars+outs-1-out)
return Name
def ColName(self, inputNb):
Name = self.truthTable.GetColLabelValue(inputNb)
return Name
def AddPage(self, PageNumber):
Karnaugh_Map = wx.NewId()
# ##### Karnaugh Map Notebook page *****/
kmapPanel = wx.Panel(self.methodBook, -1)
kmapSizer = wx.BoxSizer(wx.VERTICAL)
# ##### Karnaugh map grid control *****/
self.kmap.append( KMap(kmapPanel, Karnaugh_Map, 4, wx.DefaultPosition, wx.Size(100,130), wx.SIMPLE_BORDER) )
kmapSizer.Add(self.kmap[PageNumber], 1, wx.EXPAND | wx.ALL, 5)
# ##### Solutions tree control *****/
#rightSizer.Add( wx.StaticText(mainPanel, -1, ("Solution:")), 0, wx.EXPAND | wx.TOP, 0)
self.solutionTxt.append(wx.StaticText(kmapPanel, Sol_Txt, ("Solution:")) )
kmapSizer.Add( self.solutionTxt[PageNumber], 0, wx.EXPAND | wx.TOP, 0)
#self.solution = wx.TreeCtrl(mainPanel, Sol_Tree, wx.DefaultPosition, wx.DefaultSize, wx.SIMPLE_BORDER | wx.TR_HAS_BUTTONS )
self.solution.append( wx.TreeCtrl(kmapPanel, Sol_Tree, wx.DefaultPosition, wx.DefaultSize, wx.SIMPLE_BORDER | wx.TR_HAS_BUTTONS ) )
#rightSizer.Add(self.solution, 1, wx.EXPAND | wx.TOP, 5)
kmapSizer.Add(self.solution[PageNumber], 1, wx.EXPAND | wx.TOP, 5)
kmapPanel.SetSizer(kmapSizer)
self.methodBook.AddPage(kmapPanel, ("Karnaugh map f%d") % PageNumber)
# Event
self.Bind(grid.EVT_GRID_CMD_CELL_CHANGE, self.OnKMapChange, id=Karnaugh_Map)
# config
config = wx.Config(("Karnaugh Map Minimizer"))
if config.HasEntry('Cell_Adresses') :
adresses = config.Read(("Cell_Adresses"), 'yes')
if(adresses==("no")) :
self.kmap[-1].SetCellAdresses(0)
else :
self.kmap[-1].SetCellAdresses(1)
else :
self.kmap[-1].SetCellAdresses(1)
if config.HasEntry('Show_Zeros') :
zeros = config.Read('Show_Zeros', 'yes' )
if(zeros=="no") :
self.kmap[-1].SetShowZeros(0)
else :
self.kmap[-1].SetShowZeros(1)
else :
self.kmap[-1].SetShowZeros(0)
del config
def OnTruthTChange( self, event ):
vars = self.numberOfVariables.GetValue()
outs = self.numberOfOutputs.GetValue()
OutCol = outs-1 - (event.GetCol() - vars)
if OutCol >= 0 and OutCol < self.numberOfOutputs.GetValue():
# Only column for outputs
self.solution[OutCol].DeleteAllItems()
self.solutionTxt[OutCol].SetLabel('Solution:')
if self.Reduce:
self.Equations.DeleteAllItems()
self.Reduce = []
self.kmap[OutCol].ClearSolutions()
self.kmap[OutCol].Set(event.GetRow(), self.truthTable.GetCellValue(event.GetRow(), event.GetCol()))
def OnTruthTLabelChange( self, event):
vars = self.numberOfVariables.GetValue()
outs = self.numberOfOutputs.GetValue()
Row = event.GetRow()
Col = event.GetCol()
OutCol = outs-1 - (Col - vars)
if Col >= 0 :
ColLabel = self.truthTable.GetColLabelValue(Col)
if OutCol >= 0 and OutCol < self.numberOfOutputs.GetValue():
# Only column for outputs
self.methodBook.SetPageText(OutCol,("Karnaugh map %s") % ColLabel)
def OnKMapChange( self, event ):
vars = self.numberOfVariables.GetValue()
outs = self.numberOfOutputs.GetValue()
PageNb = self.kmap.index(event.GetEventObject())
self.solution[PageNb].DeleteAllItems()
self.solutionTxt[PageNb].SetLabel('Solution:')
if self.Reduce:
self.Equations.DeleteAllItems()
self.Reduce = []
self.kmap[PageNb].ClearSolutions()
self.truthTable.SetCellValueEvent(self.kmap[PageNb].GetMapValue(event.GetCol(), event.GetRow()), vars+(outs-1-PageNb), self.kmap[PageNb].GetCellValue(event.GetRow(), event.GetCol()))
def OnSolve( self, event ):
# Disable Interface entries
#self.Disable()
## self.methodBook.Disable()
## self.truthTable.Disable()
self.SetStatusText( ( "Solving, please wait..." ) )
self.progress_bar.Show()
self.SolveLeft = self.numberOfOutputs.GetValue()
self.solvethread = SolveTask(self)
self.solvethread.start()
#self.solvethread.run()
def OnIdle(self, event):
try:
time()-self.LastTime
except:
self.LastTime = time()
TimeInterval = 1
try:
if time()-self.LastTime > TimeInterval:
self.LastTime = time()
if self.solvethread:
outs = self.numberOfOutputs.GetValue()
if self.solvethread.is_alive():
NbWorkLeft = self.SolveLeft
# Current job progress
JobCompletion = 0
for (worker,completion) in self.WorkerList:
if worker.is_alive():
JobCompletion += 1.0*completion.value/100
wx.CallAfter(self.progress_bar.SetValue, (outs-(NbWorkLeft-JobCompletion))*100/outs)
## else:
## if self.SolveLeft == 0:
## self.SetStatusText( ( "Karnaugh map solved!" ) )
## self.progress_bar.Hide()
while not self.result_queue.empty():
try:
Kmap = self.result_queue.get()
self.Updateparent(Kmap.GetSolutions(), Kmap.out)
self.SolveLeft -= 1
if self.SolveLeft == 0:
vars = self.numberOfVariables.GetValue()
self.Reduce = ReduceSol(self, self.GetSolutions(), vars, outs)
self.Reduce.reduce()
for out in range(outs):
self.solution[out].DeleteAllItems()
self.Updateparent(self.Reduce.AllSolutions[out],out)
self.UpdateEquations()
self.SetStatusText( ( "Karnaugh map solved!" ) )
self.progress_bar.Hide()
## except Empty:
## pass
except:
traceback.print_exc()
pass
except:
traceback.print_exc()
pass
event.Skip()
def solutionStr(self, values, OP ='.', inv=False):
outs = [len(out) for out in self.GetSolutions()]
vars=self.numberOfVariables.GetValue()
if OP == '.':
b = '' # A, B, C, D
else:
b = '('
a = '' # All the rest
for i in range(0, len(values)):
if values[i] != 2:
if i < vars:
# Intputs
InvStr = ''
if ((values[i]==0) and (self.solveSOP)) or ((values[i]==1) and (not self.solveSOP)):
InvStr = '|'
if inv :
if InvStr == '':
InvStr = '|'
else:
InvStr = ''
a += InvStr+self.ColName(i)+OP
elif i >=vars and i < sum(outs)+vars:
# Output Equations
for outindex in range(len(outs)):
if i >= vars+sum(outs[:outindex]) and i < vars+sum(outs[:outindex+1]):
InvStr = ''
if(values[i]==0):
InvStr = '|'
if inv :
if InvStr == '':
InvStr = '|'
else:
InvStr = ''
a += InvStr
SolName=self.OutputName(outindex)
if SolName.endswith('>'):
SolName = SolName.replace('<','').replace('>','')
a += '%s_Equ%s' % (SolName,str(i- (vars+sum(outs[:outindex])) ))+OP
elif i >= sum(outs)+vars:
# Equations
InvStr = ''
if(values[i]==0):
InvStr = '|'
if inv :
if InvStr == '':
InvStr = '|'
else:
InvStr = ''
a += InvStr
a += 'Equ%s' % str(i- (sum(outs)+vars) ) + OP
b=b+a[0:-1]
if OP == '.' and b == '':
b='1'
elif OP == '+':
if b == '(':
b='0'
else:
b = b + ')'
return b
def Dependency(self):
AllSolutions = self.Reduce.AllSolutions
outsList = [len(out) for out in self.GetSolutions()]
vars=self.numberOfVariables.GetValue()
outs = self.numberOfOutputs.GetValue()
b = []
a= ''
for out in range(0,len(AllSolutions)):
solutionsList0 = AllSolutions[out]
NbInputs0 = len(solutionsList0)
if out >= outs:
#Equations
NbInputs0 = 1
print 'Equation...'
for index, iter in enumerate(solutionsList0):
if type(iter) != list:
values = iter.values
self.kmap[out].AddSolution(values)