Skip to content

Commit

Permalink
a layout
Browse files Browse the repository at this point in the history
  • Loading branch information
JoschD committed Nov 13, 2023
1 parent 1e344a2 commit 96d442f
Show file tree
Hide file tree
Showing 14 changed files with 813 additions and 39 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -248,3 +248,6 @@ pyproject.toml*~
.cache
/doc/_build/*
*pycache*

# testers
tst_*
66 changes: 66 additions & 0 deletions omc3_gui/plotting/classes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@


import pyqtgraph as pg
from accwidgets.graph import StaticPlotWidget
from accwidgets.graph.widgets.plotitem import ExViewBox

class DualPlot(pg.LayoutWidget):

def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)

self.top = PlotWidget()
self.bottom = PlotWidget()

self.addWidget(self.top, row=0, col=0)
self.addWidget(self.bottom, row=1, col=0)

# self.top.setMouseMode(pg.ViewBox.RectMode)
# self.bottom.setMouseMode(pg.ViewBox.PanMode)

@property
def plots(self):
return (self.top, self.bottom)


def connect_x(self) -> None:
pass

def connect_y(self) -> None:
pass


class PlotWidget(StaticPlotWidget):

def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs, viewBox=ZoomingViewBox())

# fixes for our plots
self.setBackground("w")
self.plotItem.getViewBox().setMouseMode(ZoomingViewBox.RectMode)


class ZoomingViewBox(ExViewBox):
pass

# def mouseDragEvent(self, ev):

# if ev.button() == QtCore.Qt.RightButton:
# ev.ignore()
# else:
# pg.ViewBox.mouseDragEvent(self, ev)

# ev.accept()
# pos = ev.pos()
# if ev.button() == QtCore.Qt.RightButton:
# if ev.isFinish():
# self.rbScaleBox.hide()
# self.ax = QtCore.QRectF(
# pg.Point(ev.buttonDownPos(ev.button())), pg.Point(pos)
# )
# self.ax = self.childGroup.mapRectFromParent(self.ax)
# self.Coords = self.ax.getCoords()
# self.getdataInRect()
# self.changePointsColors()
# else:
# self.updateScaleBox(ev.buttonDownPos(), ev.pos())
42 changes: 42 additions & 0 deletions omc3_gui/sbs_matcher.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import logging
import sys
from pathlib import Path

from qtpy import QtWidgets

from omc3_gui.segment_by_segment_matcher.constants import LHC_YEARS
from omc3_gui.segment_by_segment_matcher.main import SbSGuiMainController
from omc3_gui.utils import log_handler

LOGGER = logging.getLogger(__name__)


def main(lhc_year=None, match_path=None, input_dir=None):
app = QtWidgets.QApplication(sys.argv)
app.setStyle("fusion")
main_controller = SbSGuiMainController()
if match_path is None or lhc_year is None:
lhc_year, match_path = main_controller.ask_for_initial_config(
lhc_year,
match_path,
)
if match_path is None or lhc_year is None:
return
match_path = Path(match_path)
log_handler.add_file_handler(match_path)
if lhc_year not in LHC_YEARS:
raise ValueError(f"Invalid lhc mode, must be one of {LHC_YEARS!s}")
LOGGER.info("-------------------- ")
LOGGER.info("Configuration:")
LOGGER.info(f"- LHC year: {lhc_year!s}")
LOGGER.info(f"- Match output path: {match_path!s}")
LOGGER.info("-------------------- ")
main_controller.set_match_path(match_path)
main_controller.set_lhc_mode(lhc_year)
main_controller.set_input_dir(input_dir)
main_controller.show_view()
sys.exit(app.exec_())


if __name__ == "__main__":
main(lhc_year="2018", match_path=Path("/mnt/volume/jdilly/temp/"))
43 changes: 4 additions & 39 deletions omc3_gui/segment_by_segment.py
Original file line number Diff line number Diff line change
@@ -1,42 +1,7 @@
from omc3_gui.segment_by_segment.controller import SbSController
from omc3_gui.utils.log_handler import init_logging
import logging
import sys
from pathlib import Path

from qtpy import QtWidgets

from omc3_gui.segment_by_segment_matcher.constants import LHC_YEARS
from omc3_gui.segment_by_segment_matcher.main import SbSGuiMainController
from omc3_gui.utils import log_handler

LOGGER = logging.getLogger(__name__)


def main(lhc_year=None, match_path=None, input_dir=None):
app = QtWidgets.QApplication(sys.argv)
app.setStyle("fusion")
main_controller = SbSGuiMainController()
if match_path is None or lhc_year is None:
lhc_year, match_path = main_controller.ask_for_initial_config(
lhc_year,
match_path,
)
if match_path is None or lhc_year is None:
return
match_path = Path(match_path)
log_handler.add_file_handler(match_path)
if lhc_year not in LHC_YEARS:
raise ValueError(f"Invalid lhc mode, must be one of {LHC_YEARS!s}")
LOGGER.info("-------------------- ")
LOGGER.info("Configuration:")
LOGGER.info(f"- LHC year: {lhc_year!s}")
LOGGER.info(f"- Match output path: {match_path!s}")
LOGGER.info("-------------------- ")
main_controller.set_match_path(match_path)
main_controller.set_lhc_mode(lhc_year)
main_controller.set_input_dir(input_dir)
main_controller.show_view()
sys.exit(app.exec_())


if __name__ == "__main__":
main(lhc_year="2018", match_path=Path("/mnt/volume/jdilly/temp/"))
init_logging(level=logging.DEBUG)
SbSController.run_application()
Empty file.
50 changes: 50 additions & 0 deletions omc3_gui/segment_by_segment/controller.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
from pathlib import Path
from omc3_gui.utils.base_classes import Controller
from omc3_gui.utils.dialogs import OpenDirectoriesDialog, OpenDirectoryDialog
from omc3_gui.segment_by_segment.view import SbSWindow
from omc3_gui.segment_by_segment.model import Measurement, Settings
from qtpy.QtCore import Qt, Signal, Slot
from qtpy.QtWidgets import QFileDialog
import logging

LOG = logging.getLogger(__name__)

class SbSController(Controller):

settings: Settings
_view: SbSWindow # for the IDE

def __init__(self):
super().__init__(SbSWindow())
self.connect_signals()
self.settings = Settings()
self._last_selected_optics_path = None


def add_measurement(self, measurement: Measurement):
self._view.get_measurement_list().add_item(measurement)


def connect_signals(self):
self._view.sig_load_button_clicked.connect(self.open_measurements)


@Slot()
def open_measurements(self):
LOG.debug("OpenButton Clicked. Asking for folder paths.")
filenames = OpenDirectoriesDialog(
parent=self._view,
caption="Select Optics Folders",
directory=str(self._last_selected_optics_path) if self._last_selected_optics_path else None,
).run_selection_dialog()

loaded_measurements = self._view.get_measurement_list()

LOG.debug(f"User selected {len(filenames)} files.")
for filename in filenames:
self._last_selected_optics_path = filename.parent
LOG.debug(f"User selected: {filename}")
loaded_measurements.add_item(Measurement(filename))



143 changes: 143 additions & 0 deletions omc3_gui/segment_by_segment/model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
from dataclasses import dataclass
from pathlib import Path
import types
from typing import Any, Dict, List, Sequence, Union
from accwidgets.graph import StaticPlotWidget
import pyqtgraph as pg
from omc3.segment_by_segment.segments import Segment

from typing import List
from qtpy import QtCore
from qtpy.QtCore import Qt


@dataclass
class Measurement:
measurement_dir: Path
output_dir: Path = None
elements: Dict[str, Segment] = None
segments: Dict[str, Segment] = None
model_dir: Path = None
accel: str = None
year: str = None
ring: int = None

def __str__(self):
return str(self.measurement_dir)



@dataclass
class Settings:
pass



class ItemDictModel:

def __init__(self):
self.items = {}

def try_emit(self, emit: bool = True):
if not emit:
return

if hasattr(self, "layoutChanged"):
self.layoutChanged.emit()

def update_item(self, item):
self.items[str(item)] = item
self.try_emit()

def add_item(self, item, emit: bool = True):
name = str(item)
if name in self.items.keys():
raise ValueError(f"Item {name} already exists")
self.items[name] = item
self.try_emit(emit)

def add_items(self, items: Sequence):
for item in items:
self.add_item(item, emit=False)
self.try_emit()

def remove_item(self, item, emit: bool = True):
self.items.pop(str(item))
self.try_emit(emit)

def remove_items(self, items: Sequence):
for item in items:
self.remove_item(item, emit=False)
self.try_emit()

def remove_all_items(self):
self.items = {}
self.try_emit()

def remove_item_at(self, index: int):
self.remove_item(self.get_item_at(index))

def remove_items_at(self, indices: Sequence):
self.remove_items([self.get_item_at(index) for index in indices])

def get_item_at(self, index: int) -> Any:
return list(self.items.values())[index]



class MeasurementListModel(QtCore.QAbstractListModel, ItemDictModel):

items: Dict[str, Measurement] # for the IDE

def __init__(self, *args, **kwargs):
super(QtCore.QAbstractListModel, self).__init__(*args, **kwargs)
super(ItemDictModel, self).__init__()

def data(self, index: QtCore.QModelIndex, role: int = Qt.DisplayRole):
meas: Measurement = self.get_item_at(index.row())
if role == Qt.DisplayRole: # https://doc.qt.io/qt-5/qt.html#ItemDataRole-enum
return str(meas)

if role == Qt.EditRole:
return meas

def rowCount(self, index):
return len(self.items)


class SegmentTableModel(QtCore.QAbstractTableModel, ItemDictModel):

_COLUMNS = {0: "Segment", 1: "Start", 2: "End"}
_COLUMNS_MAP = {0: "name", 1: "start", 2: "end"}

items: Dict[str, Segment]

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
super(QtCore.QAbstractTableModel, self).__init__(*args, **kwargs)
super(ItemDictModel, self).__init__()

def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole):
if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
return self._COLUMNS[section]
return super().headerData(section, orientation, role)

def rowCount(self, parent=QtCore.QModelIndex()):
return len(self.items)

def columnCount(self, parent=QtCore.QModelIndex()):
return len(self._COLUMNS)

def data(self, index, role=QtCore.Qt.DisplayRole):
i = index.row()
j = index.column()
segment: Segment = self.get_item_at(i)

if role == QtCore.Qt.DisplayRole:
return str(getattr(segment, self._COLUMNS_MAP[j]))

if role == Qt.EditRole:
return segment

def flags(self, index):
return QtCore.Qt.ItemIsEnabled
Loading

0 comments on commit 96d442f

Please sign in to comment.