-
Notifications
You must be signed in to change notification settings - Fork 0
/
slalomCore.py
2391 lines (2028 loc) · 91.4 KB
/
slalomCore.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: slalomCore.py
# Type: Class
# Use: slalomCore is used throw the included slalom.py startup module
# To extend the slalomCore class, do not modify it directly but extend it by...
# ...creating a new inherited class. Here, perform only performance tuning and bug fixing.
# ------------------------------------------------------------------------------------------------------
slalomVersion = 'Version: 1.2 Build: 2105'
# Calculation
import math
import numpy as np
from scipy import optimize, interpolate, signal
from Bayes import BayesianOptimization
from Bayes import UtilityFunction
import random
# Control
import subprocess
import datetime, shutil, os, stat, sys, time
import zipfile
import traceback
import itertools
from slalomSimulator import *
def dispError(message, doExit = True, atExit = None, errFilename = None, **atExitArgs):
""" print out an error message and exit if doExit set to True """
try:
if doExit:
strT = "\n--------------------------- ERROR: ----------------------------\n"
else:
strT = "\n-------------------------- WARNING: ---------------------------\n"
# end if
strT += message
if not message.endswith("\n"):
strT += "\n"
# end if
strT += "---------------------------------------------------------------\n"
print(strT)
if doExit == False:
return
# end if
if atExit is not None:
atExit(atExitArgs)
# end if
if errFilename is not None:
fileErr = open(errFilename, 'w')
fileErr.write(message)
fileErr.close()
# end if
finally:
if doExit:
# sys.exit raise SystemExit (inherits from BaseException)
sys.exit(1)
# end if
# end try
# end dispError
class slalomCore(object):
""" the SLALOM core class """
def __init__(self, Device = None, pythonInterpreter = None, deviceSimulator = "atlas"):
""" slalomCore constructor """
self.__version__ = slalomVersion
self.pythonInterpreter = "python"
self.simulator = slalomSimulator(name = deviceSimulator)
self.optimType = ""
self.isRunning = False
self.isParamUpdated = False
self.isInputChecked = False
self.optimType = ""
self.minimizeMethodList = ["L-BFGS-B", "SLSQP", "Bayes"]
self.minimizeMethod = "Bayes"
self.maxIter = 100
self.isBound = True
self.tolerance = 1e-3
self.ftolerance = 0.005
self.jaceps = np.array([])
# Optimization cache
self.lastParam = list()
self.lastOutput = list()
self.lastParamLimit = 12
self.mainTitle = ""
self.pythonInterpreter = ""
self.inputFilename = ""
self.paramCount = 0
self.paramName = []
self.paramFormat = []
self.paramFormatShort = []
self.paramFormatNormalized = []
self.paramNorm = np.array([])
self.paramStart = np.array([])
self.paramEnd = np.array([])
self.paramInit = np.array([])
self.paramPoints = []
self.paramBounds = None
# Tukey Window (Parameters Weight: decreases near the bounds)
# If optimum is near the bounds, disable this feature or enlarge domain
self.paramWeight = False
self.weightFunc = None
self.weightAlpha = 0.20
self.weightPoints = 101
# optimPoints is used to approximate the jacobian. If increased, the optimisation time will dramatically increase. The default value is 51 and the maximum value is 201.
self.optimPoints = 51
self.paramLogscale = []
self.modelFilename = None
self.paramOptim = np.array([])
self.paramNatural = np.array([])
self.paramCountTotal = 0
self.paramFormatOutput = ""
self.outputOptimized = 0.0
self.outputOptimizedx = 0.0
self.outputOptimizedy = 0.0
self.outputOptimizedz = 0.0
self.optimCounter = 1
self.funcCounter = 1
self.jacCounter = 0
self.elapsedTime = 0
self.delayMin = 0
self.delayMax = 0
self.delayMean = 0
self.counterFormat = '{0:02d}'
self.guessParam = False
self.bruteSimul = False
self.inJac = False
# output filenames:
# * these names should be the same than the simulator output filenames
# * for the following three files, the position should be kept the same:
# * >> second file (position 1) = J(V) from V = 0 to V = VOC
# * >> before last file (position 6) = efficiency calculated by simulator
# * >> last file (position 7) = J(V) (for efficiency calculation)
# * the output file names remain unchanged since at every
# optimization a new output directory is created
self.outputFilename = [ "simuloutput_all.log",
"simuloutput_jvp.log",
"simuloutput_pv.log",
"simuloutput.log",
"simuloutput_spectralresponse_eqe.log",
"simuloutput_popt.log",
"simuloutput_efficiency.log",
"simuloutput_jv.log" ]
self.outputFilenameJVPposition = 1
self.outputFilenameEFFposition = 6
self.outputFilenameJVposition = 7
# output filenames description (each output file should have a description)
self.outputComment = [ "Voltage Sweep Data",
"J(V) Characteristic from 0V to VOC (J in mA/cm2)",
"P(V) Characteristic (P in mW/cm2)",
"PV Performances Data (JSC (mA/cm2), VOC (V), FF, EFF)",
"External quantum efficiency",
"Optical Power (in mW/cm2)",
"PV Efficiency",
"J(V) Characteristic (J in mA/cm2)" ]
self.outputCount = len(self.outputComment)
# pipe filename (used for the simulator standard output redirection)
self.verboseFilename = "simuloutput_stdout.txt"
# log filename: used for the internal optimizer logging
self.logFilename = "simuloutput_log.txt"
# weight filename: not used yet
self.weightFilename = "simuloutput_weight.txt"
# log filename:
# * contain the calculated efficiency at every optimization step along with
# the corresponding set of parameters
self.outputOptimizedFilename = "simuloutput_optimized.txt"
self.commandFilename = "Optimize.bat" if (os.name == "nt") else "Optimize.sh"
# internal filenames
self.stopFilename = "stop.txt"
self.stoppedFilename = "stopped.txt"
self.stoppedDone = False
self.delayFilename = "delay.txt"
self.currentDir = ""
self.outputDir = ""
self.outputRoot = ""
self.outputDirShort = ""
self.dirSepChar = '/'
if (Device is not None) and (pythonInterpreter is not None):
self.setParam(Device, pythonInterpreter)
# end if
return
# end __init__
def log(self, strT):
""" internal logging routine (the significant events are logged in the log file) """
try:
print(strT)
fileT = open(self.outputDir + self.logFilename, "a")
fileT.write(strT)
fileT.close()
except:
pass
# end try
# end log
def setCounterFormat(self, maxcount):
if maxcount < 100:
self.counterFormat = '{0:02d}'
elif maxcount >= 100 and maxcount < 1000:
self.counterFormat = '{0:03d}'
elif maxcount >= 1000 and maxcount < 10000:
self.counterFormat = '{0:04d}'
else:
self.counterFormat = '{0:07d}'
# endif
# end setCounterFormat
def setInterpreter(self, pythonInterpreter):
""" set the Python interpreter (usually just 'python') """
self.pythonInterpreter = pythonInterpreter
# end setInterpreter
@staticmethod
def chmodExec(strFilename):
""" chmod a+x the simulator launcher """
statT = os.stat(strFilename)
os.chmod(strFilename, statT.st_mode | stat.S_IEXEC)
return
# end chmodExec
def checkInput(self):
""" check if the simulator files (input, C models, etc.) can be accessed """
if (self.outputCount > 0):
pathIn = ""
# Check if the simulator input file contains the correct output filenames
try:
pathIn = os.path.join(self.currentDir, self.inputFilename)
if not os.path.isfile(pathIn):
dispError("cannot open input: file not found '%s'" % pathIn,
doExit = True, atExit = self.finish, errFilename = self.currentDir + 'errlog.txt')
# end if
fileT = open("{0}{1}".format(self.currentDir, self.inputFilename), "r")
foundCounter = 0
for lineT in fileT:
for ii in range(0, self.outputCount):
for ll in range(0, len(self.simulator.filedecl)):
statementT = self.simulator.filedecl[ll] % self.outputFilename[ii]
# syntax should be the same than what defined in slalomSimulator
# for Silvaco: outfile=filename (without spaces aroud '=')
if (statementT in lineT):
foundCounter += 1
break
# end if
# end for
# end for
if foundCounter == self.outputCount:
break
# end for
# end for
fileT.close()
if foundCounter != self.outputCount:
dispError("Output statements not found in the simulator input file",
doExit = True, atExit = self.finish, errFilename = self.currentDir + 'errlog.txt')
# end if
except Exception as excT:
# catch only Exception (since sys.exit raise BaseException)
dispError("Cannot open the simulator input file '%s' %s" % (pathIn, str(excT)),
doExit = True, atExit = self.finish, errFilename = self.currentDir + 'errlog.txt')
# end try
# end if
self.isInputChecked = True
return self.isInputChecked
# end checkInput
def updatePath(self, bCreateCommand = True):
""" update/normalize input files """
# Format simulator input file
fileT = open(self.currentDir + self.inputFilename, "r")
fileContent = ""
for lineT in fileT:
# Normalize line ending (Silvaco do not run input file if contains CRLF terminated lines)
lineT = lineT.rstrip("\r\n")
fileContent += (lineT + "\n")
# end for
fileT.close()
fileT = open(self.outputDir + self.inputFilename, "w")
fileT.write(fileContent)
fileT.close()
# Format model files
if self.modelCount > 0:
for ii in range(0, self.modelCount):
if self.modelFilename[ii] == "":
continue
# end if
fileT = open(self.currentDir + self.modelFilename[ii], "r")
fileContent = ""
for lineT in fileT:
# Normalize line ending (Silvaco do not run input file if contains CRLF terminated lines)
lineT = lineT.rstrip("\r\n")
fileContent += (lineT + "\n")
# end for
fileT.close()
fileT = open(self.outputDir + self.modelFilename[ii], "w")
fileT.write(fileContent)
fileT.close()
# end for
# end if
if bCreateCommand == True:
self.simulator.update(self.simulator.name, self.inputFilename, self.currentDir, self.outputDir, self.verboseFilename)
strT = ""
lenT = len(self.simulator.command)
for ii in range(0, lenT):
strT += self.simulator.command[ii]
if (ii < (lenT - 1)):
strT += "\n"
# end if
# end for
fileT = open(self.outputDir + self.commandFilename, "w")
fileT.write(strT)
fileT.close()
# chmod a+x self.commandFilename
self.chmodExec(self.outputDir + self.commandFilename)
# end if
return True
# end updatePath
def isChecked(self):
""" input files successfully checked? """
return (self.isInputChecked and self.isParamUpdated)
# end isChecked
@staticmethod
def printTime(secondsT, short=False):
""" print the time in a readable form """
strT = ""
if (secondsT < 60.0):
strT = ("%02d" % secondsT) + (" seconds" if not short else " s")
elif (secondsT < 3600.0):
strT = ("%.2f" % (secondsT / 60.0)) + (" minutes" if not short else " m")
else:
strT = ("%.2f" % (secondsT / 3600.0)) + (" hours" if not short else " h")
# end if
return strT
# end printTime
def finish(self, errorOccured=True, userStopped=True, x=None, success=None, message=None, nit=None, nlfev=None, xl=None, funl=None):
""" print out results at the optimization end """
try:
dateT = datetime.datetime.now()
dateStr = dateT.strftime("%Y-%m-%d %H:%M:%S")
if errorOccured == False:
strT = "\n---------------------------------------------------------------\n"
strT += ("Optimization ended @ " if (userStopped == False) else "Optimization interrupted @ ") + dateStr
strT += ("\nMAXIMUM Efficiency: %g %%" % self.outputOptimized)
strT += ("\nWITH Jsc = %g mA/cm2" % self.outputOptimizedx) + (" ; Voc = %.4f" % self.outputOptimizedy) + (
" ; FF = %.3f %%" % self.outputOptimizedz) + "\nOBTAINED FOR:\n"
for ii in range(0, self.paramCount - 1):
strT += self.paramName[ii] + "\t"
# end for
strT += self.paramName[self.paramCount - 1] + "\n"
for ii in range(0, self.paramCount - 1):
strT += (self.paramFormat[ii] % self.paramOptim[ii]) + "\t"
# end for
strT += (self.paramFormat[self.paramCount - 1] % self.paramOptim[self.paramCount - 1])
strT += "\nTotal duration: " + self.printTime(float(self.elapsedTime))
strT += ("\nNumber of function evaluations: %d" % self.funcCounter)
if (self.jacCounter >= self.paramCount):
strT += (" (%d for the Jacobian approximation)" % self.jacCounter)
# end if
strT += "\n---------------------------------------------------------------\n"
if (x is not None) and (success is not None) and (message is not None):
xt = np.zeros(self.paramCount)
for ii in range(0, self.paramCount):
if self.paramLogscale[ii]:
xt[ii] = math.pow(10.0, (x[ii] * math.log10(self.paramNorm[ii])))
else:
xt[ii] = x[ii] * self.paramNorm[ii]
# end if
# end for
strT += "\n---------------------------------------------------------------\n"
strT += "Optimization function (" + self.minimizeMethod + ") output:\n"
strT += "Parameter:\t"
for ii in range(0, self.paramCount - 1):
strT += self.paramName[ii] + "\t"
# end for
strT += self.paramName[self.paramCount - 1] + "\n"
strT += "x (natural):\t"
for ii in range(0, self.paramCount - 1):
strT += (self.paramFormat[ii] % xt[ii]) + "\t"
# end for
strT += (self.paramFormat[self.paramCount - 1] % xt[self.paramCount - 1]) + "\n"
strT += "x (normalized):\t"
for ii in range(0, self.paramCount - 1):
strT += (self.paramFormatNormalized[ii] % x[ii]) + "\t"
# end for
strT += (self.paramFormatNormalized[self.paramCount - 1] % x[self.paramCount - 1]) + "\n"
strT += "\nsuccess: " + str(success) + "\n"
strT += "\nmessage: " + str(message) + "\n"
strT += "\nevaluations: " + str(self.funcCounter)
strT += "\n---------------------------------------------------------------\n"
# end if
if (xl is not None) and (funl is not None) and (success is not None) and (message is not None):
nxl = len(xl)
nfunl = len(funl)
if (nxl == nfunl):
if (nxl > 10):
nxl = 10
nfunl = 10
# end if
ll = 0
for xll in xl:
effl = 100.0 * (1.0 - funl[ll])
ll = ll + 1
if (effl < 0.0) or (effl > 90.0):
# should never happen
continue
# end if
xt = np.zeros(self.paramCount)
for ii in range(0, self.paramCount):
if self.paramLogscale[ii]:
xt[ii] = math.pow(10.0, (xll[ii] * math.log10(self.paramNorm[ii])))
else:
xt[ii] = xll[ii] * self.paramNorm[ii]
# end if
# end for
strT += "\n---------------------------------------------------------------\n"
strT += "Optimization function (" + self.minimizeMethod + (") local output #%d:\n" % ll)
strT += "Parameter:\t"
for ii in range(0, self.paramCount - 1):
strT += self.paramName[ii] + "\t"
# end for
strT += self.paramName[self.paramCount - 1] + "\n"
strT += "xl (natural):\t"
for ii in range(0, self.paramCount - 1):
strT += (self.paramFormat[ii] % xt[ii]) + "\t"
# end for
strT += (self.paramFormat[self.paramCount - 1] % xt[self.paramCount - 1]) + "\n"
strT += "xl (normalized):\t"
for ii in range(0, self.paramCount - 1):
strT += (self.paramFormatNormalized[ii] % xll[ii]) + "\t"
# end for
strT += (self.paramFormatNormalized[self.paramCount - 1] % xll[self.paramCount - 1]) + "\n"
strT += "\nefficiency: %06.3f %%" % effl
strT += "\n---------------------------------------------------------------\n"
# end if
# end if
# end if
self.log(strT)
# end if
strLog = ("# Optimization ended @ " if (userStopped == False) else "# Optimization interrupted @ ") + dateStr + "\n"
fileOptim = open(self.outputDir + self.outputOptimizedFilename, "a")
fileOptim.write(strLog)
fileOptim.close()
self.log(strLog)
self.stopSet()
if self.stoppedDone == False:
pathStopped = os.path.join(self.outputDir, self.stoppedFilename)
fileT = open(pathStopped, "w")
fileT.write(strLog)
fileT.close()
self.stoppedDone = True
# end if
self.log("\nZipping optimization result files...")
zipFilename = self.outputRoot + self.outputDirShort + ".zip"
outFile = zipfile.ZipFile(zipFilename, "w", compression=zipfile.ZIP_DEFLATED)
dirToZip = self.outputDir.rstrip(self.dirSepChar)
for (dirPath, dirNames, fileNames) in os.walk(dirToZip):
for fileName in fileNames:
fileAbsolutePath = os.path.join(dirPath, fileName)
fileRelativePath = fileAbsolutePath.replace(dirToZip + self.dirSepChar, '')
outFile.write(fileAbsolutePath, fileRelativePath)
# end for
# end for
outFile.close()
self.log("\nZipping done (File: " + self.outputDirShort + ".zip" + ").")
self.isRunning = False
except:
pass
# end try
self.isRunning = False
if self.stoppedDone == False:
try:
pathStopped = os.path.join(self.outputDir, self.stoppedFilename)
fileT = open(pathStopped, "w")
fileT.write("SLALOM\nStopped\n")
fileT.close()
self.stoppedDone = True
except:
pass
# end try
# end if
sys.exit(0 if (errorOccured == False) else 1)
# end finish
def guess(self):
""" get the initial parameters set """
self.guessParam = True
self.bruteSimul = False
paramNormalized0 = np.zeros(self.paramCount)
for ii in range(0, self.paramCount):
if self.paramLogscale[ii]:
paramNormalized0[ii] = math.log10(self.paramInit[ii]) / math.log10(self.paramNorm[ii])
else:
paramNormalized0[ii] = self.paramInit[ii] / self.paramNorm[ii]
# end if
# end for
self.guessParam = False
return paramNormalized0
# end guess
def isErrorOccurred(self):
""" check if a simulator error has occurred """
maxLines = 16383
curLine = 0
simulatorError = None
try:
pathV = os.path.join(self.outputDir + self.verboseFilename)
if not os.path.isfile(pathV):
return None
# end if
iLines = 0;
fileT = open(self.outputDir + self.verboseFilename, "r")
for lineT in fileT:
if (simulatorError is not None):
simulatorError += lineT + '\n'
iLines += 1
if iLines >= 12:
return simulatorError
# end if
else:
for (name, descr) in self.simulator.error:
if lineT.find(name) != -1:
simulatorError = name + ': ' + descr + '\n'
# end if
# end for
# end if
curLine += 1
if curLine >= maxLines:
return simulatorError
# end if
# end for
fileT.close()
except:
pass
# end try
return simulatorError
# end isErrorOccurred
def printOutput(self):
""" print out the simulator output """
maxLines = 16383
curLine = 0
try:
pathV = os.path.join(self.outputDir + self.verboseFilename)
if not os.path.isfile(pathV):
return
# end if
fileT = open(self.outputDir + self.verboseFilename, "r")
strT = "\n# ---------------------- SIMULATOR OUTPUT: ----------------------\n\n"
print(strT)
for lineT in fileT:
strT += "# " + lineT
print(lineT)
curLine += 1
if curLine >= maxLines:
strT += "\n# SIMULATOR OUTPUT TOO LONG\n"
break
# end if
# end for
fileT.close()
strTT = "\n\n# ---------------------------------------------------------------\n"
print(strTT)
strT += strTT
except:
strT = "\n# ----------------------- SIMULATOR ERROR: -----------------------\n"
strT += "# Check the simulator output for details.\n"
strT += "\n# ---------------------------------------------------------------\n"
pass
# end try
return strT
# end printOutput
def stopSet(self):
""" check is the user has required the optimization to stop """
isStopSet = False
pathStop = os.path.join(self.outputDir, self.stopFilename)
try:
if os.path.isfile(pathStop):
isStopSet = True
shutil.move(self.outputDir + self.stopFilename, self.outputDir + "_" + self.stopFilename)
# end if
if isStopSet:
pathOf = os.path.join(self.currentDir, "ofname.txt")
if os.path.isfile(pathOf):
os.unlink(pathOf)
# end if
# end if
except:
pass
# end try
return isStopSet
# end stopSet
def getOptimizeJac(self, optimFunc):
""" Construct the Jacobian approximation function. Adapted from the SLSQSP code source (scipy/optimize/slsqp.py) """
def optimizeJac(x, *args):
x0 = np.asfarray(x)
self.inJac = False
f0 = np.atleast_1d(optimFunc(*((x0,)+args)))
self.inJac = True
ixcount = len(x0)
ifcount = len(f0)
jac = np.zeros([ixcount, ifcount])
dx = np.zeros(ixcount)
for ii in range(ixcount):
self.log("\nJacobian approximation [%d / %d]..." % (ii + 1, ixcount))
dx[ii] = self.jaceps[ii]
jac[ii] = (optimFunc(*((x0+dx,)+args)) - f0) / self.jaceps[ii]
dx[ii] = 0.0
# end for
self.jacCounter += ixcount
self.inJac = False
return jac.transpose()
# end optimizeJac
return optimizeJac
# end getOptimizeJac
def getWeight(self, paramIndex, paramNormalized):
""" weight/cost function for future use (giving each parameter a weight...) """
if (self.paramWeight == False) or (self.weightFunc is None) or (self.paramBounds is None) or (paramIndex < 0) or (paramIndex >= self.paramCount):
return 1.0
# end if
icw = len(self.weightFunc)
if (icw < 7):
return 1.0
# end if
(paramMin, paramMax) = self.paramBounds[paramIndex]
if (paramMax <= paramMin) or (paramNormalized < paramMin) or (paramNormalized > paramMax):
return 0.0
# end if
tdw = (paramMax - paramMin)
idx = int(((paramNormalized - paramMin) * float(icw)) / tdw)
if (idx < 0):
idx = 0
elif (idx >= icw):
idx = icw - 1
# end if
return self.weightFunc[idx]
# end if
def optimizeFuncBayesian(self, **paramNormalizedBayesian):
""" the optimizer maximization function for the Bayesian method """
paramCount = len(paramNormalizedBayesian)
if (self.paramCount != paramCount):
# should never happen
try:
self.finish(errorOccured=True, userStopped=True)
except:
self.isRunning = False
sys.exit(1)
# end try
return 0.0
# end if
paramNormalized = np.zeros(self.paramCount)
for paramT in paramNormalizedBayesian:
for ii in range(0, self.paramCount):
if (self.paramName[ii] == paramT):
paramNormalized[ii] = float(paramNormalizedBayesian[paramT])
break
# end if
# end for
# end for
return self.optimizeFunc(paramNormalized)
# end optimizeFuncBayesian
def optimizeFunc(self, paramNormalized):
""" the optimizer minimization function """
paramCount = len(paramNormalized)
if (self.paramCount != paramCount):
# should never happen
try:
self.finish(errorOccured=True, userStopped=True)
except:
self.isRunning = False
sys.exit(1)
# end try
return 0.0
# end if
bShowOutput = ((self.inJac == False) or (self.optimType == "Brute"))
# If stopFilename exists, stop optimization
if self.stopSet():
try:
self.finish(errorOccured=False, userStopped=True)
except:
self.isRunning = False
sys.exit(1)
# end try
return 0.0
# end if
for ii in range(0, self.paramCount):
if self.paramLogscale[ii]:
self.paramNatural[ii] = math.pow(10.0, (paramNormalized[ii] * math.log10(self.paramNorm[ii])))
else:
self.paramNatural[ii] = paramNormalized[ii] * self.paramNorm[ii]
# end if
# end for
# A cache strategy is implemented to avoid redundant calculation.
try:
if (self.funcCounter >= 1) and (len(self.lastParam) >= 1):
tParam = ""
for ii in range(0, self.paramCount - 1):
tParam += (self.paramFormat[ii] % self.paramNatural[ii]) + "\t"
# end for
tParam += (self.paramFormat[self.paramCount - 1] % self.paramNatural[self.paramCount - 1])
if (tParam in self.lastParam):
return self.lastOutput[self.lastParam.index(tParam)]
# end if
# end if
except:
pass
# end try
strT = ""
if (bShowOutput == True):
if self.guessParam:
strT = "\n-------------------- GUESS " + (self.counterFormat.format(self.optimCounter)) + " RUNNING -----------------------\n"
else:
strT = "\n----------------- OPTIMIZATION " + (self.counterFormat.format(self.optimCounter)) + " RUNNING ---------------------\n"
# end if
strT += self.title + ": Optimization (" + self.optimType
if self.optimType == "Optim":
strT += " " + self.minimizeMethod
# end if
strT += ") "
dateT = datetime.datetime.now()
dateStr = dateT.strftime("%Y-%m-%d %H:%M:%S")
strT += (dateStr + "\n")
strT += "Parameter:\t"
for ii in range(0, self.paramCount - 1):
if ((self.paramPoints[ii] > 1) or (self.bruteSimul == False)):
strT += "@" + self.paramName[ii] + "\t"
else:
strT += self.paramName[ii] + "\t"
# end if
# end for
if ((self.paramPoints[self.paramCount - 1] > 1) or (self.bruteSimul == False)):
strT += "@" + self.paramName[self.paramCount - 1] + "\n"
else:
strT += self.paramName[self.paramCount - 1] + "\n"
# end if
strT += "Natural:\t"
for ii in range(0, self.paramCount - 1):
strT += (self.paramFormat[ii] % self.paramNatural[ii]) + "\t"
# end for
strT += (self.paramFormat[self.paramCount - 1] % self.paramNatural[self.paramCount - 1]) + "\n"
strT += "Normalized:\t"
for ii in range(0, self.paramCount - 1):
strT += (self.paramFormatNormalized[ii] % paramNormalized[ii]) + "\t"
# end for
strT += (self.paramFormatNormalized[self.paramCount - 1] % paramNormalized[self.paramCount - 1])
strT += "\n---------------------------------------------------------------\n"
self.log(strT)
# end if bShowOutput
ticT = time.time()
pathIn = os.path.join(self.outputDir, self.inputFilename)
if not os.path.isfile(pathIn):
dispError("cannot open input: file not found", doExit = True, atExit = self.finish, errFilename = self.currentDir + 'errlog.txt')
# end if
fileContent = ""
fileT = open(self.outputDir + self.inputFilename, "r")
for lineT in fileT:
# Normalize line ending (Silvaco do not run input file if contains CRLF terminated lines)
lineT = lineT.rstrip("\r\n")
lineX = lineT.lstrip("\t ")
nSpaces = len(lineT) - len(lineX)
prefixT = lineT[0:nSpaces]
if (self.simulator.name == "atlas") and lineX.startswith("tonyplot"):
# skip tonyplot commands
continue
# endif
if not lineX.startswith("#"):
for ii in range(0, self.paramCount):
setparamT = self.simulator.vardeclpre % self.paramName[ii]
if lineX.startswith(setparamT):
# Need to format parameter to match simulator floating representation
strT = self.paramFormatShort[ii] % self.paramNatural[ii]
fT = float(strT)
lineT = self.simulator.vardecl % (self.paramName[ii], fT)
break
# end if
# end for
# end if
fileContent += (lineT + "\n")
# end for
fileT.close()
fileT = open(self.outputDir + self.inputFilename, "w")
fileT.write(fileContent)
fileT.close()
# format model files
if self.modelCount > 0:
for ii in range(0, self.modelCount):
if self.modelFilename[ii] == "":
break
# end if
pathCC = os.path.join(self.outputDir, self.modelFilename[ii])
if not os.path.isfile(pathCC):
dispError("cannot open model file: " + self.modelFilename[ii], doExit = True, atExit = self.finish, errFilename = self.currentDir + 'errlog.txt')
# end if
fileContent = ""
fileT = open(self.outputDir + self.modelFilename[ii], "r")
for lineT in fileT:
# Normalize line ending (Silvaco do not run input file if contains CRLF terminated lines)
lineT = lineT.rstrip("\r\n")
lineX = lineT.lstrip("\t ")
nSpaces = len(lineT) - len(lineX)
prefixT = lineT[0:nSpaces]
bFound = False
nn = len(self.paramName)
bFound = False
if nn > 0:
for jj in range(0, nn):
setparamT = "double " + self.paramName[jj] + " = "
if lineX.startswith(setparamT):
strT = self.paramFormat[jj] % self.paramNatural[jj]
fT = float(strT)
lineT = prefixT + setparamT + ("%g" % fT) + ";"
bFound = True
break
# end if
# end for
# end if
fileContent += (lineT + "\n")
# end while
fileT.close()
fileT = open(self.outputDir + self.modelFilename[ii], "w")
fileT.write(fileContent)
fileT.close()
# end for
# end if
# remove the simulator verbose output file before starting optimization
pathT = os.path.join(self.outputDir, self.verboseFilename)
try:
if os.path.isfile(pathT):
os.unlink(pathT)
# end if
except:
pass
# end try
# run optimization
try:
tEnv = dict(os.environ)
subprocess.check_call([self.outputDir + self.commandFilename, ""], shell=True, env=tEnv)
except (subprocess.CalledProcessError, excT):
try:
strT = self.printOutput()
fileOptim = open(self.outputDir + self.outputOptimizedFilename, "a")
fileOptim.write(strT)
fileOptim.close()
except:
pass
# end try
dispError(traceback.format_exc(), doExit = True, atExit = self.finish, errFilename = self.currentDir + 'errlog.txt')
return 0.0
# end try
simulatorError = self.isErrorOccurred()
if (simulatorError is not None):
try:
fileOptim = open(self.outputDir + self.outputOptimizedFilename, "a")
fileOptim.write(simulatorError)
fileOptim.close()
except:
pass
# end try
dispError(simulatorError, doExit = True, atExit = self.finish, errFilename = self.currentDir + 'errlog.txt')
return 0.0
# end if
# Calculate the efficiency (Very important to be precise for the optimization algorithm)
LinesToSkip = 4
arrVoltage = np.array([])
arrCurrent = np.array([])
arrPower = np.array([])
iLine = 0
iPoints = 0