-
Notifications
You must be signed in to change notification settings - Fork 93
/
oncvgui.py
executable file
·2855 lines (2253 loc) · 93.6 KB
/
oncvgui.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 python
"""Gui for the oncvpsp norm-conserving pseudopotential generator."""
import os
import copy
import time
import shutil
import abc
import sys
import six
import wx
import wx.lib.mixins.listctrl as listmix
import numpy as np
from collections import OrderedDict
from monty.dev import get_ncpus
from monty.collections import AttrDict
from pymatgen.core.periodic_table import Element
from abipy.gui.editor import TextNotebookFrame, SimpleTextViewer
from abipy.gui.oncvtooltips import oncv_tip
from abipy.gui import mixins as mix
from abipy.gui import awx
from abipy.gui.awx.elements_gui import WxPeriodicTable, PeriodicPanel, ElementButton
from abipy.flowtk import Pseudo
try:
from pseudo_dojo.core.dojoreport import DojoReport
from pseudo_dojo.refdata.nist import database as nist
from pseudo_dojo.ppcodes.ppgen import OncvGenerator
from pseudo_dojo.ppcodes.oncvpsp import OncvOutputParser, MultiPseudoGenDataPlotter
except ImportError as exc:
print("Error while trying to import pseudo_dojo modules:\n%s" % str(exc))
#raise
# TODO
# Change oncvpsp so that
# 1) we always write the logarithmic derivative
# 2) better error handling
_char2l = {
"s": 0,
"p": 1,
"d": 2,
"f": 3,
"g": 4,
"h": 5,
"i": 6,
}
def char2l(char):
return _char2l[char]
def all_symbols():
return [e.symbol for e in Element]
def add_size(kwargs, size=(800, 600)):
"""Add size to kwargs if not present."""
if "size" not in kwargs:
kwargs["size"] = size
return kwargs
def my_periodic_table(parent):
"""
A periodic table that allows the user to select the element
before starting the pseudopotential generation.
"""
class MyElementButton(ElementButton):
def makePopupMenu(self):
# Get the menu of the super class.
menu = super(MyElementButton, self).makePopupMenu()
self.ID_POPUP_ONCVPSP = wx.NewId()
menu.Append(self.ID_POPUP_ONCVPSP, "Generate NC pseudo with oncvpsp")
# Associate menu/toolbar items with their handlers.
menu_handlers = [
(self.ID_POPUP_ONCVPSP, self.onOncvpsp),
]
for combo in menu_handlers:
mid, handler = combo[:2]
self.Bind(wx.EVT_MENU, handler, id=mid)
return menu
def onOncvpsp(self, event):
"""Open a frame for the initialization of oncvpsp."""
frame = OncvParamsFrame(self, self.Z)
frame.Show()
class MyPeriodicPanel(PeriodicPanel):
element_button_class = MyElementButton
def OnSelect(self, event):
# Get the atomic number Z, open a dialog to get basic configuration parameters from the user.
# The dialog will then generate the main Frame for the pseudo generation.
super(MyPeriodicPanel, self).OnSelect(event)
z = event.GetId() - 100
print("select", z)
class MyPeriodicTable(WxPeriodicTable):
periodic_panel_class = MyPeriodicPanel
return MyPeriodicTable(parent)
class OncvParamsFrame(awx.Frame):
"""
This frame allows the user to specify the most important parameters
to generate the pseudopotential once the chemical element has been selected.
"""
HELP_MSG = """\
Quick help:
Use this window to select the AE reference configuration and how
to separate states into core and valence.
"""
def __init__(self, parent, z, **kwargs):
super(OncvParamsFrame, self).__init__(parent, **kwargs)
self.element = Element.from_Z(z)
self.buildUI()
def buildUI(self):
# Build controller with the dimensions.
panel = wx.Panel(self, -1)
self.wxdims = awx.RowMultiCtrl(self, ctrl_params=OrderedDict([
("nc", dict(dtype="i", tooltip="Number of core states")),
("nv", dict(dtype="i", tooltip="Number of valence states")),
("lmax", dict(dtype="i", tooltip="Maximum angular momentum for pseudo"))
]))
# Initialize the quantum numbers of the AE atom with the ground-state configuration.
# E.g., The electronic structure for Fe is represented as:
# [(1, "s", 2), (2, "s", 2), (2, "p", 6), (3, "s", 2), (3, "p", 6), (3, "d", 6), (4, "s", 2)]
ele_struct = self.element.full_electronic_structure
ctrls = OrderedDict([
("n", dict(dtype="i")),
("l", dict(dtype="i")),
("f", dict(dtype="f"))])
self.wxaeconf = awx.TableMultiCtrl(self, nrows=len(ele_struct), ctrls=ctrls)
for wxrow, (n, lchar, f) in zip(self.wxaeconf, ele_struct):
row = OrderedDict()
row["n"], row["l"], row["f"] = n, char2l(lchar), f
wxrow.SetParams(row)
add_button = wx.Button(self, -1, "Add row")
add_button.Bind(wx.EVT_BUTTON, self.onAddButton)
del_button = wx.Button(self, -1, "Delete row")
del_button.Bind(wx.EVT_BUTTON, self.onDelButton)
hsz = wx.BoxSizer(wx.HORIZONTAL)
hsz.Add(add_button)
hsz.Add(del_button)
main_sizer = wx.BoxSizer(wx.VERTICAL)
main_sizer.Add(hsz, 0,flag=wx.ALL | wx.ALIGN_CENTER_HORIZONTAL)
main_sizer.Add(self.wxdims, 0, flag=wx.ALL | wx.ALIGN_CENTER_HORIZONTAL)
main_sizer.Add(self.wxaeconf, 0, flag=wx.ALL | wx.ALIGN_CENTER_HORIZONTAL)
help_button = wx.Button(self, wx.ID_HELP)
help_button.Bind(wx.EVT_BUTTON, self.onHelp)
main_sizer.Add(help_button, 0, flag=wx.ALL | wx.ALIGN_RIGHT)
self.SetSizerAndFit(main_sizer)
def get_oncv_params(self):
"""Return the basic dimensions used in oncvpsp."""
print(self.wxaeconf.GetParams())
return AttrDict(
dims=self.wxdims.GetParams(),
)
def show_nist_lda_levels(self):
# Get the LDA levels of the neutral atom.
# (useful to decide if semicore states should be included in the valence).
entry = nist.get_neutral_entry(symbol=self.element.symbol)
frame = awx.Frame(self)
awx.ListCtrlFromTable(frame, table=entry.to_table())
frame.Show()
def onAddButton(self, event):
"""Add a new row."""
self.get_oncv_params()
def onDelButton(self, event):
"""Delete last row."""
self.show_nist_lda_levels()
class WxOncvFrame(awx.Frame, mix.Has_Tools):
"""The main frame of the GUI"""
VERSION = "0.1"
HELP_MSG = """\
This window shows a template input file with the variables
used to generated the pseudopotential. The `optimize` buttons
allows you to scan a set of possible values for the generation of the pseudopotential.
"""
def __init__(self, parent, filepath=None):
super(WxOncvFrame, self).__init__(parent, id=-1, title=self.codename)
# This combination of options for config seems to work on my Mac.
self.config = wx.FileConfig(appName=self.codename, localFilename=self.codename + ".ini",
style=wx.CONFIG_USE_LOCAL_FILE)
# Build menu, toolbar and status bar.
self.SetMenuBar(self.makeMenu())
self.statusbar = self.CreateStatusBar()
self.Centre()
self.makeToolBar()
#self.toolbar.Enable(False)
self.input_file = None
if filepath is not None:
if os.path.exists(filepath):
self.input_file = os.path.abspath(filepath)
self.BuildUI(notebook=OncvNotebook.from_file(self, filepath))
else:
# Assume symbol
self.BuildUI(notebook=OncvNotebook.from_symbol(self, filepath))
else:
self.BuildUI()
@property
def codename(self):
"""Name of the application."""
return "WxOncvGui"
def BuildUI(self, notebook=None):
"""Build user-interface."""
old_selection = None
if hasattr(self, "main_sizer"):
# Remove old notebook
main_sizer = self.main_sizer
main_sizer.Hide(0)
main_sizer.Remove(0)
# Save the active tab so that we can set it afterwards.
old_selection = self.notebook.GetSelection()
del self.notebook
else:
self.main_sizer = main_sizer = wx.BoxSizer(wx.VERTICAL)
if notebook is not None:
self.notebook = notebook
else:
# Default is, of course, silicon.
self.notebook = OncvNotebook.from_symbol(self, "Si")
main_sizer.Add(self.notebook, flag=wx.EXPAND)
self.SetSizerAndFit(main_sizer)
main_sizer.Layout()
# Reinstate the old selection
if old_selection is not None:
self.notebook.SetSelection(old_selection)
def AddFileToHistory(self, filepath):
"""Add the absolute filepath to the file history."""
self.file_history.AddFileToHistory(filepath)
self.file_history.Save(self.config)
self.config.Flush()
def onFileHistory(self, event):
fileNum = event.GetId() - wx.ID_FILE1
filepath = self.file_history.GetHistoryFile(fileNum)
self.file_history.AddFileToHistory(filepath)
self.BuildUI(notebook=OncvNotebook.from_file(self, filepath))
def makeMenu(self):
"""Creates the main menu."""
menu_bar = wx.MenuBar()
file_menu = wx.Menu()
file_menu.Append(wx.ID_OPEN, "&Open", help="Open an input file")
file_menu.Append(wx.ID_SAVE, "&Save", help="Save the input file")
file_menu.Append(wx.ID_CLOSE, "&Close", help="Close the Gui")
#file_menu.Append(wx.ID_EXIT, "&Quit", help="Exit the application")
# Make sub-menu with the list of supported visualizers.
symbol_menu = wx.Menu()
self._id2symbol = {}
for symbol in all_symbols():
_id = wx.NewId()
symbol_menu.Append(_id, symbol)
self._id2symbol[_id] = symbol
self.Bind(wx.EVT_MENU, self.onNewNotebookFromSymbol, id=_id)
file_menu.AppendMenu(-1, 'Template from element', symbol_menu)
file_history = self.file_history = wx.FileHistory(8)
file_history.Load(self.config)
recent = wx.Menu()
file_history.UseMenu(recent)
file_history.AddFilesToMenu()
file_menu.AppendMenu(-1, "&Recent Files", recent)
self.Bind(wx.EVT_MENU_RANGE, self.onFileHistory, id=wx.ID_FILE1, id2=wx.ID_FILE9)
menu_bar.Append(file_menu, "File")
# Add Mixin menus.
menu_bar.Append(self.CreateToolsMenu(), "Tools")
help_menu = wx.Menu()
help_menu.Append(wx.ID_HELP, "Help ", help="Quick help")
help_menu.Append(wx.ID_ABOUT, "About " + self.codename, help="Info on the application")
menu_bar.Append(help_menu, "Help")
# Associate menu/toolbar items with their handlers.
menu_handlers = [
(wx.ID_OPEN, self.onOpen),
(wx.ID_CLOSE, self.onClose),
#(wx.ID_EXIT, self.onExit),
(wx.ID_SAVE, self.onSave),
(wx.ID_HELP, self.onHelp),
(wx.ID_ABOUT, self.onAbout),
]
for combo in menu_handlers:
mid, handler = combo[:2]
self.Bind(wx.EVT_MENU, handler, id=mid)
return menu_bar
def makeToolBar(self):
"""Creates the toolbar."""
self.toolbar = toolbar = self.CreateToolBar()
self.toolbar.SetToolBitmapSize(wx.Size(48, 48))
def bitmap(path):
return wx.Bitmap(awx.path_img(path))
self.ID_SHOW_INPUT = wx.NewId()
self.ID_RUN_INPUT = wx.NewId()
toolbar.AddSimpleTool(self.ID_SHOW_INPUT, bitmap("in.png"), "Visualize the input file")
toolbar.AddSimpleTool(self.ID_RUN_INPUT, bitmap("run.png"), "Run the input file.")
toolbar.Realize()
# Associate menu/toolbar items with their handlers.
menu_handlers = [
(self.ID_SHOW_INPUT, self.onShowInput),
(self.ID_RUN_INPUT, self.onRunInput),
]
for combo in menu_handlers:
mid, handler = combo[:2]
self.Bind(wx.EVT_MENU, handler, id=mid)
def onNewNotebookFromSymbol(self, event):
symbol = self._id2symbol[event.GetId()]
self.BuildUI(notebook=OncvNotebook.from_symbol(self, symbol))
def onShowInput(self, event):
"""Show the input file in a new frame."""
text = self.notebook.makeInputString()
SimpleTextViewer(self, text=text, title="Oncvpsp Input").Show()
def onRunInput(self, event):
"""Build a new generator from the input file, and add it to the queue."""
text = self.notebook.makeInputString()
try:
psgen = OncvGenerator(text, calc_type=self.notebook.calc_type)
except:
return awx.showErrorMessage(self)
frame = PseudoGeneratorsFrame(self, [psgen], title="Run Input")
frame.launch_psgens()
frame.Show()
def onOpen(self, event):
"""Open a file"""
dialog = wx.FileDialog(self, message="Choose an input file", style=wx.OPEN)
if dialog.ShowModal() == wx.ID_CANCEL: return
filepath = dialog.GetPath()
dialog.Destroy()
# Add to the history.
self.file_history.AddFileToHistory(filepath)
self.file_history.Save(self.config)
self.config.Flush()
self.BuildUI(notebook=OncvNotebook.from_file(self, filepath))
def onSave(self, event):
"""Save a file"""
dialog = wx.FileDialog(self, message="Save file as...", style=wx.SAVE | wx.OVERWRITE_PROMPT,
wildcard="Dat files (*.dat)|*.dat")
if dialog.ShowModal() == wx.ID_CANCEL: return
filepath = dialog.GetPath()
dialog.Destroy()
# Add to the history.
self.file_history.AddFileToHistory(filepath)
self.file_history.Save(self.config)
self.config.Flush()
with open(filepath, "w") as fh:
fh.write(self.notebook.makeInputString())
def onClose(self, event):
""" Respond to the "Close" menu command."""
self.Destroy()
def onAbout(self, event):
return awx.makeAboutBox(
codename=self.codename,
version=self.VERSION,
description="oncvgui is a front-end for the pseudopotential generator oncvpsp",
developers=["Matteo Giantomassi"],
website="http://www.mat-simresearch.com/")
@six.add_metaclass(abc.ABCMeta)
class OptimizationFrame(awx.Frame):
"""Base class for optimization frames."""
def __init__(self, parent, **kwargs):
super(OptimizationFrame, self).__init__(parent, **kwargs)
# All optimization buttons are disabled when we start an optimization.
#self.main_frame.notebook.enable_all_optimize_buttons(False)
#self.main_frame.Enable(False)
#self.Bind(wx.EVT_WINDOW_DESTROY, self.onDestroy)
@property
def main_frame(self):
return self.getParentWithType(WxOncvFrame)
def onDestroy(self, event):
"""Enable all optimize_buttons before destroying the Frame."""
#self.main_frame.notebook.enable_all_optimize_buttons(True)
return super(OptimizationFrame, self).Destroy()
def onCloseButton(self, event):
self.onDestroy(event)
def onOkButton(self, event):
"""
Get input from user, generate new input files by changing some parameters
and open a new frame for running the calculations.
"""
# Build the PseudoGenerators and open a new frame to run them.
psgens = []
for inp in self.build_new_inps():
try:
psgen = OncvGenerator(str(inp), calc_type=self.notebook.calc_type)
psgens.append(psgen)
except:
return awx.showErrorMessage(self)
frame = PseudoGeneratorsFrame(self, psgens, title=self.opt_type)
frame.launch_psgens()
frame.Show()
def make_buttons(self, parent=None):
"""
Build the three buttons (Generate, Cancel, Help), binds them and return the sizer.
"""
parent = self if parent is None else parent
add_opts = dict(flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
gen_button = wx.Button(parent, wx.ID_OK, label='Generate')
gen_button.Bind(wx.EVT_BUTTON, self.onOkButton)
close_button = wx.Button(parent, wx.ID_CANCEL, label='Cancel')
close_button.Bind(wx.EVT_BUTTON, self.onCloseButton)
help_button = wx.Button(parent, wx.ID_HELP)
help_button.Bind(wx.EVT_BUTTON, self.onHelp)
hbox = wx.BoxSizer(wx.HORIZONTAL)
hbox.Add(gen_button, **add_opts)
hbox.Add(close_button, **add_opts)
hbox.Add(help_button, **add_opts)
return hbox
@abc.abstractproperty
def opt_type(self):
"""Human-readable string describing the optimization type."""
@abc.abstractmethod
def build_new_inps(self):
"""Returns a list of new inputs."""
class LlocOptimizationFrame(OptimizationFrame):
"""
This frame allows the user to optimize the parameters for the local part of the pseudopotential
"""
HELP_MSG = """\
This window allows you to change/optimize the parameters governing the local part"""
def __init__(self, parent, notebook, **kwargs):
"""
Args:
notebook:
`OncvNotebool` containing the parameters of the template.
"""
super(LlocOptimizationFrame, self).__init__(parent, **kwargs)
# Save reference to the input panel.
self.notebook = notebook
panel = wx.Panel(self, -1)
main_sizer = wx.BoxSizer(wx.VERTICAL)
add_opts = dict(flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
#self.fcfact_ctl = awx.IntervalControl(self, start=0.25, num=6, step=0.05, choices=[">", "centered", "<"])
#check_l.SetToolTipString("Enable/Disable optimization for this l-channel")
#main_sizer.Add(self.fcfact_ctl, 1, flag=wx.ALL | wx.ALIGN_CENTER_HORIZONTAL)
buttons_sizer = self.make_buttons()
main_sizer.Add(buttons_sizer, flag=wx.ALL | wx.ALIGN_CENTER_HORIZONTAL)
self.SetSizerAndFit(main_sizer)
@property
def opt_type(self):
return "lloc optimization"
def build_new_inps(self):
# Generate new list of inputs.
base_inp = self.notebook.makeInput()
return base_inp.optimize_vloc()
class Rc5OptimizationFrame(OptimizationFrame):
"""
This frame allows the user to optimize the parameters for the local part of the pseudopotential
"""
HELP_MSG = """\
This window allows you to change/optimize the rc5 parameter"""
def __init__(self, parent, notebook, **kwargs):
"""
Args:
notebook:
`OncvNotebool` containing the parameters of the template.
"""
super(Rc5OptimizationFrame, self).__init__(parent, **kwargs)
# Save reference to the input panel.
self.notebook = notebook
panel = wx.Panel(self, -1)
main_sizer = wx.BoxSizer(wx.VERTICAL)
add_opts = dict(flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
self.rc5_ctlr = awx.IntervalControl(self, start=0.25, num=6, step=0.05, choices=[">", "centered", "<"])
main_sizer.Add(self.rc5_ctlr, 1, flag=wx.ALL | wx.ALIGN_CENTER_HORIZONTAL)
buttons_sizer = self.make_buttons()
main_sizer.Add(buttons_sizer, flag=wx.ALL | wx.ALIGN_CENTER_HORIZONTAL)
self.SetSizerAndFit(main_sizer)
@property
def opt_type(self):
return "rc5 optimization"
def build_new_inps(self):
# Generate new list of inputs.
base_inp = self.notebook.makeInput()
# TODO
return base_inp.optimize_rc5()
class DeblOptimizationFrame(OptimizationFrame):
"""
This frame allows the user to optimize the VKB projectors
"""
HELP_MSG = """\
This window allows you to optimize the parameters used to construct the VKB projectors."""
def __init__(self, parent, notebook, **kwargs):
"""
Args:
notebook:
Notebook containing the parameters of the template.
"""
super(DeblOptimizationFrame, self).__init__(parent, **kwargs)
# Save reference to the input panel.
self.notebook = notebook
lmax = notebook.lmax
panel = wx.Panel(self, -1)
main_sizer = wx.BoxSizer(wx.VERTICAL)
add_opts = dict(flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
# Build list of controls to allow the user to select the list of
# debl for the different l-channels. One can disable l-channels via checkboxes.
self.checkbox_l = [None] * (lmax + 1)
self.debl_range_l = [None] * (lmax + 1)
debl_l = notebook.makeInput().debl_l
for l in range(lmax + 1):
sbox_sizer = wx.StaticBoxSizer(wx.StaticBox(self, -1, "Angular Channel L=%d" % l), wx.VERTICAL)
vsz = wx.BoxSizer(wx.HORIZONTAL)
self.checkbox_l[l] = check_l = wx.CheckBox(self, -1)
check_l.SetToolTipString("Enable/Disable optimization for this l-channel")
check_l.SetValue(True)
self.debl_range_l[l] = debl_range_l = awx.IntervalControl(self, start=debl_l[l], num=3, step=0.5)
vsz.Add(check_l, **add_opts)
vsz.Add(debl_range_l, **add_opts)
sbox_sizer.Add(vsz, 1, wx.ALL, 5)
main_sizer.Add(sbox_sizer, 1, flag=wx.ALL | wx.ALIGN_CENTER_HORIZONTAL)
buttons_sizer = self.make_buttons()
main_sizer.Add(buttons_sizer, flag=wx.ALL | wx.ALIGN_CENTER_HORIZONTAL)
self.SetSizerAndFit(main_sizer)
@property
def opt_type(self):
return "Vkb optimization"
def build_new_inps(self):
# Get the list of angular channels activated and the corresponding arrays.
l_list, deblvals_list = [], []
for l, (checkbox, wxrange) in enumerate(zip(self.checkbox_l, self.debl_range_l)):
if checkbox.IsChecked():
l_list.append(l)
deblvals_list.append(wxrange.getValues())
# Generate new list of inputs.
base_inp = self.notebook.makeInput()
new_inps = []
for l, new_debls in zip(l_list, deblvals_list):
new_inps.extend(base_inp.optimize_debls_for_l(l=l, new_debls=new_debls))
return new_inps
class FcfactOptimizationFrame(OptimizationFrame):
"""
This frame allows the user to optimize the model core charge
"""
HELP_MSG = """\
This window allows you to change/optimize the parameters governing the model core charge"""
def __init__(self, parent, notebook, **kwargs):
"""
Args:
notebook:
Notebook containing the parameters of the template.
"""
super(FcfactOptimizationFrame, self).__init__(parent, **kwargs)
# Save reference to the input panel.
self.notebook = notebook
panel = wx.Panel(self, -1)
main_sizer = wx.BoxSizer(wx.VERTICAL)
add_opts = dict(flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
self.fcfact_ctl = awx.IntervalControl(self, start=0.25, num=6, step=0.05, choices=[">", "centered", "<"])
#check_l.SetToolTipString("Enable/Disable optimization for this l-channel")
main_sizer.Add(self.fcfact_ctl, 1, flag=wx.ALL | wx.ALIGN_CENTER_HORIZONTAL)
buttons_sizer = self.make_buttons()
main_sizer.Add(buttons_sizer, flag=wx.ALL | wx.ALIGN_CENTER_HORIZONTAL)
self.SetSizerAndFit(main_sizer)
@property
def opt_type(self):
return "fcfact optimization"
def build_new_inps(self):
fcfact_list = self.fcfact_ctl.getValues()
print(fcfact_list)
# Generate new list of inputs.
base_inp = self.notebook.makeInput()
return base_inp.optimize_modelcore(fcfact_list, add_icmod0=True)
class QcutOptimizationFrame(OptimizationFrame):
"""
This frame allows the user to select the l-channels and
the list of values of qcut_l to be analyzed.
"""
HELP_MSG = """\
This window allows you to change/optimize the value of the qcut parameters for
the different angular channel. Use the checkboxes to select the l-channel(s) to be
analyzed, and the other controls to specify the list of qc values to test.
"""
def __init__(self, parent, notebook, **kwargs):
"""
Args:
notebook:
Notebook containing the parameters of the template.
"""
super(QcutOptimizationFrame, self).__init__(parent, **kwargs)
# Save reference to the input panel.
self.notebook = notebook
lmax = notebook.lmax
panel = wx.Panel(self, -1)
main_sizer = wx.BoxSizer(wx.VERTICAL)
add_opts = dict(flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
# Build list of controls to allow the user to select the list of
# qcuts for the different l-channels. One can disable l-channels via checkboxes.
self.checkbox_l = [None] * (lmax + 1)
self.wxqcut_range_l = [None] * (lmax + 1)
qcut_l = notebook.makeInput().qcut_l
for l in range(lmax + 1):
sbox_sizer = wx.StaticBoxSizer(wx.StaticBox(self, -1, "Angular Channel L=%d" % l), wx.VERTICAL)
vsz = wx.BoxSizer(wx.HORIZONTAL)
self.checkbox_l[l] = check_l = wx.CheckBox(self, -1)
check_l.SetToolTipString("Enable/Disable optimization for this l-channel")
check_l.SetValue(True)
self.wxqcut_range_l[l] = qcrange_l = awx.IntervalControl(self, start=qcut_l[l], num=4, step=0.5)
vsz.Add(check_l, **add_opts)
vsz.Add(qcrange_l, **add_opts)
sbox_sizer.Add(vsz, 1, wx.ALL, 5)
main_sizer.Add(sbox_sizer, 1, flag=wx.ALL | wx.ALIGN_CENTER_HORIZONTAL)
buttons_sizer = self.make_buttons()
main_sizer.Add(buttons_sizer, flag=wx.ALL | wx.ALIGN_CENTER_HORIZONTAL)
self.SetSizerAndFit(main_sizer)
@property
def opt_type(self):
return "Qcut optimization"
def build_new_inps(self):
# Get the list of angular channels activated and the corresponding arrays.
l_list, qcvals_list = [], []
for l, (checkbox, wxrange) in enumerate(zip(self.checkbox_l, self.wxqcut_range_l)):
if checkbox.IsChecked():
l_list.append(l)
qcvals_list.append(wxrange.getValues())
#print("\nl_list:", l_list, "\nqcvals_list", qcvals_list)
# Generate new list of inputs.
base_inp = self.notebook.makeInput()
new_inps = []
for l, new_qcuts in zip(l_list, qcvals_list):
new_inps.extend(base_inp.optimize_qcuts_for_l(l=l, new_qcuts=new_qcuts))
return new_inps
class RcOptimizationFrame(OptimizationFrame):
"""
This frame allows the user to select the l-channels and
the list of values of rc_l to be analyzed.
"""
HELP_MSG = """\
This window allows you to change/optimize the value of the rc parameters (core radius)
for the different angular channel."""
def __init__(self, parent, notebook, **kwargs):
"""
Args:
notebook:
Notebook containing the parameters of the template.
"""
super(RcOptimizationFrame, self).__init__(parent, **kwargs)
panel = wx.Panel(self, -1)
main_sizer = wx.BoxSizer(wx.VERTICAL)
# Save reference to the input panel.
self.notebook = notebook
lmax = notebook.lmax
# Build list of controls to allow the user to select the list of
# qcut values for the different l-channels.
# One can disable particular l-channels via checkboxes.
self.checkbox_l = [None] * (lmax + 1)
self.wxrc_range_l = [None] * (lmax + 1)
rc_l = notebook.makeInput().rc_l
add_opts = dict(flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
for l in range(lmax + 1):
sbox_sizer = wx.StaticBoxSizer(wx.StaticBox(self, -1, "Angular Channel L=%d" % l), wx.VERTICAL)
vsz = wx.BoxSizer(wx.HORIZONTAL)
self.checkbox_l[l] = check_l = wx.CheckBox(self, -1)
check_l.SetToolTipString("Enable/Disable optimization for this l-channel")
check_l.SetValue(True)
self.wxrc_range_l[l] = qcrange_l = awx.IntervalControl(self, start=rc_l[l], num=4, step=0.05)
vsz.Add(check_l, **add_opts)
vsz.Add(qcrange_l, **add_opts)
sbox_sizer.Add(vsz, 1, wx.ALL, 5)
main_sizer.Add(sbox_sizer, 1, flag=wx.ALL | wx.ALIGN_CENTER_HORIZONTAL)
buttons_sizer = self.make_buttons()
main_sizer.Add(buttons_sizer, flag=wx.ALL | wx.ALIGN_CENTER_HORIZONTAL)
self.SetSizerAndFit(main_sizer)
@property
def opt_type(self):
return "Rc optimization"
def build_new_inps(self):
l_list, rc_list = [], []
for l, (checkbox, wxrange) in enumerate(zip(self.checkbox_l, self.wxrc_range_l)):
if checkbox.IsChecked():
l_list.append(l)
rc_list.append(wxrange.getValues())
# Generate new list of inputs.
base_inp = self.notebook.makeInput()
new_inps = []
for l, new_rcs in zip(l_list, rc_list):
new_inps.extend(base_inp.optimize_rcs_for_l(l, new_rcs))
return new_inps
def empty_field(tag, oncv_dims=None):
"""Returns an empty field."""
# Get the subclass from tag, initialize data with None and call __init__
cls = _FIELD_LIST[tag]
data = cls.make_empty_data(oncv_dims=oncv_dims)
return cls(tag, data, oncv_dims)
class Field(object):
# Flags used to define the type of field
# Subclasses should define the class attribute type
FTYPE_ROW = 1
FTYPE_TABLE = 2
FTYPE_RAGGED = 3
# TODO: Change convention cbox --> slist
parser_for_dtype = dict(
i=int,
f=float,
cbox=str,
)
def __init__(self, tag, data, oncv_dims):
"""
Args:
tag:
Tag used to identify the field.
data:
Accepts Ordered dict or List of ordered dicts with varname=value.
oncv_dims:
Dictionary with all the dimensions of the calculation.
"""
#print("tag", tag, "data", data, "oncv_dims", oncv_dims)
self.oncv_dims = AttrDict(**oncv_dims)
self.tag = tag
self.data = data
@classmethod
def make_empty_data(cls, oncv_dims=None):
"""Initialize data and fill it with None."""
if cls.ftype == cls.FTYPE_ROW:
data = OrderedDict([(k, v.get("value")) for k, v in cls.WXCTRL_PARAMS.items()])
elif cls.ftype == cls.FTYPE_TABLE:
nrows = cls.nrows_from_dims(oncv_dims)
data = nrows * [None]
for i in range(nrows):
data[i] = OrderedDict([(k, v.get("value")) for k, v in cls.WXCTRL_PARAMS.items()])
else:
raise NotImplementedError(str(cls.ftype))
return data
#@property
#def filepos(self):
# for pos, field in enumerate(_FIELD_LIST):
# if isinstance(self, field):
# return pos
# else:
# raise ValueError("Cannot find position of class:" % self.__class__.__name__)
@property
def nrows(self):
"""
Number of rows i.e. the number of lines in the section
as specified in the input file.
"""
if self.ftype == self.FTYPE_ROW:
return 1
elif self.ftype == self.FTYPE_TABLE:
return len(self.data)
else:
raise NotImplementedError()
#@property
#def cols_per_row(self):
# if self.type == self.FTYPE_RAGGED:
# raise NotImplementedError()
def __str__(self):
"""Returns a string with the input variables."""
lines = []
app = lines.append
# Some fields have a single row but we need a list in the loop below.
entries = self.data
if self.ftype == self.FTYPE_ROW:
entries = [self.data]
for i, entry in enumerate(entries):
if i == 0:
# Put comment with the name of the variables only once.
app("# " + " ".join((str(k) for k in entry.keys())))
app(" ".join(str(v) for v in entry.values()))
return "\n".join(lines)
def has_var(self, key):
"""Return True if variable belongs to self."""
if self.ftype == self.FTYPE_ROW:
return key in self.data
else:
return key in self.data[0]
def set_var(self, key, value):
"""Set the value of a variable."""
assert self.has_var(key)
if self.ftype == self.FTYPE_ROW:
self.data[key] = value
elif self.ftype == self.FTYPE_TABLE:
for r in range(self.nrows):
self.data[r][key] = value
else:
raise NotImplementedError()
def set_vars(self, ord_vars):
"""
Set the value of the variables inside a field
Args:
ord_vars:
OrderedDict or list of OrderedDict (depending on field_idx).
"""
assert len(ord_vars) == len(self.data)
if self.ftype == self.FTYPE_ROW:
#assert isinstance(ord_vars, OrderedDict)
for k, v in ord_vars.items():
self.data[k] = v
elif self.ftype == self.FTYPE_TABLE:
# List of ordered dicts.
for i, od in enumerate(ord_vars):
for k, v in od.items():
self.data[i][k] = v
else:
raise NotImplementedError()
def set_vars_from_lines(self, lines):
"""The the value of the variables from a list of strings."""
#print("About to read: ", type(self), "\nlines=\n", "\n".join(lines))