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

nens / ThreeDiToolbox / #2596

24 Sep 2025 12:52PM UTC coverage: 34.763% (-0.4%) from 35.146%
#2596

push

coveralls-python

web-flow
Merge 771a6ea49 into f6f4be1e7

84 of 430 new or added lines in 42 files covered. (19.53%)

9 existing lines in 6 files now uncovered.

4880 of 14038 relevant lines covered (34.76%)

0.35 hits per line

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

12.85
/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, inbetween_polylines, below_polyline, closest_point_on_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
        mouse_scene_x = pos[0].x()
×
NEW
65
        mouse_scene_y = pos[0].y()
×
NEW
66
        mouse_point = self.plotItem.vb.mapSceneToView(pos[0])
×
67

NEW
68
        min_dist = float("inf")
×
NEW
69
        closest_substance = None
×
NEW
70
        closest_data_point = None
×
71

NEW
72
        for substance, plots in self.item_map.items():
×
NEW
73
            if len(plots) == 2:  # STACKED MODE
×
74
                # There is also a fill, need to check whether point is in trapezoids
NEW
75
                plot1 = plots[1].curves[0]
×
NEW
76
                plot2 = plots[1].curves[1]
×
NEW
77
                scene_x1_data, scene_y1_data, x1_data, y1_data = self._getPlotDataInSceneCoordinates(plot1)
×
NEW
78
                _, y2_data = plot2.getData()
×
79

NEW
80
                if inbetween_polylines(mouse_point.x(), mouse_point.y(), x1_data, y1_data, y2_data):
×
NEW
81
                    closest_substance = substance
×
82
                    # find closest point in scene coordinates of base line
NEW
83
                    _, _, idx1 = closest_point_on_polyline(mouse_scene_x, mouse_scene_y, scene_x1_data, scene_y1_data)
×
NEW
84
                    closest_data_point = QPointF(x1_data[idx1], y1_data[idx1])
×
NEW
85
                    break
×
NEW
86
            elif len(plots) == 1:  # SINGLE MODE
×
NEW
87
                item = plots[0]
×
NEW
88
                if item.opts['fillLevel'] == 0:
×
89
                    # this is the bottom plot, filled
NEW
90
                    scene_x_data, scene_y_data, x_data, y_data = self._getPlotDataInSceneCoordinates(item)
×
NEW
91
                    if below_polyline(mouse_point.x(), mouse_point.y(), x_data, y_data):
×
NEW
92
                        closest_substance = substance
×
NEW
93
                        _, _, idx = closest_point_on_polyline(mouse_scene_x, mouse_scene_y, scene_x_data, scene_y_data)
×
NEW
94
                        closest_data_point = QPointF(x_data[idx], y_data[idx])
×
95
                        # find closest point to item in scene coordinates
NEW
96
                        break
×
97
                else:
NEW
98
                    scene_x_data, scene_y_data, x_data, y_data = self._getPlotDataInSceneCoordinates(item)
×
NEW
99
                    dist, data_point = distance_to_polyline(mouse_scene_x, mouse_scene_y, scene_x_data, scene_y_data)
×
NEW
100
                    if dist < 10:
×
NEW
101
                        if dist < min_dist:
×
NEW
102
                            min_dist = dist
×
NEW
103
                            closest_substance = substance
×
NEW
104
                            closest_data_point = self.plotItem.vb.mapSceneToView(QPointF(data_point[0], data_point[1]))
×
105

NEW
106
        if closest_substance is not None:
×
NEW
107
            self.mouseLabel.setText("(%0.1f, %0.1f)" % (closest_data_point.x(), closest_data_point.y()))
×
NEW
108
            self.mouseLabel.setPos(closest_data_point.x(), closest_data_point.y())
×
NEW
109
            self.mouseMarker.setVisible(True)
×
NEW
110
            self.mouseMarker.setData([closest_data_point.x()], [closest_data_point.y()])
×
111
        else:
NEW
112
            self.mouseLabel.setText("")
×
NEW
113
            self.mouseMarker.setVisible(False)
×
114

NEW
115
        self.hover_plot.emit(closest_substance)
×
116

117
    def item_color_changed(self, color_model_item):
1✔
NEW
118
        if not self.item_map:  # No plots yet
×
NEW
119
            return
×
120

121
        # Retrieve the substance name from the model
NEW
122
        row = color_model_item.index().row()
×
NEW
123
        selected_model_item = color_model_item.model().item(row, 0)
×
NEW
124
        substance = selected_model_item.data()
×
125

NEW
126
        style, color, width = color_model_item.data()[0]
×
NEW
127
        pen = pg.mkPen(color=QColor(*color), width=width, style=style)
×
NEW
128
        self.item_map[substance][0].setPen(pen)
×
NEW
129
        fill_color = reduce_saturation(QColor(*color))
×
130

131
        # Check whether this is the bottom fill
NEW
132
        if self.item_map[substance][0].opts['fillLevel'] == 0:
×
NEW
133
            self.item_map[substance][0].setFillBrush(pg.mkBrush(fill_color))
×
134

NEW
135
        if len(self.item_map[substance]) == 2:
×
136
            # there is a fill, also change that color
NEW
137
            self.item_map[substance][1].setBrush(pg.mkBrush(fill_color))
×
138

139
    def highlight_plot(self, row):
1✔
140

NEW
141
        if not self.item_map:  # No plots yet
×
NEW
142
            return
×
143

NEW
144
        self.unhighlight_plots()
×
145

NEW
146
        hovered_model_item = self.fraction_model.item(row, 0)
