-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTFT_Parameter_Extraction_Linux.py
1382 lines (1086 loc) · 61.3 KB
/
TFT_Parameter_Extraction_Linux.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 3 20:04:22 2023
@author: abiswas
"""
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
import configparser
import threading
import os
import sys
from tkinter import Tk
from tkinter import font as tkfont
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
from ttkthemes import ThemedTk
from ttkthemes import ThemedStyle
from PIL import Image, ImageTk
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import subprocess
from scipy.optimize import minimize,differential_evolution,curve_fit,least_squares,basinhopping
from random import random, randint
import random
import re
from matplotlib.backends.backend_pdf import PdfPages
class GUI(ThemedTk):
def __init__(self, *args, **kwargs):
ThemedTk.__init__(self, *args, **kwargs)
self.get_themes()
self.set_theme("ubuntu")
self.title("TFT Parameter Extraction")
style = ttk.Style()
style.theme_use('clam')
style.configure('TLabelframe.Label', font=("Arial", 14, "bold"))
# Get screen width and height
screen_width = self.winfo_screenwidth()
screen_height = self.winfo_screenheight()
# Set the window size to the screen resolution
self.geometry(f'{screen_width}x{screen_height}')
# Load config file
self.config_parser = configparser.ConfigParser()
self.config_parser.read("config.ini")
# Input and output file paths
self.input_file = tk.StringVar()
self.output_file = tk.StringVar()
# Optimization algorithm
self.algorithm_var = tk.StringVar()
self.algorithm_var.set("Differential Evolution")
# Create GUI elements
self.create_menu()
self.create_file_selection_frame()
self.create_output_parameters_frame()
self.create_mosfet_parameters_frame()
# Initialize plot canvases
self.plot_canvases = []
# Create output graphs frame
self.create_output_graphs_frame()
# Create run button
self.create_run_button()
# Load file paths from config
self.input_file.set(self.config_parser.get("Files", "input_file", fallback=""))
self.output_file.set(self.config_parser.get("Files", "output_file", fallback=""))
# Load parameters
self.load_parameters()
self.thread = None
def on_close(self):
# Stop the thread execution
self.save_parameters()
if self.thread and self.thread.is_alive():
if not self.thread.is_alive():
self.thread.daemon = True
self.thread.join()
# Close the GUI
self.destroy()
def create_menu(self):
menu_bar = tk.Menu(self)
menu_bar.configure(bg="white")
# File menu
file_menu = tk.Menu(menu_bar, tearoff=0)
file_menu.add_command(label="Open Input File", command=self.browse_input_file)
file_menu.add_command(label="Open Output File", command=self.browse_output_file)
file_menu.add_separator()
file_menu.add_command(label="Save Output Parameters", command=self.save_output_parameters)
file_menu.add_command(label="Save Plots as PDF", command=self.save_plots_as_pdf)
file_menu.add_separator()
file_menu.add_command(label="Exit", command=self.on_close)
menu_bar.add_cascade(label="File", menu=file_menu)
# Algorithm menu
algorithm_menu = tk.Menu(menu_bar, tearoff=0)
algorithm_menu.add_radiobutton(label="Differential Evolution",
variable=self.algorithm_var,
value="Differential Evolution",
command=self.algorithm_changed)
algorithm_menu.add_radiobutton(label="Differential Evolution Custom",
variable=self.algorithm_var,
value="Differential Evolution Custom",
command=self.algorithm_changed)
menu_bar.add_cascade(label="Algorithm", menu=algorithm_menu)
# Load saved parameters from configuration file
self.load_parameters()
# Run menu
run_menu = tk.Menu(menu_bar, tearoff=0)
run_menu.add_command(label="Run", command=self.run_algorithm)
menu_bar.add_cascade(label="Run", menu=run_menu)
# About menu
about_menu = tk.Menu(menu_bar, tearoff=0)
about_menu.add_command(label="About", command=self.open_about_window)
menu_bar.add_cascade(label="About", menu=about_menu)
# Help menu
help_menu = tk.Menu(menu_bar, tearoff=0)
help_menu.add_command(label="How to Use", command=self.open_help_window)
menu_bar.add_cascade(label="Help", menu=help_menu)
self.config(menu=menu_bar)
def open_about_window(self):
about_window = tk.Toplevel(self)
about_window.title("About")
about_window.configure(bg="white")
about_text = """
Program Name: IGZO TFT Parameter Extraction
Version: 1.3
Change-log: Added model parameter clipboard
Author: Arpan Biswas, Patrick Schalberger
Institute: Institut für Großflächige Mikroelektronik (IGM)
University: Universität Stuttgart
This program performs parameter extraction for IGZO TFT (Thin-Film Transistor) devices. It uses differential evolution optimization algorithm to find the optimal parameter values based on the provided input and output data files.
"""
about_label = tk.Label(about_window, text=about_text, padx=10, pady=10, bg='white')
about_label.pack()
def open_help_window(self):
help_window = tk.Toplevel(self)
help_window.title("Help")
help_window.configure(bg="white")
help_text = """
How to Use IGZO TFT Parameter Extraction Program:
1. Open Input File:
- Click on 'File' -> 'Open Input File' menu item.
- Select the input data file (.dat) containing the measured input characteristics of the IGZO TFT device.
- This also automatically selects the corresponding output file so no need to select output file again.
2. Open Output File:
- Click on 'File' -> 'Open Output File' menu item.
- Select the output data file (.dat) containing the measured output characteristics of the IGZO TFT device.
3. Configure Algorithm (Optional):
- Click on 'Algorithm' menu item.
- Choose the desired optimization algorithm for parameter extraction.
4. Run Parameter Extraction:
- Click on 'Run' -> 'Run' menu item.
- The program will extract the parameters using the selected algorithm and display the results.
5. Save Output Parameters:
- Click on 'File' -> 'Save Output Parameters' menu item.
- Choose the location to save the extracted parameter values as a text file (.txt).
6. Save Plots as PDF (Optional):
- Click on 'File' -> 'Save Plots as PDF' menu item.
- Choose the location to save the generated plots as a PDF file (.pdf).
Differential Evolution Custom:
- This algorithm is a customized version of the Differential Evolution algorithm for parameter extraction.
- It allows you to specify custom settings for the algorithm parameters.
Parameters for Differential Evolution Custom:
- Population Size: The number of individuals in each generation of the algorithm.
- Mutation Factor (F): The scaling factor for the difference vector used in mutation.
- Crossover Probability (CR): The probability of recombination between the target vector and the mutant vector.
- Maximum Generations: The maximum number of generations for the algorithm to converge.
Output Parameters:
- The program will display the final predicted values for the following parameters:
- Threshold Voltage (VTO)
- Mobility (U0)
- Output resistance coefficient (Kappa)
- Static feedback factor for adjusting threshold (Eta)
- Channel length modulation (LAMBDA)
- Bulk charge effect parameter (nfs)
- Bulk surface doping (nsub)
- Mobility degradation factor (Theta)
- These parameters represent the extracted characteristics of the IGZO TFT device.
"""
help_label = tk.Label(help_window, text=help_text, padx=10, pady=10, justify='left')
help_label.pack()
def algorithm_changed(self, event=None):
selected_algorithm = self.algorithm_var.get()
if selected_algorithm == "Differential Evolution":
self.algorithm_combo.set("Differential Evolution")
self.iterations_entry.configure(state=tk.NORMAL)
self.population_size_entry.configure(state=tk.DISABLED)
self.mutation_factor_entry.configure(state=tk.DISABLED)
self.crossover_prob_entry.configure(state=tk.DISABLED)
elif selected_algorithm == "Differential Evolution Custom":
self.algorithm_combo.set("Differential Evolution Custom")
self.iterations_entry.configure(state=tk.NORMAL)
self.population_size_entry.configure(state=tk.NORMAL)
self.mutation_factor_entry.configure(state=tk.NORMAL)
self.crossover_prob_entry.configure(state=tk.NORMAL)
def load_parameters(self):
config = configparser.ConfigParser()
config.read('config_parameters.ini')
if 'Algorithm' in config:
selected_algorithm = config['Algorithm'].get('SelectedAlgorithm')
if selected_algorithm:
self.algorithm_var.set(selected_algorithm)
def create_file_selection_frame(self):
file_selection_frame = ttk.LabelFrame(self, text="File Selection", style="Bold.TLabelframe")
file_selection_frame.grid(row=0, column=0, columnspan = 2, padx=10, pady=10, sticky="nsew")
#self.columnconfigure(0, weight=1)
input_label = ttk.Label(file_selection_frame, text="Input File")
input_label.grid(row=0, column=0, padx=10)
input_entry = ttk.Entry(file_selection_frame, textvariable=self.input_file, width=100)
input_entry.grid(row=0, column=1, padx=10)
input_button = ttk.Button(file_selection_frame, text="Browse", command=self.browse_input_file)
input_button.grid(row=0, column=2, padx=10)
output_label = ttk.Label(file_selection_frame, text="Output File")
output_label.grid(row=1, column=0, padx=10)
output_entry = ttk.Entry(file_selection_frame, textvariable=self.output_file, width=100)
output_entry.grid(row=1, column=1, padx=10)
output_button = ttk.Button(file_selection_frame, text="Browse", command=self.browse_output_file)
output_button.grid(row=1, column=2, padx=10)
# Update MOSFET parameters frame after file selection
def update_mosfet_parameters_frame():
self.create_mosfet_parameters_frame()
self.input_file.trace("w", lambda *args: update_mosfet_parameters_frame())
self.output_file.trace("w", lambda *args: update_mosfet_parameters_frame())
def create_mosfet_parameters_frame(self):
mosfet_params_frame = ttk.LabelFrame(self, text="MOSFET Parameters", style="Bold.TLabelframe")
mosfet_params_frame.grid(row=1, column=0, pady=10, padx=10, sticky="nsew")
# Create and place the frame widgets
t_ox_label = ttk.Label(mosfet_params_frame, text="Thickness of oxide layer (t_ox) in nm:")
t_ox_label.grid(row=0, column=0, padx=10, pady=5)
self.t_ox_entry = ttk.Entry(mosfet_params_frame)
self.t_ox_entry.grid(row=0, column=1, padx=10, pady=5)
self.t_ox_entry.insert(0, "65") # Default value for t_ox
kappa_label = ttk.Label(mosfet_params_frame, text="Dielectric constant of SiO2 (kappa):")
kappa_label.grid(row=1, column=0, padx=10, pady=5)
self.kappa_entry = ttk.Entry(mosfet_params_frame)
self.kappa_entry.grid(row=1, column=1, padx=10, pady=5)
self.kappa_entry.insert(0, "3.9") # Default value for kappa
additional_params_frame = ttk.Frame(mosfet_params_frame)
additional_params_frame.grid(row=2, column=0, columnspan=2, pady=10)
def calculate_additional_params():
def read_dimensions(input_filename):
parameters = {}
# Read the input data
with open(input_filename, "r", encoding='ISO-8859-1') as file:
lines = file.readlines()
for line in lines:
if line.startswith("-") or line[0].isdigit():
data = list(map(float, line.strip().split()))
else:
# Attempt to parse parameter
parts = line.split(':')
if len(parts) == 2:
key = parts[0].strip()
try:
value = float(parts[1].strip())
except ValueError:
value = parts[1].strip() # keep as string if it's not a number
parameters[key] = value
ch_length = parameters.get('Ch_length', 0)
ch_width = parameters.get('Ch_width', 0)
ch_height = parameters.get('Ch_height', 0)
Epsilon_r = parameters.get('Epsilon_r', 0)
# Return the input and output data as NumPy arrays along with Ug_output
return ch_width, ch_length, ch_height, Epsilon_r
unknown_input_file = self.input_file.get()
if unknown_input_file != '':
ch_width, ch_length, ch_height, Epsilon_r = read_dimensions(unknown_input_file)
else:
ch_width, ch_length, ch_height, Epsilon_r = 0, 0, 65e-9, 4
# Device dimensions and thicknesses
W = ch_width
width = int(W/(1e-6)) #um
L = ch_length
length = int(L/(1e-6)) #um
t_dielectric = ch_height
t_dielectric1 = str(t_dielectric/(1e-9))
self.t_ox_entry.delete(0, tk.END)
self.t_ox_entry.insert(0, t_dielectric1)
# Dielectric constant of SiO2
kappa = Epsilon_r
kappa1 = str(Epsilon_r)
self.kappa_entry.delete(0, tk.END)
self.kappa_entry.insert(0, kappa1)
# Constants
epsilon_0 = 8.854e-12 # F/m
# Calculating the oxide capacitance per unit area
epsilon_ox = kappa * epsilon_0
C_ox = epsilon_ox / t_dielectric
param_labels = [
("Width x Length (um x um):", f"{width} um x {length} um"),
("epsilon_0:", f"{epsilon_0:.2e} F/m"),
("C_ox:", f"{C_ox:.2e} F/m^2"),
]
# Clear previous labels
for widget in additional_params_frame.winfo_children():
widget.destroy()
# Display the additional parameters
for i, (param_label, param_value) in enumerate(param_labels):
label = ttk.Label(additional_params_frame, text=param_label)
label.grid(row=i, column=0, padx=10, sticky="e")
value = ttk.Label(additional_params_frame, text=param_value, anchor="w")
value.grid(row=i, column=1, padx=10, sticky="w")
# Calculate and display additional parameters when the entries are modified
self.t_ox_entry.bind("<FocusOut>", lambda event: calculate_additional_params())
self.kappa_entry.bind("<FocusOut>", lambda event: calculate_additional_params())
# Calculate and display additional parameters initially
calculate_additional_params()
def create_run_button(self):
run_frame = ttk.LabelFrame(self, text="Optimzation Algorithm", style="Bold.TLabelframe")
run_frame.grid(row=1, column=1, pady=10, padx=10, sticky="nsew")
#self.columnconfigure(0, weight=1)
#self.columnconfigure(1, weight=1)
algorithm_label = ttk.Label(run_frame, text="Optimization Algorithm:")
algorithm_label.grid(row=0, column=0, padx=10)
self.algorithm_combo = ttk.Combobox(run_frame, values=["Differential Evolution", "Differential Evolution Custom"], width=50)
self.algorithm_combo.grid(row=0, column=1, padx=10)
self.algorithm_combo.current(0) # Set the default algorithm
# Parameters for Differential Evolution
de_params_frame = ttk.Frame(run_frame)
de_params_frame.grid(row=1, column=0, columnspan=3, pady=10)
iterations_label = ttk.Label(de_params_frame, text="Number of Iterations:")
iterations_label.grid(row=0, column=0, padx=10)
self.iterations_entry = ttk.Entry(de_params_frame)
self.iterations_entry.grid(row=0, column=1, padx=10)
self.iterations_entry.insert(0, "10") # Set a default value
population_size_label = ttk.Label(de_params_frame, text="Population Size:")
population_size_label.grid(row=1, column=0, padx=10)
self.population_size_entry = ttk.Entry(de_params_frame)
self.population_size_entry.grid(row=1, column=1, padx=10)
self.population_size_entry.insert(0, "50") # Set a default value
mutation_factor_label = ttk.Label(de_params_frame, text="Mutation Factor:")
mutation_factor_label.grid(row=2, column=0, padx=10)
self.mutation_factor_entry = ttk.Entry(de_params_frame)
self.mutation_factor_entry.grid(row=2, column=1, padx=10)
self.mutation_factor_entry.insert(0, "0.5") # Set a default value
crossover_prob_label = ttk.Label(de_params_frame, text="Crossover Probability:")
crossover_prob_label.grid(row=3, column=0, padx=10)
self.crossover_prob_entry = ttk.Entry(de_params_frame)
self.crossover_prob_entry.grid(row=3, column=1, padx=10)
self.crossover_prob_entry.insert(0, "0.7") # Set a default value
def load_parameters():
config = configparser.ConfigParser()
config.read('config_parameters.ini')
if 'Algorithm' in config:
selected_algorithm = config['Algorithm'].get('SelectedAlgorithm')
if selected_algorithm:
self.algorithm_combo.set(selected_algorithm)
if 'Parameters' in config:
parameters = config['Parameters']
if 'Iterations' in parameters:
self.iterations_entry.delete(0, tk.END)
self.iterations_entry.insert(0, parameters['Iterations'])
if 'PopulationSize' in parameters:
self.population_size_entry.delete(0, tk.END)
self.population_size_entry.insert(0, parameters['PopulationSize'])
if 'MutationFactor' in parameters:
self.mutation_factor_entry.delete(0, tk.END)
self.mutation_factor_entry.insert(0, parameters['MutationFactor'])
if 'CrossoverProbability' in parameters:
self.crossover_prob_entry.delete(0, tk.END)
self.crossover_prob_entry.insert(0, parameters['CrossoverProbability'])
# Load saved parameters from configuration file
load_parameters()
def algorithm_changed(*args):
selected_algorithm = self.algorithm_combo.get()
if selected_algorithm == "Differential Evolution":
self.algorithm_var.set("Differential Evolution")
self.iterations_entry.configure(state=tk.NORMAL)
self.population_size_entry.configure(state=tk.DISABLED)
self.mutation_factor_entry.configure(state=tk.DISABLED)
self.crossover_prob_entry.configure(state=tk.DISABLED)
elif selected_algorithm == "Differential Evolution Custom":
self.algorithm_var.set("Differential Evolution Custom")
self.iterations_entry.configure(state=tk.NORMAL)
self.population_size_entry.configure(state=tk.NORMAL)
self.mutation_factor_entry.configure(state=tk.NORMAL)
self.crossover_prob_entry.configure(state=tk.NORMAL)
self.algorithm_combo.bind("<<ComboboxSelected>>", algorithm_changed)
algorithm_changed() # Call the function initially to set the correct initial state
run_button = ttk.Button(run_frame, text="Run", command=self.run_algorithm)
run_button.grid(row=0, column=2, padx=10, pady=10)
# Save parameters whenever they are changed
self.iterations_entry.bind("<FocusOut>", self.save_parameters)
self.population_size_entry.bind("<FocusOut>", self.save_parameters)
self.mutation_factor_entry.bind("<FocusOut>", self.save_parameters)
self.crossover_prob_entry.bind("<FocusOut>", self.save_parameters)
def save_parameters(self, *args):
config = configparser.ConfigParser()
selected_algorithm = self.algorithm_combo.get()
config['Algorithm'] = {'SelectedAlgorithm': selected_algorithm}
if selected_algorithm == "Differential Evolution":
config['Parameters'] = {
'Iterations': self.iterations_entry.get(),
'PopulationSize': self.population_size_entry.get(),
'MutationFactor': self.mutation_factor_entry.get(),
'CrossoverProbability': self.crossover_prob_entry.get()
}
elif selected_algorithm == "Differential Evolution Custom":
config['Parameters'] = {
'Iterations': self.iterations_entry.get(),
'PopulationSize': self.population_size_entry.get(),
'MutationFactor': self.mutation_factor_entry.get(),
'CrossoverProbability': self.crossover_prob_entry.get()
}
with open('config_parameters.ini', 'w') as configfile:
config.write(configfile)
def create_output_parameters_frame(self):
output_parameters_frame = ttk.LabelFrame(self, text="Output Predicted Parameters", style="Bold.TLabelframe")
output_parameters_frame.grid(row=0, column=2, rowspan=2, columnspan=1, padx=10, pady=10, sticky="nsew")
self.columnconfigure(1, weight=2)
self.output_parameters_text = tk.Text(output_parameters_frame, height=10, width=100)
self.output_parameters_text.pack(padx=10, pady=10)
# Add new button
self.button = ttk.Button(output_parameters_frame, text="Copy Model Parameter Set", command=self.copy_model_parameters)
self.button.pack(padx=10, pady=10)
def copy_model_parameters(self):
try:
# Read the "input.cir" file
with open("input.cir", "r") as file:
# read line by line till we find the .model section
line = file.readline()
while line and ".model" not in line:
line = file.readline()
# Once the .model section is found, keep reading and collecting the parameter values until "+lambda"
params = {'u0': None, 'vto': None, 'eta': None, 'nfs': None, 'nsub': None, 'kappa': None, 'theta': None, 'lambda': None}
while line and "+lambda" not in line:
if '=' in line:
param, value = line.split('=')[0].strip()[1:], line.split('=')[1].strip().split(' ')[0]
if param in params:
params[param] = value
line = file.readline()
if '+lambda' in line:
params['lambda'] = line.split('=')[1].strip()
parameters = """.model testfet nmos level=3
+is=0 u0={u0} vto={vto} gamma=0 pb=0 fc=0 tpg=0 tox=65e-9 eta={eta}
+nfs={nfs} nsub={nsub} kappa={kappa} theta={theta} lambda={lambda}""".format(**params)
# Copy parameters to clipboard
self.clipboard_clear()
self.clipboard_append(parameters)
self.update() # now it stays on the clipboard after the window is closed
messagebox.showinfo("Info", "Parameters copied to clipboard!")
except FileNotFoundError:
messagebox.showerror("Error", "File 'input.cir' not found!")
def create_output_graphs_frame(self):
frame = ttk.LabelFrame(self, text="Output Graphs", style="Bold.TLabelframe")
frame.grid(row=2, column=0, columnspan=4, padx=10, pady=10, sticky="nsew")
# Configure grid column and row weights
self.columnconfigure(0, weight=1)
self.rowconfigure(2, weight=1)
canvas = tk.Canvas(frame, width=800, height=800)
v_scrollbar = ttk.Scrollbar(frame, orient="vertical", command=canvas.yview)
h_scrollbar = ttk.Scrollbar(frame, orient="horizontal", command=canvas.xview) # Horizontal scrollbar
plots_frame = ttk.Frame(canvas)
self.plot_canvases.append(self.create_plot_canvas(plots_frame, 0, 0))
self.plot_canvases.append(self.create_plot_canvas(plots_frame, 0, 1))
self.plot_canvases.append(self.create_plot_canvas(plots_frame, 0, 2))
self.plot_canvases.append(self.create_plot_canvas(plots_frame, 1, 0))
self.plot_canvases.append(self.create_plot_canvas(plots_frame, 1, 1))
self.plot_canvases.append(self.create_plot_canvas(plots_frame, 1, 2))
v_scrollbar.pack(side="right", fill="y")
h_scrollbar.pack(side="bottom", fill="x")
canvas.pack(side="left", fill="both", expand=True)
canvas.create_window((0, 0), window=plots_frame, anchor='n')
canvas.configure(yscrollcommand=v_scrollbar.set, xscrollcommand=h_scrollbar.set, scrollregion=canvas.bbox("all"))
plots_frame.bind("<Configure>", lambda e: canvas.configure(scrollregion=canvas.bbox("all")))
self.update()
def _on_mousewheel(event):
canvas.yview_scroll(-1 * (event.delta // 120), "units")
def _on_shift_mousewheel(event):
canvas.xview_scroll(-1 * (event.delta // 120), "units")
frame.bind_all("<MouseWheel>", _on_mousewheel)
frame.bind_all("<Shift-MouseWheel>", _on_shift_mousewheel)
def create_plot_canvas(self, parent, row, column):
plot_canvas = tk.Canvas(parent, width=600, height=400, bg="white")
plot_canvas.grid(row=row, column=column, padx=10, pady=10, sticky="nsew")
return plot_canvas
def browse_input_file(self):
file_path = filedialog.askopenfilename(filetypes=[("DAT Files", "*.dat")])
if file_path:
self.input_file.set(file_path)
self.auto_select_output_file(file_path)
def browse_output_file(self):
file_path = filedialog.askopenfilename(filetypes=[("DAT Files", "*.dat")])
if file_path:
self.output_file.set(file_path)
def auto_select_output_file(self, input_file):
# Extract the file name and directory from the input file path
input_dir, input_file_name = os.path.split(input_file)
# Create the output file name based on the input file name
output_file_name = input_file_name.replace("_input.dat", "_output.dat")
# Create the output file path by joining the directory and output file name
output_file = os.path.join(input_dir, output_file_name)
# Set the output file path
self.output_file.set(output_file)
def save_output_parameters(self):
output_parameters = self.output_parameters_text.get(1.0, tk.END)
file_path = filedialog.asksaveasfilename(defaultextension=".txt", filetypes=[("Text Files", "*.txt")])
if file_path:
with open(file_path, "w") as file:
file.write(output_parameters)
def save_plots_as_pdf(self):
file_path = filedialog.asksaveasfilename(defaultextension=".pdf", filetypes=[("PDF Files", "*.pdf")])
if file_path:
with PdfPages(file_path) as pdf:
for canvas in self.plot_canvases:
figure = canvas.fig_agg.figure
pdf.savefig(figure)
def run_algorithm(self):
# Clear previous plot canvases
for plot_canvas in self.plot_canvases:
plot_canvas.destroy()
self.plot_canvases = []
# Create output graphs frame
self.create_output_graphs_frame()
input_file = self.input_file.get() # Get the string value from StringVar
output_file = self.output_file.get() # Get the string value from StringVar
algorithm = self.algorithm_var.get()
# Check if the 'Files' section exists in the configuration file
if not self.config_parser.has_section("Files"):
self.config_parser.add_section("Files")
# Save file paths to config
self.config_parser.set("Files", "input_file", input_file)
self.config_parser.set("Files", "output_file", output_file)
# Write the updated configuration to the file
with open("config.ini", "w") as configfile:
self.config_parser.write(configfile)
# Clear the output parameters text
self.output_parameters_text.delete("1.0", tk.END)
# Run algorithm in a separate thread to prevent freezing the GUI
self.thread = threading.Thread(target=self.run_algorithm_thread, args=(input_file, output_file, algorithm))
self.thread.start()
def run_algorithm_thread(self, input_file, output_file, algorithm):
def read_data(input_filename, output_filename, plot=False):
colors = ["r", "g", "b", "m"]
labels = ["Udconst = 0.1", "Udconst = 5.1", "Udconst = 10.1", "Udconst = 15.1"]
Udconst_values = [0.1, 5.1, 10.1, 15.1]
Ug_output = [0, 4, 8, 12, 16, 20]
############################## input ###################################
# Initialize lists to store the data
Ug_input_meas = []
Id_Udconst = [[] for _ in range(4)]
parameters = {}
# Read the input data
with open(input_filename, "r", encoding='ISO-8859-1') as file:
lines = file.readlines()
for line in lines:
if line.startswith("-") or line[0].isdigit():
data = list(map(float, line.strip().split()))
if len(data) >= 5: # Make sure the data list has at least 5 elements
Ug_input_meas.append(data[0])
for i in range(4):
Id_Udconst[i].append(data[i + 1])
else:
# Attempt to parse parameter
parts = line.split(':')
if len(parts) == 2:
key = parts[0].strip()
try:
value = float(parts[1].strip())
except ValueError:
value = parts[1].strip() # keep as string if it's not a number
parameters[key] = value
# Convert to a NumPy array
Ug_input_meas = np.array(Ug_input_meas)
Id_input_meas = np.array(Id_Udconst)
ch_length = parameters.get('Ch_length', 0)
ch_width = parameters.get('Ch_width', 0)
ch_height = parameters.get('Ch_height', 0)
Epsilon_r = parameters.get('Epsilon_r', 0)
############################## output ###################################
# Extract Ud and Id values for different Ug values
Ud_output_meas = []
Id_output_meas = [[] for _ in range(6)] # 6 Ug values: 0, 4, 8, 12, 16, 20V
with open(output_filename, "r", encoding='ISO-8859-1') as file:
raw_data = file.read()
# Remove comments and split the data into lines
data_lines = [line for line in raw_data.split('\n')[27:] if not line.startswith('#') and line.strip()]
for line in data_lines:
values = list(map(float, line.split()))
Ud_output_meas.append(values[0])
for i in range(6):
Id_output_meas[i].append(values[i + 1])
# Convert to NumPy arrays
Ud_output_meas = np.array(Ud_output_meas)
Id_output_meas = np.array([np.array(ids) for ids in Id_output_meas])
if plot:
def plot1(canvas):
fig, ax = plt.subplots()
# Plot the input data
for j in range(4):
ax.plot(Ug_input_meas, Id_input_meas[j], color=colors[j], label=labels[j])
ax.set_title("IGZO TFT Input Characteristics")
ax.set_xlabel("Ug (V)")
ax.set_ylabel("Id (A)")
ax.legend(fontsize=8)
canvas.fig_agg = FigureCanvasTkAgg(fig, master=canvas)
canvas.fig_agg.draw()
canvas.fig_agg.get_tk_widget().pack(side="top", fill="both", expand=True)
self.after(0, plot1, self.plot_canvases[0])
def plot2(canvas):
fig, ax = plt.subplots()
# Plot the input data
for i, ids in enumerate(Id_output_meas):
ax.plot(Ud_output_meas, ids, label=f'Ug = {Ug_output[i]}V')
ax.set_title("IGZO TFT Output Characteristics")
ax.set_xlabel("Ud (V)")
ax.set_ylabel("Id (A)")
ax.legend(fontsize=8)
canvas.fig_agg = FigureCanvasTkAgg(fig, master=canvas)
canvas.fig_agg.draw()
canvas.fig_agg.get_tk_widget().pack(side="top", fill="both", expand=True)
self.after(0, plot2, self.plot_canvases[1])
# Return the input and output data as NumPy arrays along with Ug_output
return Ug_input_meas, Id_input_meas, Ud_output_meas, Id_output_meas, Ug_output, ch_width, ch_length, ch_height, Epsilon_r
unknown_input_file = os.path.basename(input_file)
unknown_output_file = os.path.basename(output_file)
Ug_input_meas, Id_input_meas, Ud_output_meas, Id_output_meas, Ug_output, ch_width, ch_length, ch_height, Epsilon_r = read_data(input_file, output_file, plot=True)
# Device dimensions and thicknesses
W = ch_width
width = W/(1e-6) #um
L = ch_length
length = L/(1e-6) #um
t_dielectric = float(self.t_ox_entry.get())*1e-9
# Dielectric constant of SiO2
kappa = float(self.kappa_entry.get())
# Constants
epsilon_0 = 8.854e-12 # F/m
# Calculating the oxide capacitance per unit area
epsilon_ox = kappa * epsilon_0
C_ox = epsilon_ox / t_dielectric
################### Vth Calc #################################
def func_vth(Id_data_list, Ug_array, plot=False):
def plot_data_and_vth(Id_data, color, label, Ug_array):
# Calculate the square root of Id_data
sqrt_Id_data = np.sqrt(np.abs(Id_data))
# Calculate the slope between consecutive points
slopes = np.diff(sqrt_Id_data) / np.diff(Ug_array)
# Find the index with the steepest slope
steepest_slope_index = np.argmax(slopes)
# Get the point on the curve corresponding to the steepest slope
point_x = Ug_array[steepest_slope_index]
point_y = sqrt_Id_data[steepest_slope_index]
# Extrapolate the tangent line to the x-axis (Id = 0) and find the corresponding Vth
Vth = point_x - point_y / slopes[steepest_slope_index]
return Vth
colors = ["r", "g", "b", "m"]
labels = ["Udconst = 0.1", "Udconst = 5.1", "Udconst = 10.1", "Udconst = 15.1"]
vth_list = []
for i in range(1,4):
vth = plot_data_and_vth(Id_data_list[i], colors[i], labels[i], Ug_array)
vth_list.append(vth)
average_vth = np.mean(vth_list)
Vth = average_vth
if plot:
def plot3(canvas):
fig, ax = plt.subplots()
# Plot the input data
for i in range(4):
sqrt_Id_data = np.sqrt(np.abs(Id_input_meas[i]))
ax.plot(Ug_input_meas, sqrt_Id_data, color=colors[i], label=labels[i])
ax.axvline(average_vth, color='k', linestyle='--', label=f"Average Vth = {average_vth:.2f}")
ax.set_title("IGZO TFT Vth Calculations")
ax.set_xlabel("Gate Voltage (V)")
ax.set_ylabel("Square root of Drain Current")
ax.legend(fontsize=8)
canvas.fig_agg = FigureCanvasTkAgg(fig, master=canvas)
canvas.fig_agg.draw()
canvas.fig_agg.get_tk_widget().pack(side="top", fill="both", expand=True)
self.after(0, plot3, self.plot_canvases[2])
return Vth
Vth = func_vth(Id_input_meas, Ug_input_meas, plot=True)
print(f"Average Vth = {Vth :.2f} V")
################################### mobility calc ######################################
Udconst_values = [0.1, 5.1, 10.1, 15.1]
def func_mobility(Ug_input_meas, Id_input_meas, Udconst_values, Vth, W, L, C_ox):
def calc_saturation_mobility_from_input(Id, Ug, Udconst, W, L, C_ox, Vth):
# Select the saturation region where Ug > Udconst + Vth
sat_region = Ug > (Udconst + Vth)
Id_sat = Id[sat_region]
Ug_sat = Ug[sat_region]
# Calculate the saturation mobility
mobility = (2 * Id_sat) / (C_ox * W/L * (Ug_sat - Vth)**2)
return np.mean(mobility)
mobilities = []
for i in range(1,len(Id_input_meas)): # for each set of Ids corresponding to a specific Udconst
Id = Id_input_meas[i]
Ug = Ug_input_meas
Udconst = Udconst_values[i]
mobility = calc_saturation_mobility_from_input(Id, Ug, Udconst, W, L, C_ox, Vth)
mobilities.append(mobility)
# Calculate the average mobility
average_mobility = np.mean(mobilities) * 1e4 # Convert from m^2/Vs to cm^2/Vs
return average_mobility
# Usage
average_mobility_input = func_mobility(Ug_input_meas, Id_input_meas, Udconst_values, Vth, W, L, C_ox)
print(f"Average saturation mobility from input characteristics = {average_mobility_input} cm^2/Vs")
u0 = average_mobility_input
#################### kappa ########################################
def calculate_kappa(Id_input_meas, Ug_input_meas):
# Calculate the logarithm of the Id values
log_Id = np.log10(np.abs(Id_input_meas))
# Calculate the derivative of log10(Id) with respect to Vg
dlog_Id_dVg = np.gradient(log_Id, Ug_input_meas)
# Find the minimum value of the derivative
min_dlog_Id_dVg = np.min(dlog_Id_dVg)
# Calculate kappa from the minimum derivative value
kappa = 1 / (1 - min_dlog_Id_dVg)
return kappa
kappa_list = []
for i in range(4):
kappa_i = calculate_kappa(Id_input_meas[i], Ug_input_meas)
kappa_list.append(kappa_i)
mean_kappa = np.mean(kappa_list)
print(f"Average Kappa: {mean_kappa:.3f}")
##################### eta ############################################
def calculate_eta_from_output(Id_output_meas, Ud_output_meas, Ug_output, Vth, kappa):
eta_list = []
for i, Id_data in enumerate(Id_output_meas):
# Choose a dataset where Vgs is close to the subthreshold region
if Ug_output[i] < Vth:
continue
# Linearize the equation by taking the natural logarithm of both sides
ln_Id = np.log(np.abs(Id_data))
# Perform a linear regression on the plot of ln(Id) vs Vds
slope, _ = np.polyfit(Ud_output_meas, ln_Id, 1)
# Slope is equal to eta
eta = slope
eta_list.append(eta)
# Calculate the average eta value
mean_eta = np.mean(eta_list)
return mean_eta
mean_eta = calculate_eta_from_output(Id_output_meas, Ud_output_meas, Ug_output, Vth, mean_kappa)
print(f"Average Eta (from output characteristics): {mean_eta:.3f}")
#################### lambda ###########################################
def calculate_lambda(Ud_output_meas, Id_output_meas):
# Calculate the derivative of Id with respect to Ud
dId_dUd = np.gradient(Id_output_meas, axis=1) / np.gradient(Ud_output_meas)
# Calculate LAMBDA as the average of the derivatives in the saturation region
LAMBDA = np.mean(dId_dUd[:, -10:]) # Using the last 10 points in the saturation region
return LAMBDA
LAMBDA = calculate_lambda(Ud_output_meas, Id_output_meas)
print(f"LAMBDA = {LAMBDA} V^-1")
####################### ECRIT ########################################
def estimate_ecrit(u0):
Vsat = 1e7 # cm/s
ECRIT = Vsat / u0
return ECRIT
ECRIT = estimate_ecrit(u0)
print(f"Estimated ECRIT = {ECRIT} V/cm")
####################### VMAX ########################################
def calculate_vmax(ECRIT, Ug_input_meas, t_dielectric):
E_peak = np.max(Ug_input_meas) / t_dielectric
VMAX = ECRIT * E_peak
return VMAX
VMAX = calculate_vmax(ECRIT, Ug_input_meas, t_dielectric)
print(f"VMAX = {VMAX} m/s")
####################### KP ########################################
def calculate_kp(Ug_input_meas, Id_input_meas, Vth, W, L):
# Calculate the derivative of Id with respect to Vg
gm = np.gradient(Id_input_meas, axis=1) / np.gradient(Ug_input_meas)
# Select the linear region where (Vg - Vth) is small
linear_region_mask = (Ug_input_meas - Vth) < 1.0
# Calculate KP using the average gm in the linear region
KP = np.mean(gm[:, linear_region_mask]) / (W / L)