• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

nens / ThreeDiToolbox / #2592

24 Sep 2025 08:27AM UTC coverage: 34.856% (-0.3%) from 35.146%
#2592

push

coveralls-python

web-flow
Merge 660edfaba into f6f4be1e7

80 of 381 new or added lines in 42 files covered. (21.0%)

9 existing lines in 6 files now uncovered.

4876 of 13989 relevant lines covered (34.86%)

0.35 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

14.19
/tool_fraction_analysis/fraction_plot.py
1
import re
1✔
2
from qgis.PyQt.QtGui import QColor
1✔
3
import pyqtgraph as pg
1✔
4
from qgis.PyQt.QtCore import pyqtSignal, QPointF
1✔
5
import numpy as np
1✔
6
from threedi_results_analysis.utils.geo_utils import distance_to_polyline
1✔
7
from threedi_results_analysis.utils.color import reduce_saturation, increase_value
1✔
8

9
pg.setConfigOption("background", "w")
1✔
10
pg.setConfigOption("foreground", "k")
1✔
11
from qgis.PyQt.QtCore import Qt
1✔
12
from threedi_results_analysis.threedi_plugin_model import ThreeDiPluginModel
1✔
13
from threedi_results_analysis.tool_fraction_analysis.fraction_model import FractionModel
1✔
14

15

16
class FractionPlot(pg.PlotWidget):
1✔
17
    hover_plot = pyqtSignal(str)
1✔
18

19
    def __init__(self, parent, result_model: ThreeDiPluginModel, fraction_model: FractionModel):
1✔
20
        super().__init__(parent)
×
21
        self.showGrid(True, True, 0.5)
×
NEW
22
        self.proxy = pg.SignalProxy(self.scene().sigMouseMoved, rateLimit=10, slot=self.mouse_moved)
×
23
        self.fraction_model = fraction_model
×
24
        self.result_model = result_model
×
25
        # map from substance name to (list of) plot
26
        self.item_map = {}
×
27
        self.setLabel("bottom", "Time", "hrs")
×
28
        self.setLabel("left", "Concentration", "")
×
29
        self.getAxis("left").enableAutoSIPrefix(False)
×
NEW
30
        self.mouseLabel = pg.TextItem(text="", anchor=(1, 1), color=(0, 0, 0))
×
31

NEW
32
        self.mouseMarker = pg.ScatterPlotItem(
×
33
            [0], [0],
34
            symbol='o',
35
            size=12,
36
            brush='r',
37
            pen='k'
38
        )
NEW
39
        self.mouseMarker.setZValue(20)
×
NEW
40
        self.mouseMarker.setVisible(False)
×
NEW
41
        self.addItem(self.mouseMarker)
×
NEW
42
        self.addItem(self.mouseLabel)
×
43

44
    def clear_plot(self):
1✔
45
        self.clear()
×
46
        self.item_map.clear()
×
47
        self.setLabel("left", "Concentration", "")
×
NEW
48
        self.addItem(self.mouseMarker)
×
NEW
49
        self.addItem(self.mouseLabel)
×
NEW
50
        self.mouseLabel.setText("")
×
NEW
51
        self.mouseLabel.setZValue(200)
×
NEW
52
        self.mouseMarker.setVisible(False)
×
NEW
53
        self.mouseMarker.setZValue(200)
×
54

55
    def item_checked(self, model_item):
1✔
NEW
56
        if not self.item_map:  # No plots yet
×
NEW
57
            return
×
58
        substance = model_item.data()
×
59
        for plot in self.item_map[substance]:
×
NEW
60
            plot.setVisible(model_item.checkState() == Qt.CheckState.Checked)
×
61

62
    def mouse_moved(self, pos):
1✔
63
        # As we are using a ProxySignal, we get a list of events
NEW
64
        x = pos[0].x()
×
NEW
65
        y = pos[0].y()
×
66
        # find closest plot (if any) in scene coordinates (not data point)