×
NEW
147
        substance = hovered_model_item.data()
×
148

NEW
149
        hovered_color_item = self.fraction_model.item(row, 1)
×
150
        # Original color
NEW
151
        style, color, width = hovered_color_item.data()[1]
×
NEW
152
        highlight_color = increase_value(QColor(*color))
×
NEW
153
        pen = pg.mkPen(color=highlight_color, width=width, style=style)
×
NEW
154
        self.item_map[substance][0].setPen(pen)
×
155

156
        # Check whether this is the bottom fill
NEW
157
        if self.item_map[substance][0].opts['fillLevel'] == 0:
×
NEW
158
            self.item_map[substance][0].setFillBrush(pg.mkBrush(highlight_color))
×
159

160
        # also set fill color
NEW
161
        if len(self.item_map[substance]) == 2:
×
NEW
162
            self.item_map[substance][1].setBrush(pg.mkBrush(highlight_color))
×
163

164
    def unhighlight_plots(self):
1✔
NEW
165
        if not self.item_map:  # No plots yet
×
NEW
166
            return
×
167

NEW
168
        for row in range(self.fraction_model.rowCount()):
×
NEW
169
            substance = self.fraction_model.item(row, 0).data()
×
170
            # original color
NEW
171
            style, color, width = self.fraction_model.item(row, 1).data()[1]
×
172

NEW
173
            pen = pg.mkPen(color=QColor(*color), width=width, style=style)
×
NEW
174
            self.item_map[substance][0].setPen(pen)
×
175

NEW
176
            fill_color = reduce_saturation(QColor(*color))
×
177
            # Check whether this is the bottom fill
NEW
178
            if self.item_map[substance][0].opts['fillLevel'] == 0:
×
NEW
179
                self.item_map[substance][0].setFillBrush(pg.mkBrush(fill_color))
×
180

NEW
181
            if len(self.item_map[substance]) == 2:
×
NEW
182
                self.item_map[substance][1].setBrush(pg.mkBrush(fill_color))
×
183

184
    def fraction_selected(self, feature_id, substance_unit: str, time_unit: str, stacked: bool, volume: bool):
1✔
185
        """
186
        Retrieve info from model and create plots
187
        """
188
        self.clear_plot()
×
189

190
        substance_unit_conversion = 1.0
×
191

192
        if volume:
×
193
            # for known units, we apply basic conversion
194
            pattern = r"^(.*)/\s*(m3|l)\s*$"
×
195
            matches = re.findall(pattern, substance_unit, flags=re.IGNORECASE)
×
196
            if len(matches) == 1 and len(matches[0]) == 2:
×
197
                if matches[0][1].lower() == "l":
×
198
                    substance_unit_conversion = 1000.0
×
199
                    processed_substance_unit = matches[0][0].strip()
×
200
                    volume_label = "Load"
×
201
                elif matches[0][1].lower() == "m3":
×
202
                    substance_unit_conversion = 1.0
×
203
                    processed_substance_unit = matches[0][0].strip()
×
204
                    volume_label = "Load"
×
205
            elif substance_unit.strip() == "%":
×
206
                substance_unit_conversion = 1.0
×
207
                processed_substance_unit = "m<sup>3</sup>"
×
208
                volume_label = "Volume"
×
209
            else:  # unknown, take original unit as-is and append x m3
210
                substance_unit_conversion = 1.0
×
211
                processed_substance_unit = f"{substance_unit} ยท m<sup>3</sup>"
×
212
                volume_label = "Load"
×
213

214
        plots = self.fraction_model.create_plots(feature_id, time_unit, stacked, volume, substance_unit_conversion)
×
215
        prev_plot = None
×
NEW
216
        for substance, plot, visible in plots:
×
217
            self.item_map[substance] = [plot]
×
218
            plot.setZValue(100)
×
NEW
219
            plot.setVisible(visible)
×
UNCOV
220
            self.addItem(plot)
×
221

222
            if stacked:
×
223
                # Add fill between consecutive plots
224
                plot_color = plot.opts['pen'].color()
×
225
                # Reduce saturation for fill
NEW
226
                fill_color = reduce_saturation(plot_color)
×
227
                if not prev_plot:
×
228
                    # this is the first, just fill downward to axis
229
                    plot.setFillLevel(0)
×
230
                    plot.setFillBrush(pg.mkBrush(fill_color))
×
231
                else:
232
                    fill = pg.FillBetweenItem(plot, prev_plot, pg.mkBrush(fill_color))
×
233
                    fill.setZValue(20)
×
NEW
234
                    fill.setVisible(visible)
×
235
                    self.addItem(fill)
×
236
                    self.item_map[substance].append(fill)
×
237

238
            prev_plot = plot
×
239

240
        self.setLabel("left", volume_label if volume else "Concentration", processed_substance_unit if volume else substance_unit)
×
241
        self.plotItem.vb.menu.viewAll.triggered.emit()
×
242

243
    def _getPlotDataInSceneCoordinates(self, plot):
1✔
NEW
244
        x_data, y_data = plot.getData()
×
NEW
245
        scene_points = [self.plotItem.vb.mapViewToScene(QPointF(x, y)) for x, y in zip(x_data, y_data)]
×
246
        # Convert to numpy arrays for distance calculations
NEW
247
        scene_x_data = np.array([pt.x() for pt in scene_points])
×
NEW
248
        scene_y_data = np.array([pt.y() for pt in scene_points])
×
NEW
249
        return scene_x_data, scene_y_data, x_data, y_data
×
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