-
Notifications
You must be signed in to change notification settings - Fork 0
/
slalomWindow.py
2785 lines (2329 loc) · 103 KB
/
slalomWindow.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
# -*- coding: utf-8 -*-
# ======================================================================================================
# SLALOM - Open-Source Solar Cell Multivariate Optimizer
# Copyright(C) 2012-2019 Sidi OULD SAAD HAMADY (1,2,*), Nicolas FRESSENGEAS (1,2). All rights reserved.
# (1) Université de Lorraine, Laboratoire Matériaux Optiques, Photonique et Systèmes, Metz, F-57070, France
# (2) Laboratoire Matériaux Optiques, Photonique et Systèmes, CentraleSupélec, Université Paris-Saclay, Metz, F-57070, France
# (*) sidi.hamady@univ-lorraine.fr
# SLALOM source code is available to download from:
# https://github.com/sidihamady/SLALOM
# https://hal.archives-ouvertes.fr/hal-01897934
# http://www.hamady.org/photovoltaics/slalom_source.zip
# Cite as: S Ould Saad Hamady and N Fressengeas, EPJ Photovoltaics, 9:13, 2018.
# See Copyright Notice in COPYRIGHT
# ======================================================================================================
# ------------------------------------------------------------------------------------------------------
# File: slalomWindow.py
# Type: Class
# Use: The slalomWindow class and related classes are used by the slalomMonitor module.
# slalomWindow provides visualisation and control functionality...
# either in client/server configuration using ssh...
# ... or locally if it runs on the same machine than the optimizer.
# slalomWindow uses tkinter that is already installed on the client...
# (this is generally the case, except for some CentOS or RedHat machines)
# ------------------------------------------------------------------------------------------------------
from slalomCore import *
import threading
import re
# tkinter is not always installed by default (e.g. in RedHat Enterprise Linux 7+ or CentOS 6.x)...
# ...if not installed, the graphic part of the optimizer cannot be started...
# ...(just (re)install it or install a more recent python/numpy/scipy/matplotlib/tk version...
# ....and restart slalomMonitor).
TkFound = False
try:
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as pl
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.backends.backend_tkagg
from matplotlib.font_manager import FontProperties
if sys.version_info[0] < 3:
# Python 2.7.x
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
import Tkinter as Tk
import ttk
import tkFileDialog
import tkFont
import tkMessageBox
else:
# Python 3.x
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.backends.backend_tkagg import NavigationToolbar2Tk as NavigationToolbar2TkAgg
import tkinter as Tk
import tkinter.ttk as ttk
import tkinter.filedialog as tkFileDialog
import tkinter.font as tkFont
import tkinter.messagebox as tkMessageBox
# end if
import matplotlib.pyplot as pl
from matplotlib.backends.backend_pdf import PdfPages
from matplotlib.ticker import MaxNLocator
TkFound = True
except ImportError as ierr:
# tkinter related modules not found. Just warn and skip this part.
# just install or update python/numpy/scipy/matplotlib/tk modules
dispError("{0}".format(ierr), doExit = False)
# catch only Exception (since sys.exit raise BaseException)
pass
except:
pass
try:
class NavigationToolbar(NavigationToolbar2TkAgg):
""" custom toolbar including an Autoscale and PDF save buttons """
def __init__(self, chart):
NavigationToolbar2TkAgg.__init__(self, chart.canvas, chart.root)
self.chart = chart
# end __init__
try:
toolitems = [tt for tt in NavigationToolbar2TkAgg.toolitems if tt[0] in ('Home', 'Back', 'Forward', 'Pan', 'Zoom')]
toolitems.append(('AutoScale', 'Auto scale the plot', 'hand', 'onAutoScale'))
toolitems.append(('Save', 'Save the plot as PDF', 'filesave', 'onSave'))
except:
pass
# end try
def onAutoScale(self):
self.chart.onAutoScale()
# end onAutoScale
def onSave(self):
self.chart.onSave()
# end onAutoScale
# end NavigationToolbar
except:
pass
import tkFont
# :REV:1:20181115: suppress a nonrelevant warning from matplotlib
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
class OptimizerViewer(Tk.Frame):
""" view the optimization data file in realtime """
def __init__(self, parent, *args, **kwargs):
Tk.Frame.__init__(self, parent, *args, **kwargs)
self.root = parent
xscrollbar = ttk.Scrollbar(self, orient=Tk.HORIZONTAL)
xscrollbar.pack(side=Tk.BOTTOM, fill=Tk.X)
yscrollbar = ttk.Scrollbar(self, orient=Tk.VERTICAL)
yscrollbar.pack(side=Tk.RIGHT, fill=Tk.Y)
# colorize some optimizer specific keywords
self.text = Tk.Text(self, spacing1=2, spacing3=2, wrap='none', selectbackground="#B7DCFF", selectforeground="#000000", inactiveselectbackground="#B7DCFF")
self.boldFont = tkFont.Font(self.text, self.text.cget("font"))
self.boldFont.configure(weight="bold")
self.text.tag_configure("keyword", foreground="#414AF3")
self.text.tag_configure("keyword2", foreground="#41A30B")
self.text.tag_configure("bold", font=self.boldFont)
self.text.tag_configure("selectedline", background="#B7DCFF")
self.text.pack(side=Tk.LEFT, fill="both", expand=1)
self.text['xscrollcommand'] = xscrollbar.set
self.text['yscrollcommand'] = yscrollbar.set
xscrollbar.config(command=self.text.xview)
yscrollbar.config(command=self.text.yview)
self.selectedline = -1
self.count = Tk.IntVar()
self.listKeyword = None
self.listKeyword2 = None
self.text.bind("<1>", lambda event: self.text.focus_set())
self.text.bind('<Button-3>', self.onRightClick, add='')
self.text.bind("<Control-c>", lambda event: self.onCopy())
self.text.bind("<Control-a>", lambda event: self.onSelectAll())
self.text.bind("<Control-s>", lambda event: self.onSave())
# end __init__
def setText(self, strText, listKeyword, listKeyword2):
""" update the viewer colorize the optimizer specific keywords """
try:
self.config(cursor="wait")
self.update()
except:
pass
wfocus = self.text.focus_get()
self.text.config(state=Tk.NORMAL)
try:
self.text.delete("1.0", "end")
except:
pass
# end try
try:
self.text.insert("end", strText)
self.listKeyword = list(listKeyword)
self.listKeyword2 = list(listKeyword2)
if wfocus == self.text:
self.text.focus()
# end if
for strK in self.listKeyword:
self.colorize(strK, "keyword", "bold")
# end for
for strK in self.listKeyword2:
self.colorize(strK, "keyword2", "bold")
# end for
except:
pass
# end try
self.text.config(state=Tk.DISABLED)
self.config(cursor="")
# end setText
def colorize(self, keyword, taga, tagb):
start = self.text.index("1.0")
end = self.text.index("end")
self.text.mark_set("matchStart", start)
self.text.mark_set("matchEnd", start)
self.text.mark_set("searchEnd", end)
while True:
index = self.text.search(keyword, "matchEnd","searchEnd", count=self.count)
if (index == "") or (self.count.get() == 0):
break
# end while
self.text.mark_set("matchStart", index)
self.text.mark_set("matchEnd", "%s+%dc" % (index, self.count.get()))
self.text.tag_add(taga, "matchStart", "matchEnd")
self.text.tag_add(tagb, "matchStart", "matchEnd")
# end while
# end colorize
def onSelectAll(self):
self.text.tag_add(Tk.SEL, "1.0", Tk.END)
self.text.mark_set(Tk.INSERT, "1.0")
self.text.see(Tk.INSERT)
return 'break'
# end onCopy
# offset corresponds to the data file header and non-numeric part
def selectLine(self, index, offset = 12):
index += offset
if self.selectedline >= 0:
self.text.tag_remove("selectedline", "%d.0" % (1 + self.selectedline), "%d.end" % (1 + self.selectedline))
# end if
self.text.tag_add("selectedline", "%d.0" % (1 + index), "%d.end" % (1 + index))
self.selectedline = index
# end onCopy
def onCopy(self):
self.text.clipboard_clear()
strC = self.text.get("sel.first", "sel.last")
self.text.clipboard_append(strC)
return 'break'
# end onCopy
def onRightClick(self, event):
popmenu = Tk.Menu(None, tearoff=0)
popmenu.add_command(label='Select All', command=self.onSelectAll)
if self.text.tag_ranges("sel"):
popmenu.add_command(label='Copy', command=self.onCopy)
# end if
popmenu.add_separator()
popmenu.add_command(label='Save', command=self.onSave)
popmenu.add_separator()
popmenu.add_command(label='Close', command=self.onClose)
popmenu.tk_popup(event.x_root, event.y_root, 0)
return "break"
# end onRightClick
def onSave(self):
fileopt = {}
fileopt['defaultextension'] = '.txt'
fileopt['filetypes'] = [('Text files', '.txt')]
fileopt['initialfile'] = ''
fileopt['parent'] = self.root
fileopt['title'] = 'Save data'
dataFilename = tkFileDialog.asksaveasfilename(**fileopt)
if dataFilename:
try:
fileT = open(dataFilename, "w")
fileT.write(self.text.get(1.0, Tk.END))
fileT.close()
except:
pass
# end try
# end if
# end onRestart
# end OptimizerViewer
class OptimizerThread(threading.Thread):
def __init__(self, id, func):
threading.Thread.__init__(self)
self.id = id
self.func = func
# end __init__
def run(self):
self.func()
# end run
# end OptimizerThread
class OptimizerReport(Tk.Frame):
def __init__(self, owner, index, report, *args, **kwargs):
Tk.Frame.__init__(self, report, *args, **kwargs)
self.listParam = list()
self.listOptim = list()
self.listOptimout = list()
self.count = 0
self.fontsize = 10
self.index = index
self.owner = owner
self.root = report
self.figure = matplotlib.figure.Figure(figsize=(8,5), dpi=100, facecolor='#F1F1F1', linewidth=1.0, frameon=True)
self.figure.subplots_adjust(top = 0.95, bottom = 0.12, left = 0.09, right = 0.95, wspace = 0.0, hspace = 0.1)
self.plot = self.figure.add_subplot(111)
self.plot.set_xlabel("$\mathregular{Voltage\ (V)}$" if (self.index == 0) else "$\mathregular{Wavelength\ (\mu m)}$", fontsize=self.fontsize)
self.plot.set_ylabel("$\mathregular{Current\ (mA/cm^{2})}$" if (self.index == 0) else "$\mathregular{EQE}$", fontsize=self.fontsize)
self.plot.format_coord = self.formatCoord
try:
self.plot.tick_params(axis='x', labelsize=self.fontsize)
self.plot.tick_params(axis='y', labelsize=self.fontsize)
except:
[tx.label.set_fontsize(self.fontsize) for tx in self.plot.xaxis.get_major_ticks()]
[ty.label.set_fontsize(self.fontsize) for ty in self.plot.yaxis.get_major_ticks()]
pass
try:
if self.index == 0:
self.plot.axhline(0.0, linestyle='-', linewidth=2, color='g', zorder=3)
self.plot.axvline(0.0, linestyle='-', linewidth=2, color='g', zorder=3)
else:
self.plot.axhline(1.0, linestyle='-', linewidth=2, color='g', zorder=3)
# end if
self.plot.xaxis.major.locator.set_params(nbins=10)
self.plot.yaxis.major.locator.set_params(nbins=5)
self.plot.grid(True)
except:
pass
self.plot.mlinex = None
self.plot.mliney = None
self.indexm = 0
self.currentsign = 1.0
paramFrame = Tk.Frame(self.root)
paramFrame.pack(fill=Tk.X, padx=5, pady=5)
self.paramlistBox = ttk.Combobox(paramFrame, state='readonly')
self.paramlistBox.pack(side=Tk.LEFT, padx=(5, 5), fill=Tk.X, expand=1)
self.paramlistBox['state'] = 'readonly'
self.paramlistBox.bind('<<ComboboxSelected>>', self.onParamlistBox)
self.paramlistCurrent = 0
self.canvas = FigureCanvasTkAgg(self.figure, master=self.root)
self.canvas._tkcanvas.config(highlightthickness=0)
try:
self.toolbar = NavigationToolbar(self)
except:
self.toolbar = None
pass
self.toolbar.pack(side=Tk.BOTTOM, fill=Tk.X)
self.toolbar.update()
self.canvas._tkcanvas.pack(side=Tk.LEFT, fill=Tk.BOTH, expand=1)
self.canvas.show()
self.linecolor = 'b'
self.linecolorm = '#FF7F00'
self.linestyle = '-'
self.linesize = 2.0
self.markersm = 'o'
self.markerhg = 'None'
self.markersizesm = 6.0
self.markersizehg = 3.0
self.line = None
self.dataSep = ' '
self.datax = list()
self.datay = list()
self.root.bind('<Button-3>', self.onRightClick, add='')
self.root.bind("<Control-s>", lambda event: self.onSave())
self.root.bind("<Prior>", self.onPageDown)
self.root.bind("<Next>", self.onPageUp)
# end __init__
def reset(self, listParam, listOptim, listOptimout, listFileContent):
if (listParam is None) or (listOptim is None) or (listOptimout is None):
return False
# end if
del self.listParam[:]
self.listParam = list(listParam)
del self.listOptim[:]
self.listOptim = list(listOptim)
del self.listOptimout[:]
self.listOptimout = list(listOptimout)
if self.count > 0:
for ida in range(0, self.count):
self.datax[ida] = np.delete(self.datax[ida], np.s_[:])
self.datay[ida] = np.delete(self.datay[ida], np.s_[:])
# end for
del self.datax[:]
self.datax = list()
del self.datay[:]
self.datay = list()
# end if
self.count = 0
dataValid = self.isDataValid(listFileContent)
if dataValid:
self.paramlistBox['values'] = self.listParam
self.paramlistBox.set(self.listParam[self.count - 1])
self.paramlistCurrent = self.paramlistBox.current()
# end if
return dataValid
# end reset
def isDataValid(self, listFileContent = None):
try:
iParamLen = len(self.listParam)
if iParamLen < 1:
return False
# end if
if listFileContent is not None:
iFcontentLen = len(listFileContent)
if (iFcontentLen < 1) or (iParamLen != iFcontentLen):
return False
# end if
# end if
self.count = iParamLen
except:
return False
# end try
return True
# end isDataValid
def formatCoord(self, x, y):
return ('Voltage: %08.5f V ; Current: %09.5f mA/cm²' if (self.index == 0) else 'Wavelength: %8.5f µm ; EQE: %8.5f') % (x, y)
# end formatCoord
def onPageMove(self, event, idir):
if self.owner.isRunning():
return
# end if
try:
indexT = self.paramlistBox.current() + idir
indexMax = len(self.paramlistBox["values"])
if (indexT < 0) or (indexT >= indexMax):
return
# end if
self.updatePlot(index = indexT)
self.paramlistBox.current(newindex = indexT)
if (self.owner is not None):
self.owner.updateSel(index = indexT)
self.owner.paramlistBox.current(newindex = indexT)
# end if
self.paramlistCurrent = self.paramlistBox.current()
except:
pass
# end onPageDown
def onPageDown(self, event):
return self.onPageMove(event, -1)
# end onPageDown
def onPageUp(self, event):
return self.onPageMove(event, 1)
# end onPageUp
def updatePlot(self, index = None, autoscale = False):
if (index is None) or (index < 0) or (index >= self.count):
index = self.count - 1
# end if
try:
if self.line is None:
self.line, = self.plot.plot(self.datax[index], self.datay[index], self.linestyle, linewidth=self.linesize, zorder=4)
self.line.set_markerfacecolor(self.linecolor)
self.line.set_markeredgecolor(self.linecolor)
else:
self.line.set_xdata(self.datax[index])
self.line.set_ydata(self.datay[index])
# end if
strTX = ""
try:
strTX = self.listOptim[index]
except:
pass
self.line.set_color(self.linecolorm if (self.indexm == index) else self.linecolor)
self.plot.set_title(strTX, fontsize=self.fontsize)
self.line.set_marker(self.markerhg if (len(self.datax[index]) > 20) else self.markersm)
self.line.set_markersize(self.markersizehg if (len(self.datax[index]) > 20) else self.markersizesm)
if (self.index == 0):
(Jm, Vm, FF, Jsc, Voc, Eff) = self.listOptimout[index]
if (self.plot.mlinex is not None):
self.plot.mlinex.remove()
# end if
if (self.plot.mliney is not None):
self.plot.mliney.remove()
# end if
self.plot.mlinex = self.plot.hlines(y=Jm * self.currentsign, xmin=0.0, xmax=Vm, linewidth=1, colors='g', linestyles='dashed', zorder=4)
self.plot.mliney = self.plot.vlines(x=Vm, ymin=Jm * self.currentsign, ymax=0.0, linewidth=1, colors='g', linestyles='dashed', zorder=4)
# end if
# end if
if autoscale:
self.plot.relim()
self.plot.autoscale()
if (self.index == 1):
ylim = self.plot.get_ylim()
self.plot.set_ylim([0.0, ylim[1]])
# end if
# end if
self.canvas.draw()
except:
pass
# end try
# end updatePlot
def setParam(self, listParam, listOptim, listOptimout, listFileContent):
if not self.reset(listParam, listOptim, listOptimout, listFileContent):
tkMessageBox.showwarning("SLALOM", "Report data not valid", parent=self.root)
return
# end if
try:
self.config(cursor="wait")
self.update()
except:
pass
arrLine = list()
try:
(Jmr, Vmr, FFr, Jscr, Vocr, Effr) = (0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
self.indexm = self.count - 1
linestoskip = 8
prevPoints = 0
for ida in range(0, self.count):
(Jm, Vm, FF, Jsc, Voc, Eff) = self.listOptimout[ida]
if (Eff > Effr):
(Jmr, Vmr, FFr, Jscr, Vocr, Effr) = (Jm, Vm, FF, Jsc, Voc, Eff)
self.indexm = ida
# end if
arrLine = listFileContent[ida].split("\n")
arrlen = len(arrLine)
if (arrlen <= linestoskip):
break
# end if
self.datax.append(np.array([]))
self.datay.append(np.array([]))
xprev = None
xval = 0.0
yval = 0.0
curPoints = 0
for ii in range(linestoskip, arrlen):
tLine = arrLine[ii].replace("\r", "").replace("\n", "").split(self.dataSep)
dlen = len(tLine)
if dlen != 2:
break
# end if
try:
xval = float(tLine[0])
yval = float(tLine[1])
except:
pass
if xprev is None:
xprev = xval
elif xval > xprev:
# :REV:1:20181115: keep only (voltage or wavelength) that are monotically increasing
# but do not break (sometimes the simulator saves the same point)
self.datax[ida] = np.append(self.datax[ida], xval)
self.datay[ida] = np.append(self.datay[ida], yval)
xprev = xval
curPoints += 1
# end if
# end for
if ida == 0:
prevPoints = curPoints
elif (curPoints < 3):
tkMessageBox.showwarning("SLALOM", "Report data not valid (number of points: %d)" % curPoints, parent=self.root)
return
# end if
self.currentsign = 1.0 if (self.datay[ida][0] > 0.0) else -1.0
del arrLine[:]
arrLine = list()
# end for
self.updatePlot(index = self.indexm, autoscale = True)
except:
tkMessageBox.showwarning("SLALOM", "Report data not valid", parent=self.root)
return
self.config(cursor="")
# end setParam
def onParamlistBox(self, event):
if self.owner.isRunning():
self.paramlistBox.current(newindex = self.paramlistCurrent)
return
# end if
try:
self.paramlistBox.selection_clear()
indexT = self.paramlistBox.current()
self.updateSel(index = indexT)
if (self.owner is not None):
self.owner.updateSel(index = indexT)
self.owner.paramlistBox.current(newindex = indexT)
for ii in range(0, len(self.owner.report)):
if (self.owner.report[ii] is not None) and (ii != self.index):
self.owner.report[ii].frame.paramlistBox.current(newindex = indexT)
self.owner.report[ii].frame.updateSel(index = self.owner.report[ii].frame.paramlistBox.current())
# end if
# end for
if (self.owner.viewer is not None):
self.owner.viewer.frame.selectLine(index = indexT)
# end if
# end if
self.paramlistCurrent = indexT
except:
pass
# end try
# end onParamlistBox
def updateSel(self, index=None):
if not self.isDataValid():
tkMessageBox.showwarning("SLALOM", "Report data not valid", parent=self.root)
return
# end if
if (index is None) or (index < 0) or (index >= self.count):
index = self.count - 1
# end if
self.updatePlot(index)
# end updateSel
def onRightClick(self, event):
if self.owner.isRunning():
return
# end if
popmenu = Tk.Menu(None, tearoff=0)
popmenu.add_command(label='Auto scale', command=self.onAutoScale)
popmenu.add_command(label='Save as PDF', command=self.onSave)
popmenu.add_separator()
popmenu.add_command(label='Close', command=self.onClose)
popmenu.tk_popup(event.x_root, event.y_root, 0)
return "break"
# end onRightClick
def onAutoScale(self):
if self.owner.isRunning():
return
# end if
for ida in range(0, self.count):
curPoints = len(self.datax[ida])
if (curPoints < 4):
tkMessageBox.showwarning("SLALOM", "Report data not valid (number of points: %d)" % curPoints, parent=self.root)
return
# end if
# end for
if (self.plot is not None) and (self.count > 0):
self.plot.relim()
self.plot.autoscale()
if (self.index == 1):
ylim = self.plot.get_ylim()
self.plot.set_ylim([0.0, ylim[1]])
# end if
self.canvas.draw()
# end if
# end onAutoScale
def onSave(self):
if self.owner.isRunning():
return
# end if
fileopt = {}
fileopt['defaultextension'] = '.pdf'
fileopt['filetypes'] = [('PDF files', '.pdf')]
fileopt['initialfile'] = ''
fileopt['parent'] = self.root
fileopt['title'] = 'Save figure'
dataFilename = tkFileDialog.asksaveasfilename(**fileopt)
if dataFilename:
try:
pdfT = PdfPages(dataFilename)
pdfT.savefig(self.figure)
pdfT.close()
except:
pass
# end try
# end if
# end onSave
# end OptimizerReport
# slalomWindow class, the main monitor window
class slalomWindow(object):
""" main monitor window """
def __init__(self, dataFilename, remoteHost = None, simulator = "atlas"):
self.__version__ = slalomVersion
self.deviceSimulator = simulator
xIndex = 0
y1Index = 0
y2Index = 0
y3Index = 0
xLabel = None
y1Label = None
y2Label = None
y3Label = None
xType = 'int'
dataSep = '\t'
updateDelay = 30
# in seconds
self.updateDelay = 30
self.delayMin = 30
self.delayMax = 7200
self.startTime = 0
self.updateTime = 0
self.updateCount = 0
self.updateDelayMin = 0
self.updateDelayMax = 0
self.updateDelayMean = 0
self.filemtime = 0
self.fontsize = 10
self.dataSep = dataSep
self.count = 3
self.datax = np.array([])
self.dataxSel = np.array([])
self.datay = {}
self.dataySel = {}
for idy in range(0, self.count):
self.datay[idy] = np.array([])
self.dataySel[idy] = np.array([])
# end for
self.xLabel = xLabel
self.yLabel = {}
self.yLabel[0] = y1Label if (y1Label is not None) else '$\mathregular{J_{SC}\ (mA/cm^{2})}$'
self.yLabel[1] = y2Label if (y2Label is not None) else '$\mathregular{V_{OC}\ (V)}$'
self.yLabel[2] = y3Label if (y3Label is not None) else '$\mathregular{Efficiency\ (\%)}$'
self.xType = xType
self.xIndex = xIndex if ((xIndex >= -1) and (xIndex <= 16)) else 0
self.yIndex = [0, 0, 0]
self.yIndex[0] = y1Index if ((y1Index >= 0) and (y1Index <= 16)) else 0
self.yIndex[1] = y2Index if ((y2Index >= 0) and (y2Index <= 16)) else 0
self.yIndex[2] = y3Index if ((y3Index >= 0) and (y3Index <= 16)) else 0
self.root = Tk.Tk()
self.root.bind_class("Entry","<Control-a>", self.onEntrySelectAll)
self.root.bind_class("Entry","<Control-z>", self.onEntryUndo)
self.root.bind_class("Entry","<Control-y>", self.onEntryRedo)
self.root.withdraw()
self.root.wm_title("SLALOM")
self.figure = matplotlib.figure.Figure(figsize=(8,6), dpi=100, facecolor='#F1F1F1', linewidth=1.0, frameon=True)
self.figure.subplots_adjust(top = 0.9, bottom = 0.1, left = 0.09, right = 0.95, wspace = 0.0, hspace = 0.25)
self.plot = {}
self.plot[0] = self.figure.add_subplot(311)
self.plot[1] = self.figure.add_subplot(312, sharex=self.plot[0])
self.plot[2] = self.figure.add_subplot(313, sharex=self.plot[0])
for idy in range(0, self.count):
self.plot[idy].format_coord = self.formatCoord
# end for
self.dataFilename = None
self.dataDir = None
self.dataZip = None
self.dataFilenameLocal = None
self.dataDirLocal = None
self.dataZipLocal = None
self.dataShortPath = None
self.remoteHost = None
self.threadrunning = False
self.threadfinish = None
self.thread = None
self.killproc = 0
self.iPoints = 0
self.remoteHostEnabled = True
self.updateDelayAuto = True
# load the last used data filename, ssh host and update delay...
# ... only loaded if no parameter is given as a command line argument
if dataFilename is None:
try:
fileT = open("Settings/slalomMonitor.params", "r")
# maximum number of line to read
iMaxLine = 12
iMaxParam = 5
iLine = 0
iParam = 0
for lineT in fileT:
lineT = lineT.rstrip("\r\n")
if lineT.startswith("dataFilename = "):
dataFilename = lineT[len("dataFilename = "):]
if not dataFilename:
dataFilename = None
iParam += 1
elif lineT.startswith("remoteHost = ") and (remoteHost is None):
remoteHost = lineT[len("remoteHost = "):]
if not remoteHost:
remoteHost = None
iParam += 1
elif lineT.startswith("remoteHostEnabled = "):
try:
self.remoteHostEnabled = int(lineT[len("remoteHostEnabled = "):]) == 1
except:
self.remoteHostEnabled = False
iParam += 1
elif lineT.startswith("updateDelay = "):
updateDelay = lineT[len("updateDelay = "):]
if not updateDelay:
updateDelay = None
iParam += 1
elif lineT.startswith("updateDelayAuto = "):
try:
self.updateDelayAuto = int(lineT[len("updateDelayAuto = "):]) == 1
except:
self.updateDelayAuto = False
iParam += 1
# end if
iLine += 1
if (iLine >= iMaxLine) or (iParam >= iMaxParam):
break
# end for
fileT.close()
except:
pass
# end if
if remoteHost is None:
self.remoteHostEnabled = False
# end if
topFrame = Tk.Frame(self.root)
topFrame.pack(fill=Tk.X, padx=5, pady=5)
self.dataFilenameLabel = Tk.Label(topFrame, width=10, text="Filename: ")
self.dataFilenameLabel.pack(side=Tk.LEFT)
dataFilenameValidate = (topFrame.register(self.onDataFilenameValidate), '%P')
self.dataFilenameEdit = Tk.Entry(topFrame, validate="key", vcmd=dataFilenameValidate)
self.dataFilenameEdit.pack(side=Tk.LEFT, fill=Tk.X, expand=1)
self.dataFilenameEdit.insert(0, dataFilename if (dataFilename is not None) else "")
self.dataFilenameEdit.prev = None
self.dataFilenameEdit.next = None
self.dataFilenameBrowse = ttk.Button(topFrame, width=4, text="...", command=self.onBrowse)
self.dataFilenameBrowse.pack(side=Tk.LEFT, padx=(2, 2))
self.sepLabel1 = Tk.Label(topFrame, text="|")
self.sepLabel1.pack(side=Tk.LEFT)
self.remoteHostLabel = Tk.Label(topFrame, text="SSH: ")
self.remoteHostLabel.pack(side=Tk.LEFT)
remoteHostValidate = (topFrame.register(self.onRemoteHostValidate), '%P')
self.remoteHostEdit = Tk.Entry(topFrame, width=22, validate="key", vcmd=remoteHostValidate)
self.remoteHostEdit.pack(side=Tk.LEFT)
self.remoteHostEdit.insert(0, remoteHost if (remoteHost is not None) else "")
self.remoteHostEdit.prev = None
self.remoteHostEdit.next = None
self.remoteHostVar = Tk.BooleanVar()
self.remoteHostOpt = Tk.Checkbutton(topFrame, text="", variable=self.remoteHostVar, command=self.onRemoteHostOpt)
self.remoteHostOpt.pack(side=Tk.LEFT)
if self.remoteHostEnabled:
self.remoteHostOpt.select()
# end if
self.buttonbar = Tk.Frame(self.root)
self.buttonbar.pack(fill=Tk.X, padx=5, pady=5)
self.updateDelayLabel = Tk.Label(self.buttonbar, width=10, text="Delay(s): ")
self.updateDelayLabel.pack(side=Tk.LEFT)
updateDelayValidate = (self.buttonbar.register(self.onDelayValidate), '%P')
self.updateDelayEdit = Tk.Entry(self.buttonbar, width=6, validate="key", vcmd=updateDelayValidate)
self.updateDelayEdit.pack(side=Tk.LEFT)
self.updateDelayEdit.insert(0, updateDelay if (updateDelay is not None) else "30")
self.updateDelayEdit.prev = None
self.updateDelayEdit.next = None
self.updateDelayVar = Tk.BooleanVar()
self.updateDelayOpt = Tk.Checkbutton(self.buttonbar, text="Auto", variable=self.updateDelayVar, command=self.onUpdateDelayOpt)
self.updateDelayOpt.pack(side=Tk.LEFT, padx=(0, 5))
if self.updateDelayAuto:
self.updateDelayOpt.select()
# end if
self.updateProgressVar = Tk.IntVar()
self.updateProgress = ttk.Progressbar(self.buttonbar, length=120, orient='horizontal', mode='determinate', variable=self.updateProgressVar, maximum=(int(updateDelay) + 1) if (updateDelay is not None) else 31)
self.updateProgress.pack(side=Tk.LEFT, padx=(0, 5))
self.updateProgress.stopping = 0
self.updateProgress.stoppingtime = None
self.updateProgress.stopped = 0
self.updateProgress.stoppedtime = None
self.updateProgress.waiting = 0
self.sepLabel2 = Tk.Label(self.buttonbar, text="|")
self.sepLabel2.pack(side=Tk.LEFT)
self.btnstyle_red = ttk.Style()
self.btnstyle_red.configure("Red.TButton", foreground="#DE0015")
self.btnstyle_black = ttk.Style()
self.btnstyle_black.configure("Black.TButton", foreground="black")
iconStart = Tk.PhotoImage(file='Images/iconstart.gif')
self.btnStart = ttk.Button(self.buttonbar, width=10, text="Start", image=iconStart, compound=Tk.LEFT, command=self.onRestart)
self.btnStart.pack(side=Tk.LEFT, padx=(5, 5))
self.btnStart.configure(style="Black.TButton")
iconStop = Tk.PhotoImage(file='Images/iconstop.gif')
self.btnStop = ttk.Button(self.buttonbar, width=10, text="Stop", image=iconStop, compound=Tk.LEFT, command=self.onStop)
self.btnStop.pack(side=Tk.LEFT, padx=(2, 5))
self.btnStop.configure(style="Black.TButton")
iconView = Tk.PhotoImage(file='Images/iconview.gif')
self.btnView = ttk.Button(self.buttonbar, width=10, text="View data", image=iconView, compound=Tk.LEFT, command=self.onView)
self.btnView.pack(side=Tk.LEFT, padx=(2, 5))
self.btnView.configure(style="Black.TButton")
iconReport = Tk.PhotoImage(file='Images/iconreport.gif')
self.btnReport = ttk.Button(self.buttonbar, width=10, text="View JV", image=iconReport, compound=Tk.LEFT, command=self.onShowReport)
self.btnReport.pack(side=Tk.LEFT, padx=(2, 5))
self.btnReport.configure(style="Black.TButton")
iconReportb = Tk.PhotoImage(file='Images/iconreportb.gif')
self.btnReportb = ttk.Button(self.buttonbar, width=10, text="View SR", image=iconReportb, compound=Tk.LEFT, command=self.onShowReportb)
self.btnReportb.pack(side=Tk.LEFT, padx=(2, 5))
self.btnReportb.configure(style="Black.TButton")
self.actionbutton = None
self.timercount = 0.0
self.timerdelay = 500 # milliseconds
self.timerProgressVar = Tk.StringVar()
self.timerProgress = Tk.Label(self.buttonbar, text=" ", textvariable=self.timerProgressVar)
self.timerProgress.pack(side=Tk.LEFT, padx=(2, 0))
self.labelFill = Tk.Label(self.buttonbar, text=" ")
self.labelFill.pack(side=Tk.LEFT, fill=Tk.X, expand=1)
self.btnClose = ttk.Button(self.buttonbar, width=10, text="Close", image=None, command=self.onClose)
self.btnClose.pack(side=Tk.LEFT, padx=(0, 5))
self.btnClose.configure(style="Black.TButton")
iconAbout = Tk.PhotoImage(file='Images/iconabout.gif')
self.btnAbout = ttk.Button(self.buttonbar, width=3, text="", image=iconAbout, command=self.onAbout)