NEW
67
        min_dist = float("inf")
×
NEW
68
        closest_substance = None
×
NEW
69
        closest_data_point = None
×
NEW
70
        for item in self.plotItem.listDataItems():
×
NEW
71
            x_data, y_data = item.getData()
×
72

73
            # Convert data points to scene coordinates
NEW
74
            scene_points = [self.plotItem.vb.mapViewToScene(QPointF(x, y)) for x, y in zip(x_data, y_data)]
×
75
            # Convert to numpy arrays for distance calculations
NEW
76
            scene_x_data = np.array([pt.x() for pt in scene_points])
×
NEW
77
            scene_y_data = np.array([pt.y() for pt in scene_points])
×
78

NEW
79
            dist, data_point = distance_to_polyline(x, y, scene_x_data, scene_y_data)
×
NEW
80
            if dist < 10:
×
NEW
81
                if dist < min_dist:
×
NEW
82
                    min_dist = dist
×
83
                    # Check which substance this plot corresponds to
NEW
84
                    for substance, plots in self.item_map.items():
×
NEW
85
                        for plot in plots:
×
NEW
86
                            if plot is item:
×
NEW
87
                                closest_substance = substance
×
NEW
88
                                closest_data_point = self.plotItem.vb.mapSceneToView(QPointF(data_point[0], data_point[1]))
×
NEW
89
                                break
×
NEW
90
                assert closest_substance  # We should always find a plot
×
91

NEW
92
        if closest_substance is not None:
×
NEW
93
            self.mouseLabel.setText("(%0.1f, %0.1f)" % (closest_data_point.x(), closest_data_point.y()))
×
NEW
94
            self.mouseLabel.setPos(closest_data_point.x(), closest_data_point.y())
×
NEW
95
            self.mouseMarker.setVisible(True)
×
NEW
96
            self.mouseMarker.setData([closest_data_point.x()], [closest_data_point.y()])
×
97
        else:
NEW
98
            self.mouseLabel.setText("")
×
NEW
99
            self.mouseMarker.setVisible(False)
×
100

NEW
101
        self.hover_plot.emit(closest_substance)
×
102

103
    def item_color_changed(self, color_model_item):
1✔
NEW
104
        if not self.item_map:  # No plots yet
×
NEW
105
            return
×
106

107
        # Retrieve the substance name from the model
NEW
108
        row = color_model_item.index().row()
×
NEW
109
        selected_model_item = color_model_item.model().item(row, 0)
×
NEW
110
        substance = selected_model_item.data()
×
111

NEW
112
        style, color, width = color_model_item.data()[0]
×
NEW
113
        pen = pg.mkPen(color=QColor(*color), width=width, style=style)
×
NEW
114
        self.item_map[substance][0].setPen(pen)
×
115

NEW
116
        if len(self.item_map[substance]) == 2:
×
117
            # there is a fill, also change that color
NEW
118
            fill_color = reduce_saturation(QColor(*color))
×
NEW
119
            self.item_map[substance][1].setBrush(pg.mkBrush(fill_color))
×
120

121
    def highlight_plot(self, row):
1✔
122

NEW
123
        if not self.item_map:  # No plots yet
×
NEW
124
            return
×
125

NEW
126
        self.unhighlight_plots()
×
127

NEW
128
        hovered_model_item = self.fraction_model.item(row, 0)
×
NEW
129
        substance = hovered_model_item.data()
×
130

NEW
131
        hovered_color_item = self.fraction_model.item(row, 1)
×
132
        # Original color
NEW
133
        style, color, width = hovered_color_item.data()[1]
×
NEW
134
        highlight_color = increase_value(QColor(*color))
×
NEW
135
        pen = pg.mkPen(color=highlight_color, width=width, style=style)
×
NEW
136
        self.item_map[substance][0].setPen(pen)
×
137
        # also set fill color
