pyibis-ami 7.3.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,726 @@
1
+ """IBIS-AMI parameter parsing and configuration utilities.
2
+
3
+ Original author: David Banas <capn.freako@gmail.com>
4
+
5
+ Original date: December 17, 2016
6
+
7
+ Copyright (c) 2019 David Banas; all rights reserved World wide.
8
+ """
9
+
10
+ from ctypes import c_double
11
+ import re
12
+ from typing import Any, Callable, NewType, Optional, TypeAlias
13
+
14
+ import numpy as np
15
+ from numpy.typing import NDArray
16
+ from parsec import ParseError, generate, many, regex, string
17
+ from traits.api import Bool, Enum, HasTraits, Range, Trait, TraitType
18
+ from traitsui.api import Group, HGroup, Item, VGroup, View
19
+ from traitsui.menu import ModalButtons
20
+
21
+ from .model import AMIModelInitializer
22
+ from .parameter import AMIParamError, AMIParameter
23
+ from .reserved_parameter_names import AmiReservedParameterName, RESERVED_PARAM_NAMES
24
+
25
+ # New types and aliases.
26
+ # Parameters = NewType('Parameters', dict[str, AMIParameter] | dict[str, 'Parameters'])
27
+ # ParamValues = NewType('ParamValues', dict[str, list[Any]] | dict[str, 'ParamValues'])
28
+ # See: https://stackoverflow.com/questions/70894567/using-mypy-newtype-with-type-aliases-or-protocols
29
+ ParamName = NewType("ParamName", str)
30
+ ParamValue: TypeAlias = int | float | str | list["ParamValue"]
31
+ Parameters: TypeAlias = dict[ParamName, "'AMIParameter' | 'Parameters'"]
32
+ ParamValues: TypeAlias = dict[ParamName, "'ParamValue' | 'ParamValues'"]
33
+
34
+ AmiName = NewType("AmiName", str)
35
+ AmiAtom: TypeAlias = bool | int | float | str
36
+ AmiExpr: TypeAlias = "'AmiAtom' | 'AmiNode'"
37
+ AmiNode: TypeAlias = tuple[AmiName, list[AmiExpr]]
38
+ AmiNodeParser: TypeAlias = Callable[[str], AmiNode]
39
+ AmiParser: TypeAlias = Callable[[str], tuple[AmiName, list[AmiNode]]] # Atoms may not exist at the root level.
40
+
41
+ ParseErrMsg = NewType("ParseErrMsg", str)
42
+ AmiRootName = NewType("AmiRootName", str)
43
+ ReservedParamDict: TypeAlias = dict[AmiReservedParameterName, AMIParameter]
44
+ ModelSpecificDict: TypeAlias = dict[ParamName, "'AMIParameter' | 'ModelSpecificDict'"]
45
+
46
+ __all__ = [
47
+ "ParamName", "ParamValue", "Parameters", "ParamValues",
48
+ "AmiName", "AmiAtom", "AmiExpr", "AmiNode", "AmiNodeParser", "AmiParser",
49
+ "ami_parse", "AMIParamConfigurator"]
50
+
51
+ #####
52
+ # AMI parameter configurator.
53
+ #####
54
+
55
+
56
+ class AMIParamConfigurator(HasTraits):
57
+ """Customizable IBIS-AMI model parameter configurator.
58
+
59
+ This class can be configured to present a customized GUI to the user
60
+ for configuring a particular IBIS-AMI model.
61
+
62
+ The intended use model is as follows:
63
+
64
+ 1. Instantiate this class only once per IBIS-AMI model invocation.
65
+ When instantiating, provide the unprocessed contents of the AMI
66
+ file, as a single string. This class will take care of getting
67
+ that string parsed properly, and report any errors or warnings
68
+ it encounters, in its ``ami_parsing_errors`` property.
69
+
70
+ 2. When you want to let the user change the AMI parameter
71
+ configuration, call the ``open_gui`` member function.
72
+ (Or, just call the instance as if it were a function.)
73
+ The instance will then present a GUI to the user,
74
+ allowing him to modify the values of any *In* or *InOut* parameters.
75
+ The resultant AMI parameter dictionary, suitable for passing
76
+ into the ``ami_params`` parameter of the ``AMIModelInitializer``
77
+ constructor, can be accessed, via the instance's
78
+ ``input_ami_params`` property. The latest user selections will be
79
+ remembered, as long as the instance remains in scope.
80
+
81
+ The entire AMI parameter definition dictionary, which should *not* be
82
+ passed to the ``AMIModelInitializer`` constructor, is available in the
83
+ instance's ``ami_param_defs`` property.
84
+
85
+ Any errors or warnings encountered while parsing are available, in
86
+ the ``ami_parsing_errors`` property.
87
+ """
88
+
89
+ def __init__(self, ami_file_contents_str: str) -> None:
90
+ """
91
+ Args:
92
+ ami_file_contents_str: The unprocessed contents of the AMI file, as a single string.
93
+ """
94
+
95
+ # Super-class initialization is ABSOLUTELY NECESSARY, in order
96
+ # to get all the Traits/UI machinery setup correctly.
97
+ super().__init__()
98
+
99
+ # Parse the AMI file contents, storing any errors or warnings, and customize the view accordingly.
100
+ (err_str,
101
+ root_name,
102
+ description,
103
+ reserved_param_dict,
104
+ model_specific_dict) = parse_ami_file_contents(ami_file_contents_str)
105
+ if err_str:
106
+ raise RuntimeError(
107
+ "\n".join([
108
+ "AMI parsing error:",
109
+ err_str
110
+ ]))
111
+ if not reserved_param_dict:
112
+ raise ValueError(
113
+ "\n".join([
114
+ "No 'Reserved_Parameters' section found!",
115
+ err_str
116
+ ]))
117
+ if not model_specific_dict:
118
+ raise ValueError(
119
+ "\n".join([
120
+ "No 'Model_Specific' section found!",
121
+ err_str
122
+ ]))
123
+ gui_items, new_traits = make_gui(model_specific_dict)
124
+ trait_names = []
125
+ for trait in new_traits:
126
+ self.add_trait(trait[0], trait[1])
127
+ trait_names.append(trait[0])
128
+ self._param_trait_names = trait_names
129
+ self._root_name = root_name
130
+ self._ami_parsing_errors = err_str
131
+ self._content = gui_items
132
+ self._reserved_param_dict = reserved_param_dict
133
+ self._model_specific_dict = model_specific_dict
134
+ self._description = description
135
+
136
+ def __call__(self):
137
+ self.open_gui()
138
+
139
+ def open_gui(self):
140
+ """Present a customized GUI to the user, for parameter
141
+ customization."""
142
+ # self.configure_traits(kind='modal') # Waiting for Enthought/Traits PR1841 to be accepted.
143
+ self.configure_traits()
144
+
145
+ def default_traits_view(self):
146
+ "Default Traits/UI view definition."
147
+ view = View(
148
+ resizable=False,
149
+ buttons=ModalButtons,
150
+ title=f"{self._root_name} AMI Parameter Configurator",
151
+ )
152
+ view.set_content(self._content)
153
+ return view
154
+
155
+ def fetch_param(self, branch_names):
156
+ """Returns the parameter found by traversing 'branch_names' or None if
157
+ not found.
158
+
159
+ Note: 'branch_names' should *not* begin with 'root_name'.
160
+ """
161
+ param_dict = self.ami_param_defs
162
+ while branch_names:
163
+ branch_name = branch_names.pop(0)
164
+ if branch_name in param_dict:
165
+ param_dict = param_dict[branch_name]
166
+ else:
167
+ return None
168
+ if isinstance(param_dict, AMIParameter):
169
+ return param_dict
170
+ return None
171
+
172
+ def fetch_param_val(self, branch_names):
173
+ """Returns the value of the parameter found by traversing
174
+ 'branch_names' or None if not found.
175
+
176
+ Note: 'branch_names' should *not* begin with 'root_name'.
177
+ """
178
+ _param = self.fetch_param(branch_names)
179
+ if _param:
180
+ return _param.pvalue
181
+ return None
182
+
183
+ def set_param_val(self, branch_names, new_val):
184
+ """Sets the value of the parameter found by traversing 'branch_names'
185
+ or raises an exception if not found.
186
+
187
+ Note: 'branch_names' should *not* begin with 'root_name'.
188
+ Note: Be careful! There is no checking done here!
189
+ """
190
+
191
+ param_dict = self.ami_param_defs
192
+ while branch_names:
193
+ branch_name = branch_names.pop(0)
194
+ if branch_name in param_dict:
195
+ param_dict = param_dict[branch_name]
196
+ else:
197
+ raise ValueError(
198
+ f"Failed parameter tree search looking for: {branch_name}; available keys: {param_dict.keys()}"
199
+ )
200
+ if isinstance(param_dict, AMIParameter):
201
+ param_dict.pvalue = new_val
202
+ try:
203
+ eval(f"self.set({branch_name}_={new_val})") # pylint: disable=eval-used
204
+ except Exception: # pylint: disable=broad-exception-caught
205
+ eval(f"self.set({branch_name}={new_val})") # pylint: disable=eval-used
206
+ else:
207
+ raise TypeError(f"{param_dict} is not of type: AMIParameter!")
208
+
209
+ @property
210
+ def ami_parsing_errors(self):
211
+ """Any errors or warnings encountered, while parsing the AMI parameter
212
+ definition file contents."""
213
+ return self._ami_parsing_errors
214
+
215
+ @property
216
+ def ami_param_defs(self) -> dict[str, ReservedParamDict | ModelSpecificDict]:
217
+ """The entire AMI parameter definition dictionary.
218
+
219
+ Should *not* be passed to ``AMIModelInitializer`` constructor!
220
+ """
221
+ return {"Reserved_Parameters": self._reserved_param_dict,
222
+ "Model_Specific": self._model_specific_dict}
223
+
224
+ @property
225
+ def input_ami_params(self) -> ParamValues:
226
+ """
227
+ The dictionary of *Model Specific* AMI parameters of type 'In' or
228
+ 'InOut', along with their user selected values.
229
+
230
+ Should be passed to ``AMIModelInitializer`` constructor.
231
+ """
232
+
233
+ res: ParamValues = {}
234
+ res[ParamName("root_name")] = str(self._root_name)
235
+ params = self._model_specific_dict
236
+ for pname in params:
237
+ res.update(self.input_ami_param(params, pname))
238
+ return res
239
+
240
+ def input_ami_param(
241
+ self,
242
+ params: Parameters,
243
+ pname: ParamName,
244
+ prefix: str = ""
245
+ ) -> ParamValues:
246
+ """
247
+ Retrieve one AMI parameter value, or dictionary of subparameter values,
248
+ from the given parameter definition dictionary.
249
+
250
+ Args:
251
+ params: The parameter definition dictionary.
252
+ pname: The simple name of the parameter of interest, used by the IBIS-AMI model.
253
+
254
+ Keyword Args:
255
+ prefix: The current working parameter name prefix.
256
+
257
+ Returns:
258
+ A dictionary of parameter values indexed by non-prefixed parameter names.
259
+
260
+ Notes:
261
+ 1. The "prefix" referred to above refers to a string encoding of the
262
+ hierarchy above a particular trait. We need this hierarchy for the
263
+ sake of the ``Traits/UI`` machinery, which addresses traits by name
264
+ alone. However, the IBIS-AMI model is not expecting it. So, we have
265
+ to strip it off, before sending the result here into ``AMI_Init()``.
266
+ """
267
+
268
+ res = {}
269
+ tname = prefix + pname # This is the fully hierarchical trait name, used by the Traits/UI machinery.
270
+ param = params[pname]
271
+ if isinstance(param, AMIParameter):
272
+ if tname in self._param_trait_names: # If model specific and of type In or InOut...
273
+ # See the docs on the *HasTraits* class, if this is confusing.
274
+ # Querry for a mapped trait, first, by trying to get '<trait_name>_'. (Note the underscore.)
275
+ try:
276
+ res[pname] = self.trait_get(tname + "_")[tname + "_"]
277
+ # If we get an exception, we have an ordinary (i.e. - not mapped) trait.
278
+ except Exception: # pylint: disable=broad-exception-caught
279
+ res[pname] = self.trait_get(tname)[tname]
280
+ elif isinstance(param, dict): # We received a dictionary of subparameters, in 'param'.
281
+ subs: ParamValues = {}
282
+ for sname in param:
283
+ subs.update(self.input_ami_param(param, sname, prefix=pname + "_")) # type: ignore
284
+ res[pname] = subs
285
+ return res
286
+
287
+ @property
288
+ def info_ami_params(self):
289
+ "Dictionary of *Reserved* AMI parameter values."
290
+ return self._reserved_param_dict
291
+
292
+ def get_init(
293
+ self,
294
+ bit_time: float,
295
+ sample_interval: float,
296
+ channel_response: NDArray[np.longdouble],
297
+ ami_params: Optional[dict[str, Any]] = None
298
+ ) -> AMIModelInitializer:
299
+ """
300
+ Get a model initializer, configured by the user if necessary.
301
+ """
302
+
303
+ row_size = len(channel_response)
304
+ if ami_params:
305
+ initializer = AMIModelInitializer(
306
+ ami_params,
307
+ info_params=self.info_ami_params,
308
+ bit_time=c_double(bit_time),
309
+ row_size=row_size,
310
+ sample_interval=c_double(sample_interval)
311
+ )
312
+ else:
313
+ # This call will invoke a GUI applet for the user to interact with,
314
+ # to configure the AMI parameter values.
315
+ self()
316
+ initializer = AMIModelInitializer(
317
+ self.input_ami_params,
318
+ info_params=self.info_ami_params,
319
+ bit_time=c_double(bit_time),
320
+ row_size=row_size,
321
+ sample_interval=c_double(sample_interval)
322
+ )
323
+
324
+ # Don't try to pack this into the parentheses above!
325
+ initializer.channel_response = channel_response
326
+ return initializer
327
+
328
+
329
+ #####
330
+ # AMI file parser.
331
+ #####
332
+
333
+ # ignore cases.
334
+ whitespace = regex(r"\s+", re.MULTILINE)
335
+ comment = regex(r"\|.*")
336
+ ignore = many(whitespace | comment)
337
+
338
+
339
+ def lexeme(p):
340
+ """Lexer for words."""
341
+ return p << ignore # skip all ignored characters.
342
+
343
+
344
+ def int2tap(x):
345
+ """Convert integer to tap position."""
346
+ x = x.strip()
347
+ match x[0]:
348
+ case "-":
349
+ res = "pre" + x[1:]
350
+ case "+":
351
+ res = "post" + x[1:]
352
+ case _:
353
+ res = "post" + x
354
+ return res
355
+
356
+
357
+ lparen = lexeme(string("("))
358
+ rparen = lexeme(string(")"))
359
+ number = lexeme(regex(r"[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?"))
360
+ integ = lexeme(regex(r"[-+]?[0-9]+"))
361
+ nat = lexeme(regex(r"[0-9]+"))
362
+ # tap_ix = (integ << whitespace).parsecmap(int2tap) # Doesn't work!
363
+ # tap_ix = integ.parsecmap(int2tap) # Breaks parsing of node names that begin with a numeral!
364
+ tap_ix = integ.parsecmap(int2tap) << whitespace
365
+ symbol = lexeme(regex(r"[0-9a-zA-Z_][^\s()]*"))
366
+ true = lexeme(string("True")).result(True)
367
+ false = lexeme(string("False")).result(False)
368
+ ami_string = lexeme(regex(r'"[^"]*"'))
369
+
370
+ atom = number | symbol | ami_string | (true | false)
371
+ node_name = tap_ix ^ symbol # `tap_ix` is new and gives the tap position; negative positions are allowed.
372
+
373
+
374
+ @generate("AMI node")
375
+ def node():
376
+ "Parse AMI node."
377
+ yield lparen
378
+ label = yield node_name
379
+ values = yield many(expr)
380
+ yield rparen
381
+ return (label, values)
382
+
383
+
384
+ @generate("AMI file")
385
+ def root():
386
+ "Parse AMI file."
387
+ yield lparen
388
+ label = yield node_name
389
+ values = yield many(node)
390
+ yield rparen
391
+ return (label, values)
392
+
393
+
394
+ expr = atom | node
395
+ ami = ignore >> root
396
+ ami_parse: AmiParser = ami.parse
397
+
398
+
399
+ def proc_branch(branch):
400
+ """Process a branch in a AMI parameter definition tree.
401
+
402
+ That is, build a dictionary from a pair containing:
403
+ - a parameter name, and
404
+ - a list of either:
405
+ - parameter definition tags, or
406
+ - subparameters.
407
+
408
+ We distinguish between the two possible kinds of payloads, by
409
+ peaking at the names of the first two items in the list and noting
410
+ whether they are keys of 'AMIParameter._param_def_tag_procs'.
411
+ We have to do this twice, due to the dual use of the 'Description'
412
+ tag and the fact that we have no guarantee of any particular
413
+ ordering of subparameter branch items.
414
+
415
+ Args:
416
+ p (str, list): A pair, as described above.
417
+
418
+ Returns:
419
+ (str, dict): A pair containing:
420
+ err_str: String containing any errors or warnings encountered,
421
+ while building the parameter dictionary.
422
+ param_dict: Resultant parameter dictionary.
423
+ """
424
+ results = ("", {}) # Empty Results
425
+ if len(branch) != 2:
426
+ if not branch:
427
+ err_str = "ERROR: Empty branch provided to proc_branch()!\n"
428
+ else:
429
+ err_str = f"ERROR: Malformed item: {branch[0]}\n"
430
+ results = (err_str, {})
431
+
432
+ param_name = branch[0]
433
+ param_tags = branch[1]
434
+
435
+ if not param_tags:
436
+ err_str = f"ERROR: No tags/subparameters provided for parameter, '{param_name}'\n"
437
+ results = (err_str, {})
438
+
439
+ try:
440
+ if (
441
+ (len(param_tags) > 1)
442
+ and ( # noqa: W503
443
+ param_tags[0][0] in AMIParameter._param_def_tag_procs # pylint: disable=protected-access # noqa: W503
444
+ )
445
+ and ( # noqa: W503
446
+ param_tags[1][0] in AMIParameter._param_def_tag_procs # pylint: disable=protected-access # noqa: W503
447
+ )
448
+ ):
449
+ try:
450
+ results = ("", {param_name: AMIParameter(param_name, param_tags)})
451
+ except AMIParamError as err:
452
+ results = (str(err), {})
453
+ elif param_name == "Description":
454
+ results = ("", {"description": param_tags[0].strip('"')})
455
+ else:
456
+ err_str = ""
457
+ param_dict = {}
458
+ param_dict[param_name] = {}
459
+ for param_tag in param_tags:
460
+ temp_str, temp_dict = proc_branch(param_tag)
461
+ param_dict[param_name].update(temp_dict)
462
+ if temp_str:
463
+ err_str = (
464
+ f"Error returned by recursive call, while processing parameter, '{param_name}':\n{temp_str}"
465
+ )
466
+ results = (err_str, param_dict)
467
+
468
+ results = (err_str, param_dict)
469
+ except Exception: # pylint: disable=broad-exception-caught
470
+ print(f"Error processing branch:\n{param_tags}")
471
+ return results
472
+
473
+
474
+ def parse_ami_file_contents( # pylint: disable=too-many-locals,too-many-branches
475
+ file_contents: str
476
+ ) -> tuple[ParseErrMsg, AmiRootName, str, ReservedParamDict, ModelSpecificDict]:
477
+ """
478
+ Parse the contents of an IBIS-AMI *parameter definition* (i.e. - `*.ami`) file.
479
+
480
+ Args:
481
+ file_contents: The contents of the file, as a single string.
482
+
483
+ Example:
484
+ ::
485
+
486
+ with open(<ami_file_name>) as ami_file:
487
+ file_contents = ami_file.read()
488
+ (err_str, root_name, reserved_param_dict, model_specific_param_dict) = parse_ami_file_contents(file_contents)
489
+
490
+ Returns:
491
+ A tuple containing
492
+
493
+ 1. Any error message generated by the parser. (empty on success)
494
+
495
+ 2. AMI file "root" name.
496
+
497
+ 3. *Reserved Parameters* dictionary. (empty on failure)
498
+
499
+ - The keys of the *Reserved Parameters* dictionary are
500
+ limited to those called out in the IBIS-AMI specification.
501
+
502
+ - The values of the *Reserved Parameters* dictionary
503
+ must be instances of class ``AMIParameter``.
504
+
505
+ 4. *Model Specific Parameters* dictionary. (empty on failure)
506
+
507
+ - The keys of the *Model Specific Parameters* dictionary can be anything.
508
+
509
+ - The values of the *Model Specific Parameters* dictionary
510
+ may be either: an instance of class ``AMIParameter``, or a nested sub-dictionary.
511
+ """
512
+ try:
513
+ res = ami_parse(file_contents)
514
+ except ParseError as pe:
515
+ err_str = ParseErrMsg(f"Expected {pe.expected} at {pe.loc()} in:{pe.text[pe.index: pe.index + 20]}")
516
+ return err_str, AmiRootName(""), "", {}, {}
517
+
518
+ err_str, param_dict = proc_branch(res)
519
+ if err_str:
520
+ return (err_str, AmiRootName(""), "", {}, {})
521
+ if len(param_dict.keys()) != 1:
522
+ raise ValueError(f"Malformed AMI parameter S-exp has top-level keys: {param_dict.keys()}!")
523
+
524
+ reserved_found = False
525
+ init_returns_impulse_found = False
526
+ getwave_exists_found = False
527
+ model_spec_found = False
528
+ root_name, params = list(param_dict.items())[0]
529
+ description = ""
530
+ reserved_params_dict = {}
531
+ model_specific_dict = {}
532
+ _err_str = ""
533
+ for label in list(params.keys()):
534
+ tmp_params = params[label]
535
+ if label == "Reserved_Parameters":
536
+ reserved_found = True
537
+ for param_name in list(tmp_params.keys()):
538
+ if param_name not in RESERVED_PARAM_NAMES:
539
+ _err_str += f"WARNING: Unrecognized reserved parameter name, '{param_name}', found in parameter definition string!\n"
540
+ continue
541
+ param = tmp_params[param_name]
542
+ if param.pname == "AMI_Version":
543
+ if param.pusage != "Info" or param.ptype != "String":
544
+ _err_str += "WARNING: Malformed 'AMI_Version' parameter.\n"
545
+ elif param.pname == "Init_Returns_Impulse":
546
+ init_returns_impulse_found = True
547
+ elif param.pname == "GetWave_Exists":
548
+ getwave_exists_found = True
549
+ reserved_params_dict = tmp_params
550
+ elif label == "Model_Specific":
551
+ model_spec_found = True
552
+ model_specific_dict = tmp_params
553
+ elif label == "description":
554
+ description = str(tmp_params)
555
+ else:
556
+ _err_str += f"WARNING: Unrecognized group with label, '{label}', found in parameter definition string!\n"
557
+
558
+ if not reserved_found:
559
+ _err_str += "ERROR: Reserved parameters section not found! It is required."
560
+
561
+ if not init_returns_impulse_found:
562
+ _err_str += "ERROR: Reserved parameter, 'Init_Returns_Impulse', not found! It is required."
563
+
564
+ if not getwave_exists_found:
565
+ _err_str += "ERROR: Reserved parameter, 'GetWave_Exists', not found! It is required."
566
+
567
+ if not model_spec_found:
568
+ _err_str += "WARNING: Model specific parameters section not found!"
569
+
570
+ return (ParseErrMsg(_err_str), root_name, description, reserved_params_dict, model_specific_dict)
571
+
572
+
573
+ # Legacy client code support:
574
+ def parse_ami_param_defs(file_contents: str) -> tuple[ParseErrMsg, dict[str, Any]]:
575
+ "The legacy version of ``parse_ami_file_contents()``."
576
+ err_msg, root_name, description, reserved_params_dict, model_specific_dict = parse_ami_file_contents(file_contents)
577
+ return (err_msg, {root_name: {"description": description,
578
+ "Reserved_Parameters": reserved_params_dict,
579
+ "Model_Specific": model_specific_dict}})
580
+
581
+
582
+ def make_gui(params: ModelSpecificDict) -> tuple[Group, list[TraitType]]: # pylint: disable=too-many-locals
583
+ """
584
+ Builds top-level ``Group`` and list of ``Trait`` s from AMI parameter dictionary.
585
+
586
+ Args:
587
+ params: Dictionary of AMI parameters to be configured.
588
+
589
+ Returns:
590
+ A pair consisting of:
591
+
592
+ - the top-level ``Group`` for the ``View``, and
593
+ - a list of new ``Trait`` s created.
594
+
595
+ Notes:
596
+ 1. The dictionary passed through ``params`` may have sub-dictionaries.
597
+ The window layout will reflect this nesting.
598
+ 2. Some AMI files are written to encode the AMI parameter hierarchy
599
+ via some parameter naming scheme. This function makes a primitive attempt
600
+ to decode one particular example of this: ``<grp>_<param>``.
601
+ """
602
+
603
+ gui_items: list[Item | Group] = []
604
+ new_traits: list[tuple[str, TraitType]] = []
605
+
606
+ # Place parameters with a common prefix in their names,
607
+ # but no pre-existing enclosing group, in a ``VGroup``.
608
+ # - Generate grouped parameter names and list of unique group names.
609
+ pnames = list(params.keys())
610
+ pnames_split = list(map(lambda n: n.split('_'), pnames))
611
+ group_names = list(map(lambda xs: xs[0], pnames_split))
612
+ grouped_pnames = list(zip(pnames, group_names))
613
+ # The following doesn't preserve the parameter ordering of the AMI file!
614
+ # for group_name in set(group_names): # Iterate over unique group names.
615
+ unique_group_names = []
616
+ for group_name in group_names:
617
+ if group_name not in unique_group_names:
618
+ unique_group_names.append(group_name)
619
+ # - Process all parameters, trapping those from a non-explicit group for special processing.
620
+ for group_name in unique_group_names:
621
+ pnames_in_group = [pname for pname, grp_name in grouped_pnames if grp_name == group_name]
622
+ if len(pnames_in_group) > 1:
623
+ _gui_items: list[Item | Group] = []
624
+ for pname in pnames_in_group:
625
+ gui_item, new_trait = make_gui_items(pname, params[pname])
626
+ _gui_items.extend(gui_item)
627
+ new_traits.extend(new_trait)
628
+ gui_items.append(VGroup(*_gui_items, label=group_name, show_border=True))
629
+ else:
630
+ pname = pnames_in_group[0]
631
+ gui_item, new_trait = make_gui_items(pname, params[pname])
632
+ gui_items.extend(gui_item)
633
+ new_traits.extend(new_trait)
634
+
635
+ # Finally, split into two rows if necessary.
636
+ MAX_ITEMS_PER_ROW = 8
637
+ if len(gui_items) > MAX_ITEMS_PER_ROW:
638
+ rslt_grp = VGroup(
639
+ HGroup(*(gui_items[:MAX_ITEMS_PER_ROW])),
640
+ HGroup(*(gui_items[MAX_ITEMS_PER_ROW:])))
641
+ else:
642
+ rslt_grp = HGroup(*gui_items)
643
+
644
+ return (rslt_grp, new_traits)
645
+
646
+
647
+ def make_gui_items( # pylint: disable=too-many-locals,too-many-branches
648
+ pname: str,
649
+ param: AMIParameter | Parameters
650
+ ) -> tuple[list[Item | Group], list[tuple[str, TraitType]]]:
651
+ """
652
+ Builds list of GUI items and list of traits from AMI parameter or dictionary.
653
+
654
+ Args:
655
+ pname: Parameter or sub-group name.
656
+ param: AMI parameter or dictionary of AMI parameters to be configured.
657
+
658
+ Returns:
659
+ A pair consisting of:
660
+
661
+ - the list of GUI items for the ``View``, and
662
+ - the list of new ``Trait`` s created.
663
+
664
+ Notes:
665
+ 1. A dictionary passed through ``param`` may have sub-dictionaries.
666
+ These will be converted into sub- ``Group`` s in the returned list of GUI items.
667
+ """
668
+
669
+ if isinstance(param, AMIParameter): # pylint: disable=no-else-return
670
+ pusage = param.pusage
671
+ if pusage not in ("In", "InOut"):
672
+ return ([], [])
673
+
674
+ if param.ptype == "Boolean":
675
+ return ([Item(pname, tooltip=param.pdescription)], [(pname, Bool(param.pvalue))])
676
+
677
+ pformat = param.pformat
678
+ match pformat:
679
+ case "Value": # Value
680
+ the_trait = Trait(param.pvalue)
681
+ case "Range":
682
+ the_trait = Range(param.pmin, param.pmax, param.pvalue)
683
+ case "List":
684
+ list_tips = param.plist_tip
685
+ default = param.pdefault
686
+ if list_tips:
687
+ tmp_dict: dict[str, Any] = {}
688
+ tmp_dict.update(list(zip(list_tips, param.pvalue)))
689
+ val = list(tmp_dict.keys())[0]
690
+ if default:
691
+ for tip in tmp_dict.items():
692
+ if tip[1] == default:
693
+ val = tip[0]
694
+ break
695
+ the_trait = Trait(val, tmp_dict)
696
+ else:
697
+ val = default if default else param.pvalue[0]
698
+ the_trait = Enum([val] + param.pvalue)
699
+ case _:
700
+ raise ValueError(f"Unrecognized AMI parameter format: {pformat}, for parameter `{pname}` of type `{param.ptype}` and usage `{param.pusage}`!")
701
+ if the_trait.metadata:
702
+ the_trait.metadata.update({"transient": False}) # Required to support modal dialogs.
703
+ else:
704
+ the_trait.metadata = {"transient": False}
705
+ return ([Item(name=pname, label=pname.split("_")[-1], tooltip=param.pdescription)], [(pname, the_trait)])
706
+
707
+ else: # subparameter branch
708
+ gui_items: list[Item | Group] = []
709
+ new_traits: list[tuple[str, TraitType]] = []
710
+ subparam_names = list(param.keys())
711
+ subparam_names.sort()
712
+ group_desc = None
713
+
714
+ # Build GUI items for this branch.
715
+ for subparam_name in subparam_names:
716
+ if subparam_name == "description":
717
+ group_desc = param[subparam_name]
718
+ else:
719
+ tmp_items, tmp_traits = make_gui_items(pname + "_" + subparam_name, param[subparam_name])
720
+ gui_items.extend(tmp_items)
721
+ new_traits.extend(tmp_traits)
722
+
723
+ if group_desc:
724
+ gui_items = [Item(label=group_desc)] + gui_items
725
+
726
+ return ([VGroup(*gui_items, label=pname.split("_")[-1], show_border=True)], new_traits)