ATLAS Offline Software
structure.py
Go to the documentation of this file.
1 # Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
2 
3 import ast
4 import logging
5 from typing import Callable, Dict, List, Sequence, Set, Tuple
6 
7 from AthenaConfiguration.iconfTool.models.element import (
8  Element,
9  SingleElement,
10  GroupingElement,
11  ValueElement,
12 )
13 
14 logger = logging.getLogger(__name__)
15 INDENT = 3
16 
17 
18 class Structure:
19  def __init__(self, flags_dict: Dict, checked_elements=set()) -> None:
20  self.flags_dict: Dict = flags_dict
21  self.structure_dict: Dict = {}
22  self.checked_elements: Set = (
23  checked_elements # Set of checked elements
24  )
25  # hashed
26 
27  def generate_structure_dict(self) -> Dict:
28  """Split dictionary keys into nested structure
29  e.g. Test1.Test2: Value -> Test1: {Test2: Value}
30  """
31  structure_dict: Dict = {}
32 
33  for flag, value in self.flags_dict.items():
34  groups = flag.split(".")
35  structure_point = structure_dict
36  for i in range(len(groups) - 1):
37  if groups[i] not in structure_point:
38  structure_point[groups[i]] = {}
39  elif isinstance(structure_point[groups[i]], str):
40  structure_point[groups[i]] = {
41  structure_point[groups[i]]: {}
42  }
43  structure_point = structure_point[groups[i]]
44  if groups:
45  last = groups[-1]
46  if (
47  last in structure_point
48  and isinstance(structure_point[last], dict)
49  and isinstance(value, dict)
50  ):
51  structure_point[last].update(value)
52  else:
53  structure_point[last] = value
54  return structure_dict
55 
57  self, grouping_element: GroupingElement, structure: Dict
58  ) -> None:
59  child_x_pos = grouping_element.x_pos + INDENT
60  for child in structure:
61  try:
62  # Handles situation when list or dict is provided as a string
63  structure[child] = ast.literal_eval(structure[child])
64  except (ValueError, SyntaxError):
65  pass
66 
67  if isinstance(structure[child], dict):
68  group = GroupingElement(child, child_x_pos, grouping_element)
69  if group.hash in self.checked_elements:
70  group.set_as_checked()
71  self.generate_for_element(group, structure[child])
72  grouping_element.add_child(group)
73  elif isinstance(structure[child], list):
74  group = GroupingElement(child, child_x_pos, grouping_element)
75  if group.hash in self.checked_elements:
76  group.set_as_checked()
77  for el in structure[child]:
78  no_value_child = SingleElement(el, child_x_pos + INDENT)
79  if no_value_child.hash in self.checked_elements:
80  no_value_child.set_as_checked()
81  group.add_child(no_value_child)
82  grouping_element.add_child(group)
83  else:
84  flag = ValueElement(
85  child, child_x_pos, structure[child], grouping_element
86  )
87  if flag.hash in self.checked_elements:
88  flag.set_as_checked()
89  grouping_element.add_child(flag)
90 
91  def add_to_checked(self, element: Element) -> None:
92  hash_value = element.hash
93  self.checked_elements.add(hash_value)
94 
95  def remove_from_checked(self, element: Element) -> None:
96  hash_value = element.hash
97  if hash_value in self.checked_elements:
98  self.checked_elements.remove(hash_value)
99 
100 
102  def __init__(self, flags_dict: Dict, checked_elements: Set) -> None:
103  super().__init__(flags_dict, checked_elements)
104  self.roots_dict: Dict = {}
105  self.structure_list: List[Element] = []
106  self.filter: ComponentsStructureFilter # Filter object used in search
107 
108  def replace_references(self, element: GroupingElement) -> None:
109  element.replaced = True
110  for i, child in enumerate(element.children):
111  if isinstance(child, SingleElement):
112  ref_name = child.get_reference_name()
113  if ref_name in self.roots_dict and not element.has_parent(
114  self.roots_dict[ref_name].get_name()
115  ):
116  element.children[i] = self.roots_dict[ref_name]
117 
118  element.children[i].parent = element
119  element.update_xpos(element.x_pos)
120 
121  def generate(self, x_pos: int = 1, structure_dict=None) -> None:
122 
123  self.structure_dict = structure_dict or self.generate_structure_dict()
124  for root_name in self.structure_dict:
125  if isinstance(self.structure_dict[root_name], dict):
126  root_group = GroupingElement(root_name, x_pos)
127  if root_group.hash in self.checked_elements:
128  root_group.set_as_checked()
130  root_group, self.structure_dict[root_name]
131  )
132  self.structure_list.append(root_group)
133  self.roots_dict[root_name] = root_group
134 
136  self.structure_list, x_pos - 1
137  )
138 
139  self.sort()
141 
143  self, structure_list: List[Element], x_pos: int
144  ) -> List[Element]:
145 
146  algs = GroupingElement("Algorithms and Sequences", x_pos)
147  tools = GroupingElement("Public tools", x_pos)
148  settings = GroupingElement("Application Settings and Services", x_pos)
149 
150  new_structure_list: List[Element] = [algs, tools, settings]
151 
152  seq_names = []
153 
154  def get_ath_sequences(el) -> None:
155  if isinstance(el, GroupingElement):
156  members_obj = el.get_child_by_name("Members")
157  if members_obj:
158  assert isinstance(members_obj, GroupingElement)
159  for member in members_obj.children:
160  ref_name = member.get_reference_name()
161  seq_names.append(ref_name)
162  get_ath_sequences(self.roots_dict.get(ref_name))
163 
164  seq_names.append("AthMasterSeq")
165  get_ath_sequences(self.roots_dict["AthMasterSeq"])
166 
167  for el in structure_list:
168  if el.name == "AthMasterSeq":
169  algs.add_child(el)
170  elif (
171  el.name == "ToolSvc"
172  ): # any of ToolSvc children is not present in roots dict
173  tools.add_child(el)
174  elif el.name not in seq_names:
175  settings.add_child(el)
176 
177  return new_structure_list
178 
179  def get_list(self) -> List[Element]:
180  self.filter.reset()
181  return self.structure_list
182 
183  def filter_by_text(self, filter_text: str) -> None:
184  self.filter.generate_by_text(filter_text)
185  for element in self.structure_list:
186  assert isinstance(element, GroupingElement)
187  element.children = list(
188  filter(
189  lambda child: child.get_reference_name()
190  in self.filter.comps_to_save
191  or child not in self.roots_dict,
192  element.children,
193  )
194  )
195 
196  def sort(self) -> None:
197  self.structure_list.sort(key=lambda el: el.get_name().lower())
198  for element in self.structure_list:
199  element.sort_children()
200 
201 
203  def __init__(self, structure_dict: Dict[str, str]) -> None:
204  self.structure_dict: Dict[str, str] = structure_dict
205  self.comps_to_save: List[str] = []
206 
207  def reset(self) -> None:
208  self.comps_to_save = []
209 
210  def generate_by_text(self, filter_text: str) -> None:
211  self.reset()
212  found_elements: List[str] = []
213  self.search_elements(filter_text, found_elements)
214  if not found_elements:
215  return
216  found_elements.extend(
217  [
218  "Algorithms and Sequences",
219  "Public tools",
220  "Application Settings and Services",
221  ]
222  )
223  self.comps_to_save = found_elements
224  logger.debug(f"SEARCH - found elements: {found_elements}")
225 
226  @staticmethod
228  filter_text: str, structure_dict: Dict
229  ) -> List[Tuple[str, str]]:
230  return list(
231  filter(lambda el: filter_text in str(el), structure_dict.items())
232  )
233 
235  self, filter_text: str, found_elements: List[str]
236  ) -> None:
237  for el in self.find_text_in_dict(filter_text, self.structure_dict):
238  if el[0] not in found_elements:
239  found_elements.append(el[0])
240  self.search_elements(el[0], found_elements)
241 
243  self, elements: Sequence[Element], filter_lambda: Callable
244  ) -> None:
245  filtered = list(filter(filter_lambda, elements))
246  self.filter_children(filtered)
247 
248  @staticmethod
249  def filter_children(filtered: Sequence[Element]) -> None:
250  if len(filtered) > 0:
251  first = filtered[0]
252  if first.parent:
253  first.parent.children = list(filtered)
python.iconfTool.models.structure.Structure.generate_for_element
None generate_for_element(self, GroupingElement grouping_element, Dict structure)
Definition: structure.py:56
python.iconfTool.models.structure.ComponentsStructure.sort
None sort(self)
Definition: structure.py:196
python.iconfTool.models.structure.ComponentsStructure.structure_list
structure_list
Definition: structure.py:135
python.iconfTool.models.structure.ComponentsStructure.filter
filter
Definition: structure.py:140
python.iconfTool.models.structure.Structure.__init__
None __init__(self, Dict flags_dict, checked_elements=set())
Definition: structure.py:19
python.iconfTool.models.structure.ComponentsStructureFilter.reset
None reset(self)
Definition: structure.py:207
python.iconfTool.models.structure.ComponentsStructureFilter.__init__
None __init__(self, Dict[str, str] structure_dict)
Definition: structure.py:203
python.iconfTool.models.structure.ComponentsStructure.get_list
List[Element] get_list(self)
Definition: structure.py:179
dumpHVPathFromNtuple.append
bool append
Definition: dumpHVPathFromNtuple.py:91
covarianceTool.filter
filter
Definition: covarianceTool.py:514
python.iconfTool.models.structure.Structure
Definition: structure.py:18
PixelModuleFeMask_create_db.remove
string remove
Definition: PixelModuleFeMask_create_db.py:83
python.iconfTool.models.structure.ComponentsStructure.structure_dict
structure_dict
Definition: structure.py:123
python.iconfTool.models.structure.ComponentsStructureFilter.comps_to_save
comps_to_save
Definition: structure.py:208
python.iconfTool.models.structure.ComponentsStructure.replace_references
None replace_references(self, GroupingElement element)
Definition: structure.py:108
python.iconfTool.models.structure.ComponentsStructureFilter
Definition: structure.py:202
plotBeamSpotVxVal.range
range
Definition: plotBeamSpotVxVal.py:195
add
bool add(const std::string &hname, TKey *tobj)
Definition: fastadd.cxx:55
histSizes.list
def list(name, path='/')
Definition: histSizes.py:38
python.iconfTool.models.structure.ComponentsStructure.group_elements
List[Element] group_elements(self, List[Element] structure_list, int x_pos)
Definition: structure.py:142
python.iconfTool.models.structure.Structure.generate_structure_dict
Dict generate_structure_dict(self)
Definition: structure.py:27
python.iconfTool.models.structure.ComponentsStructureFilter.filter_children
None filter_children(Sequence[Element] filtered)
Definition: structure.py:249
CxxUtils::set
constexpr std::enable_if_t< is_bitmask_v< E >, E & > set(E &lhs, E rhs)
Convenience function to set bits in a class enum bitmask.
Definition: bitmask.h:232
python.iconfTool.models.structure.ComponentsStructure
Definition: structure.py:101
python.iconfTool.models.structure.ComponentsStructure.generate
None generate(self, int x_pos=1, structure_dict=None)
Definition: structure.py:121
TrigJetMonitorAlgorithm.items
items
Definition: TrigJetMonitorAlgorithm.py:79
python.iconfTool.models.structure.ComponentsStructureFilter.search_elements
None search_elements(self, str filter_text, List[str] found_elements)
Definition: structure.py:234
python.iconfTool.models.structure.ComponentsStructure.__init__
None __init__(self, Dict flags_dict, Set checked_elements)
Definition: structure.py:102
python.iconfTool.models.structure.ComponentsStructureFilter.find_text_in_dict
List[Tuple[str, str]] find_text_in_dict(str filter_text, Dict structure_dict)
Definition: structure.py:227
python.iconfTool.models.structure.Structure.remove_from_checked
None remove_from_checked(self, Element element)
Definition: structure.py:95
CxxUtils::reset
constexpr std::enable_if_t< is_bitmask_v< E >, E & > reset(E &lhs, E rhs)
Convenience function to clear bits in a class enum bitmask.
Definition: bitmask.h:251
get
T * get(TKey *tobj)
get a TObject* from a TKey* (why can't a TObject be a TKey?)
Definition: hcg.cxx:127
python.iconfTool.models.structure.ComponentsStructureFilter.browse_and_save_by_text
None browse_and_save_by_text(self, Sequence[Element] elements, Callable filter_lambda)
Definition: structure.py:242
str
Definition: BTagTrackIpAccessor.cxx:11
WriteBchToCool.update
update
Definition: WriteBchToCool.py:67
python.iconfTool.models.structure.ComponentsStructure.filter_by_text
None filter_by_text(self, str filter_text)
Definition: structure.py:183
python.iconfTool.models.structure.Structure.add_to_checked
None add_to_checked(self, Element element)
Definition: structure.py:91
python.iconfTool.models.structure.ComponentsStructureFilter.generate_by_text
None generate_by_text(self, str filter_text)
Definition: structure.py:210