NEW
138
        if len(self.item_map[substance]) == 2:
×
NEW
139
            self.item_map[substance][1].setBrush(pg.mkBrush(highlight_color))
×
140

141
    def unhighlight_plots(self):
1✔
NEW
142
        if not self.item_map:  # No plots yet
×
NEW
143
            return
×
144

NEW
145
        for row in range(self.fraction_model.rowCount()):
×
NEW
146
            substance = self.fraction_model.item(row, 0).data()
×
147
            # original color
NEW
148
            style, color, width = self.fraction_model.item(row, 1).data()[1]
×
149

NEW
150
            pen = pg.mkPen(color=QColor(*color), width=width, style=style)
×
NEW
151
            self.item_map[substance][0].setPen(pen)
×
NEW
152
            if len(self.item_map[substance]) == 2:
×
NEW
153
                fill_color = reduce_saturation(QColor(*color))
×
NEW
154
                self.item_map[substance][1].setBrush(pg.mkBrush(fill_color))
×
155

156
    def fraction_selected(self, feature_id, substance_unit: str, time_unit: str, stacked: bool, volume: bool):
1✔
157
        """
158
        Retrieve info from model and create plots
159
        """
160
        self.clear_plot()
×
161

162
        substance_unit_conversion = 1.0
×
163

164
        if volume:
×
165
            # for known units, we apply basic conversion
166
            pattern = r"^(.*)/\s*(m3|l)\s*$"
×
167
            matches = re.findall(pattern, substance_unit, flags=re.IGNORECASE)
×
168
            if len(matches) == 1 and len(matches[0]) == 2:
×
169
                if matches[0][1].lower() == "l":
×
170
                    substance_unit_conversion = 1000.0
×
171
                    processed_substance_unit = matches[0][0].strip()
×
172
                    volume_label = "Load"
×
173
                elif matches[0][1].lower() == "m3":
×
174
                    substance_unit_conversion = 1.0
×
175
                    processed_substance_unit = matches[0][0].strip()
×
176
                    volume_label = "Load"
×
177
            elif substance_unit.strip() == "%":
×
178
                substance_unit_conversion = 1.0
×
179
                processed_substance_unit = "m<sup>3</sup>"
×
180
                volume_label = "Volume"
×
181
            else:  # unknown, take original unit as-is and append x m3
182
                substance_unit_conversion = 1.0
×
183
                processed_substance_unit = f"{substance_unit} ยท m<sup>3</sup>"
×
184
                volume_label = "Load"
×
185

186
        plots = self.fraction_model.create_plots(feature_id, time_unit, stacked, volume, substance_unit_conversion)
×
187
        prev_plot = None
×
NEW
188
        for substance, plot, visible in plots:
×
189
            self.item_map[substance] = [plot]
×
190
            plot.setZValue(100)
×
NEW
191
            plot.setVisible(visible)
×
UNCOV
192
            self.addItem(plot)
×
193

194
            if stacked:
×
195
                # Add fill between consecutive plots
196
                plot_color = plot.opts['pen'].color()
×
197
                # Reduce saturation for fill
NEW
198
                fill_color = reduce_saturation(plot_color)
×
199
                if not prev_plot:
×
200
                    # this is the first, just fill downward to axis
201
                    plot.setFillLevel(0)
×
202
                    plot.setFillBrush(pg.mkBrush(fill_color))
×
203
                else:
204
                    fill = pg.FillBetweenItem(plot, prev_plot, pg.mkBrush(fill_color))
×
205
                    fill.setZValue(20)
×
NEW
206
                    fill.setVisible(visible)
×
207
                    self.addItem(fill)
×
208
                    self.item_map[substance].append(fill)
×
209

210
            prev_plot = plot
×
211

212
        self.setLabel("left", volume_label if volume else "Concentration", processed_substance_unit if volume else substance_unit)
×
213
        self.plotItem.vb.menu.viewAll.triggered.emit()
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc