Source code for kicad2ems.gui.viewer

"""
The Viewer: everything about the board and its fields in one page.

    Plan    the board from above: one layer's copper, a solver's mesh on it, the
            ports
    2D      a cut through a field dump, with its values (time frames, phases,
            live while openEMS runs)
    3D      the board in 3D: copper, vias, a solver's mesh, plane and volume
            dumps in place, the far field
    Images  the plots a run wrote (the openEMS mesh with its side views, the
            model, the line model)

The line model is an overlay of Plan and 3D: its sections coloured by Z0 against
the ports' impedance, listed beside the view with their Z0, length, delay and
eeff. Pick a section in the list, or click it in the plan: both views mark it.
The views a folder has nothing for are disabled.

The field across the section picked is a page of its own, the window's Section
(Viewer.section, a SectionView: the window puts it in a dock under the board, so
the plan and the section are seen together). It is solved only while that page
is in view (set_section_shown); sections(bool) says whether the folder loaded
has any.
"""
import glob, os
from PySide6.QtCore import Qt, QSignalBlocker, Signal
from PySide6.QtGui import QColor, QPainter, QLinearGradient, QPixmap, QIcon
from PySide6.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QToolButton,
                               QButtonGroup, QStackedWidget, QSplitter,
                               QTreeWidget, QTreeWidgetItem, QCheckBox, QLabel,
                               QHeaderView, QSizePolicy)
from kicad2ems.core import overlay as ov
from .fieldtab import FieldsTab
from .panels import ImagePanel
from .planview import PlanView
from .sectionview import SectionView
from .volumetab import VolumeTab

# the buttons' order: the board flat, a field in a cut, 3D, pictures
VIEWS = ('Plan', '2D', '3D', 'Images')
TIPS = {
    '3D': 'the board in 3D: copper, a solver\'s mesh, the line model, dumps in '
          'place, the far field',
    'Plan': 'the board from above: one layer, a solver\'s mesh, the line model '
            '(hover, click a section)',
    '2D': 'a field dump in 2D: a cut through it, with its values',
    'Images': 'the plots the run wrote: the openEMS mesh and its side views, '
              'the model, the line model'
}


[docs] class Z0Legend(QWidget): """The Z0 colours: blue below the ports' impedance, grey at it, red above.""" def __init__(self): super().__init__() self.ref, self.half = 50.0, 10.0 self.setMinimumHeight(34) self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) def set_range(self, ref, half): self.ref, self.half = ref, half self.update() def paintEvent(self, _): p = QPainter(self) w, h = self.width(), 12 g = QLinearGradient(0, 0, w, 0) for t in (0.0, 0.5, 1.0): r, gg, b = ov.z0_colour(self.ref + (2 * t - 1) * self.half, self.ref, self.half) g.setColorAt(t, QColor.fromRgbF(r, gg, b)) p.fillRect(0, 2, w, h, g) p.setPen(QColor('#333')) y = h + 16 p.drawText(0, y, f"{self.ref - self.half:.0f} Ω") mid = f"Z0 {self.ref:.0f} Ω" p.drawText(int(w / 2 - p.fontMetrics().horizontalAdvance(mid) / 2), y, mid) right = f"{self.ref + self.half:.0f} Ω" p.drawText(w - p.fontMetrics().horizontalAdvance(right) - 1, y, right)
[docs] class Viewer(QWidget): view_changed = Signal(str) # a folder was loaded: whether its line model has cross-sections sections = Signal(bool) def __init__(self, win=None): super().__init__() self.win, self.out, self.lines = win, None, None self.cuts, self.volume, self.plan, self.section = (FieldsTab(win), VolumeTab(win), PlanView(), SectionView()) self.images = ImagePanel( 'the plots of a preview or a run: the openEMS mesh, the model, the ' 'line model' ) lay = QVBoxLayout(self) lay.setContentsMargins(0, 0, 0, 0) bar = QHBoxLayout() self.buttons, group = {}, QButtonGroup(self) group.setExclusive(True) for name in VIEWS: b = QToolButton(text=name, checkable=True, toolTip=TIPS[name], minimumWidth=56) b.clicked.connect(lambda _=False, n=name: self.set_view(n)) group.addButton(b) bar.addWidget(b) self.buttons[name] = b bar.addSpacing(12) self.lines_on = QCheckBox( 'Line model', checked=True, toggled=self._lines_toggled, toolTip="the line model's sections over the board, coloured by Z0") self.note = QLabel('', styleSheet='color: gray') bar.addWidget(self.lines_on) bar.addStretch(1) bar.addWidget(self.note) lay.addLayout(bar) self.stack = QStackedWidget() self.views = { '3D': self.volume, 'Plan': self.plan, '2D': self.cuts, 'Images': self.images } self._section_on = False # the Section page is in view (its dock says) for w in self.views.values(): self.stack.addWidget(w) side = QWidget() sl = QVBoxLayout(side) sl.setContentsMargins(4, 0, 0, 0) sl.addWidget(QLabel('<b>Line model</b>')) self.legend = Z0Legend() sl.addWidget(self.legend) self.tree = QTreeWidget(rootIsDecorated=True, uniformRowHeights=True) self.tree.setHeaderLabels( ['section', 'Z0 (Ω)', 'mm', 'ps', 'εeff', 'by']) self.tree.headerItem().setToolTip( 5, "where its Z0 came from: the formula, or the field solver") self.tree.header().setSectionResizeMode(0, QHeaderView.Interactive) self.tree.header().setStretchLastSection(False) self.tree.setColumnWidth(0, 170) for c in range(1, 6): self.tree.header().setSectionResizeMode( c, QHeaderView.ResizeToContents) self.tree.itemSelectionChanged.connect(self._tree_picked) sl.addWidget(self.tree, 1) self.detail = QLabel(' ', wordWrap=True, textInteractionFlags=Qt.TextSelectableByMouse) sl.addWidget(self.detail) self.side = side self.split = QSplitter() self.split.setObjectName('viewer') self.split.addWidget(self.stack) self.split.addWidget(side) self.split.setStretchFactor(0, 1) self.split.setCollapsible(0, False) self.split.setSizes([880, 380]) lay.addWidget(self.split, 1) self.plan.selected.connect(lambda i: self.select(i, source='plan')) self._picked = None self._items = {} # the board as drawn (show_layout); what each view has to show (load) self.drawn, self._has = None, {} # OpenGL that imports but cannot make a context (a display without it, # offscreen): the 3D view as if there were no OpenGL, the Plan in front # (the window had stayed on an empty 3D view, saying so) said = self.volume.view.on_error def no_gl(why): said(why) self.volume.gl = None self._enable(dict(self._has, **{'3D': False})) if self.view() == '3D': self.set_view('Plan') self.volume.view.on_error = no_gl self.set_view('3D' if self.volume.gl is not None else 'Plan') self._fit() # ---- data ----
[docs] def load(self, out_dir): """A results folder in every view; the first view with something in it shown unless the one shown still has. False: nothing to show.""" self.out = out_dir self.lines = ov.load_lines(out_dir) self.volume.set_lines(self.lines) three = self.volume.load(out_dir) plan = ran = self.plan.load(out_dir, self.lines) # a folder without a board: the board as drawn if not plan and self.drawn is not None: plan = self.plan.set_board(self.drawn, None, {}) self.cuts.load(out_dir) imgs = [p for p in sorted(glob.glob(os.path.join(out_dir, '*.png'))) if p.endswith(('_model.png', '_mesh.png', '_tlines.png'))] self.images.show_images(imgs) self._fill_tree() self.detail.setText(' ') # a new folder: nothing selected self._picked = None self.section.show_section(None) has = { '3D': self.volume.gl is not None and bool(three or ran), 'Plan': plan, '2D': bool(self.cuts.srcs), 'Images': bool(imgs) } self._enable(has) cur = self.view() if not has.get(cur): # volume or plane dumps vol = self.volume.gl is not None and bool(self.volume.srcs) order = (['3D', 'Plan', '2D', 'Images'] if (vol or not self.cuts.srcs) else ['2D', '3D', 'Plan', 'Images']) self.set_view(next((n for n in order if has[n]), cur)) self._fit() self.sections.emit(self.has_sections()) return any(has.values())
[docs] def clear(self): """No run's results: the board as drawn (if any) in the plan, the other views off (another board chosen: the last one's run had stayed in the pages).""" self.out, self.lines = None, None self.images.show_images([]) self.detail.setText(' ') self._picked = None self.section.show_section(None) plan = self.plan.set_board(self.drawn, None, {}) self._enable({'3D': False, 'Plan': plan, '2D': False, 'Images': False}) if plan: self.set_view('Plan') self.sections.emit(False)
[docs] def has_sections(self): """Whether the folder shown has a line model with cross-sections to solve (the Section page's).""" return any( e.get('section') for e in (self.lines or {}).get('elements', []))
[docs] def show_layout(self, layout): """The board as drawn (kicad2ems.core.layout; None: none), in the plan wherever no run's board is: now, and after a folder without one is loaded. False: the plan shows no board.""" self.drawn = layout shown = self.plan.board # a run's board is there: it stays if shown and not shown.get('layout_of'): return True plan = self.plan.set_board(layout, None, {}) self._enable(dict(self._has, Plan=plan)) # the view shown has nothing: the plan has if plan and not self._has.get(self.view()): self.set_view('Plan') return plan
def _enable(self, has): """What each view has to show ({view: bool}): the buttons of those that have nothing disabled.""" self._has = has for n, b in self.buttons.items(): b.setEnabled(bool(has.get(n)))
[docs] def show_dump(self, label): """The dump of that label as the one the 2D and 3D views show (a folder's default is its first).""" for view in (self.cuts, self.volume): labels = [s.label for s in view.srcs] if (label in labels and view.dump.currentIndex() != labels.index(label)): view.dump.setCurrentIndex(labels.index(label))
[docs] def follow(self, out_dir): """A running simulation's newest field frames (the 2D view's live mode).""" self.cuts.follow(out_dir)
def _fill_tree(self): with QSignalBlocker(self.tree): self.tree.clear() self._items = {} d = self.lines if not d: return ref, half = ov.reference(d), ov.span(d) self.legend.set_range(ref, half) els, used = d['elements'], set() def row(parent, e): z0 = e.get('z0') it = QTreeWidgetItem([ e.get('label') or e.get('kind', ''), f"{z0:.1f}" if z0 else '', f"{e['length']:.2f}" if e.get('length') is not None else '', f"{e['delay_ps']:.1f}" if e.get('delay_ps') else '', f"{e['eeff']:.2f}" if e.get('eeff') else '', {'formula': 'formula', 'cut': 'field', 'cpwg': 'field'}.get(e.get('source'), '') ]) swatch = QPixmap(12, 12) swatch.fill(QColor.fromRgbF(*ov.z0_colour(z0, ref, half))) it.setIcon(0, QIcon(swatch)) it.setData(0, Qt.UserRole, e['id']) it.setToolTip(0, ov.describe(e)) parent.addChild(it) self._items.setdefault(e['id'], it) for p in d.get('paths', []): top = QTreeWidgetItem([f"{p['port']} → {p.get('to') or 'end'}"]) self.tree.addTopLevelItem(top) for i in p['ids']: if els[i].get('kind') != 'coupling': row(top, els[i]) used.add(i) top.setExpanded(True) rest = [ e for e in els if e['id'] not in used and e.get('kind') != 'coupling' ] if rest: top = QTreeWidgetItem(['other pieces']) self.tree.addTopLevelItem(top) for e in rest: row(top, e) # ---- views ---- def set_view(self, name): self.stack.setCurrentWidget(self.views[name]) for n, b in self.buttons.items(): b.setChecked(n == name) self._fit() self.view_changed.emit(name) def view(self): return next(n for n, w in self.views.items() if self.stack.currentWidget() is w) def _fit(self): """The section list where it means something: a line model, shown, in the 3D or plan view.""" on = (bool(self.lines) and self.view() in ('3D', 'Plan') and self.lines_on.isChecked()) self.side.setVisible(on) self.lines_on.setVisible( bool(self.lines) and self.view() in ('3D', 'Plan')) n = len([ e for e in (self.lines or {}).get('elements', []) if e.get('kind') != 'coupling' ]) self.note.setText(f"{n} line-model sections" if self.lines else ( 'no line model' if self.out else '')) def _lines_toggled(self, on): self.plan.set_lines_visible(on) if self.volume.gl is not None: self.volume.lines_on.setChecked(on) self._fit() # ---- the selected section ---- def _tree_picked(self): its = self.tree.selectedItems() i = its[0].data(0, Qt.UserRole) if its else None if i is not None: self.select(i, source='tree')
[docs] def select(self, i, source=None): """Select a section in every view (i None: none).""" if source != 'plan': self.plan.select(i) self.volume.select(i) if source != 'tree': with QSignalBlocker(self.tree): self.tree.clearSelection() if i in self._items: self._items[i].setSelected(True) self.tree.scrollToItem(self._items[i]) self.detail.setText( ov.describe(self.lines['elements'][i]) if ( i is not None and self.lines) else ' ') self._picked = i if self._section_on: self._show_section()
[docs] def set_section_shown(self, on): """The Section page came into view (or went out of it): the section picked is solved only while it is.""" self._section_on = bool(on) if on: self._show_section()
def _show_section(self): """The Section page on the section picked; solved only here, while that page is in view.""" i = self._picked e = (self.lines['elements'][i] if (i is not None and self.lines) else None) if e is not self.section.e: self.section.show_section(e) @property def selected(self): return self.plan.sel