-
Notifications
You must be signed in to change notification settings - Fork 2
/
OGP_v11.py
6007 lines (4599 loc) · 260 KB
/
OGP_v11.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from PyQt5 import QtWidgets
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QVBoxLayout
from PyQt5.uic import loadUi
from PyQt5.QtWidgets import QMainWindow
from PyQt5.QtWidgets import QListWidget, QListWidgetItem
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import QFileDialog
from PyQt5.QtGui import QStandardItemModel, QStandardItem, QFont, QColor
from PyQt5 import uic
import traceback
from matplotlib.widgets import SpanSelector
from collections import defaultdict
from matplotlib.patches import Rectangle
import json
from PyQt5.QtGui import QCursor
from PyQt5.QtCore import QSize
from PyQt5.QtGui import QColor, QPalette, QIntValidator
from PyQt5.QtCore import Qt
from PyQt5.QtCore import pyqtSignal
import copy
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QSizePolicy
from PyQt5.QtWidgets import QMessageBox
from PyQt5.QtWidgets import QDialogButtonBox
from PyQt5.QtWidgets import QInputDialog
from mpl_toolkits.mplot3d import Axes3D
import xml.etree.ElementTree as ET
from matplotlib.text import Annotation
from PyQt5 import QtGui
from PyQt5.QtWidgets import QFrame
import math
import csv
import Test_1_rc
import OpenGeoUI2
import pandas as pd
from matplotlib.ticker import FuncFormatter
import pickle
print(pd.__version__)
from sklearn.decomposition import FactorAnalysis
from sklearn.preprocessing import StandardScaler
from pandas import DataFrame
from ColumnSelectionDialog import Ui_ColumnSelectionDialog
import os
from functools import partial
from OpenGeoUI2 import Ui_MainWindow
import sys
import numpy as np
import seaborn as sns
import matplotlib.patches as mpatches
import factor_analyzer
from factor_analyzer import FactorAnalyzer
import matplotlib
matplotlib.use('Qt5Agg')
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.path import Path
from matplotlib import patches
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from matplotlib import colors as mcolors
from matplotlib.colors import LinearSegmentedColormap
import traceback
from matplotlib.cm import ScalarMappable
from matplotlib.colors import Normalize
import mplstereonet
from mplstereonet.stereonet_math import pole, plane
from mplstereonet.stereonet_axes import StereonetAxes
from matplotlib.patches import Polygon
import rasterio
from rasterio.features import geometry_mask, geometry_window
from shapely.geometry import LineString
from scipy.interpolate import griddata
from sklearn.cluster import DBSCAN
from pykrige.ok import OrdinaryKriging
from scipy.interpolate import Rbf
from scipy.spatial import ConvexHull
from scipy.spatial import distance
from PyQt5.QtWidgets import QDialog, QVBoxLayout, QComboBox, QPushButton, QColorDialog, QLabel, QSpinBox, QListView, QScrollArea, QWidget, QDoubleSpinBox, QLineEdit, QGroupBox, QHBoxLayout, QGridLayout, QFileDialog, QTableView, QApplication, QSlider, QCheckBox, QTextEdit
from PyQt5.QtWidgets import QProgressDialog
from OGP_help import HELP_TEXT
import matplotlib.transforms as mtransforms
class ColumnSelectorDialog(QDialog): # Lithology parameters window
plot_requested = pyqtSignal(dict)
def __init__(self, df):
super().__init__()
# Create a QVBoxLayout for the dialog
self.dialog_layout = QVBoxLayout(self)
# Create a QScrollArea
self.scroll = QScrollArea(self)
self.dialog_layout.addWidget(self.scroll)
# widget of the QScrollArea
self.scroll_content = QWidget(self.scroll)
self.scroll.setWidget(self.scroll_content)
self.scroll.setWidgetResizable(True) # Enable the scroll area to resize the widget
# QVBoxLayout for the content of the QScrollArea
self.layout = QVBoxLayout(self.scroll_content)
self.setWindowTitle("Column and Color Selector")
# Select lithology column
self.layout.addWidget(QLabel("Lithology Column:"))
self.lithology_combo = QComboBox()
self.lithology_combo.addItems(df.columns)
self.layout.addWidget(self.lithology_combo)
# Select from_depth column
self.layout.addWidget(QLabel("From Depth Column:"))
self.from_depth_combo = QComboBox()
self.from_depth_combo.addItems(df.columns)
self.layout.addWidget(self.from_depth_combo)
# Select to_depth column
self.layout.addWidget(QLabel("To Depth Column:"))
self.to_depth_combo = QComboBox()
self.to_depth_combo.addItems(df.columns)
self.layout.addWidget(self.to_depth_combo)
# Lithology column changed
self.lithology_combo.currentTextChanged.connect(self.lithology_column_changed)
self.from_depth_combo.currentTextChanged.connect(self.from_depth_column_changed)
self.to_depth_combo.currentTextChanged.connect(self.to_depth_column_changed)
# Hold color variables
self.color_buttons = {}
self.length_spin_boxes = {}
self.df = df
# Cancel or accept
self.buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel, self)
self.buttons.accepted.connect(self.accept)
self.buttons.rejected.connect(self.reject)
self.dialog_layout.addWidget(self.buttons)
self.setLayout(self.dialog_layout) # Set dialog_layout as the layout of the dialog
def lithology_column_changed(self, text):
self.lithology_column = text
self.update_lithology_controls()
def from_depth_column_changed(self, text):
self.from_depth_column = text
def to_depth_column_changed(self, text):
self.to_depth_column = text
def update_lithology_controls(self):
for widget in self.color_buttons.values():
self.layout.removeWidget(widget)
widget.setParent(None)
for widget in self.length_spin_boxes.values():
self.layout.removeWidget(widget)
widget.setParent(None)
self.color_buttons.clear()
self.length_spin_boxes.clear()
# Reference to self.lithology_column
unique_values = self.df[self.lithology_column].unique()
for value in unique_values:
color_button = QPushButton(f"Choose color for {value}")
color_button.clicked.connect(lambda _, v=value: self.choose_color(v))
self.layout.addWidget(color_button)
self.color_buttons[value] = color_button
length_spin_box = QDoubleSpinBox()
length_spin_box.setRange(0, 0.5) # Adjust the range
length_spin_box.setSingleStep(0.1) # Allow for decimal point precision
self.layout.addWidget(QLabel(f"Choose length for {value}:"))
self.layout.addWidget(length_spin_box)
self.length_spin_boxes[value] = length_spin_box
def choose_color(self, value):
color = QColorDialog.getColor()
if color.isValid():
self.color_buttons[value].setText(f"{value} color: {color.name()}")
def get_colors(self):
colors = {}
for value, button in self.color_buttons.items():
if ":" in button.text():
_, color = button.text().split(": ")
colors[value] = color
else:
colors[value] = 'white'
return colors
def get_lengths(self):
return {value: spin_box.value() for value, spin_box in self.length_spin_boxes.items()}
def get_parameters(self):
parameters = {
'lithology_column': self.lithology_combo.currentText(),
'from_column': self.from_depth_combo.currentText(),
'to_column': self.to_depth_combo.currentText(),
'colors': self.get_colors(),
'lengths': self.get_lengths()
}
return parameters or {}
class OrderDialog(QtWidgets.QDialog): # Change order for grpahic log window
def __init__(self, hole_ids, parent=None):
super().__init__(parent)
self.setWindowTitle("Change Order")
layout = QtWidgets.QVBoxLayout(self)
self.comboboxes = []
for _ in hole_ids:
combobox = QtWidgets.QComboBox(self)
combobox.addItems(hole_ids)
self.comboboxes.append(combobox)
layout.addWidget(combobox)
button_box = QtWidgets.QDialogButtonBox(QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel, self)
button_box.accepted.connect(self.accept)
button_box.rejected.connect(self.reject)
layout.addWidget(button_box)
self.setLayout(layout)
def get_order(self):
return [combobox.currentText() for combobox in self.comboboxes]
class LegendWindow(QtWidgets.QWidget):
def __init__(self, parameters, parent=None):
super().__init__(parent)
self.parameters = parameters
self.initUI()
def initUI(self):
layout = QtWidgets.QVBoxLayout()
for lithology, color in self.parameters['colors'].items():
color_label = QtWidgets.QLabel()
color_label.setFixedSize(20, 20)
color_label.setStyleSheet(f"background-color: {color}; border: 1px solid black;")
lithology_label = QtWidgets.QLabel(f"{lithology}")
row_layout = QtWidgets.QHBoxLayout()
row_layout.addWidget(color_label)
row_layout.addWidget(lithology_label)
layout.addLayout(row_layout)
self.setLayout(layout)
self.setWindowTitle("Lithology Legend")
self.resize(200, 400)
class ElevationDialog(QtWidgets.QDialog):
def __init__(self, column_names, parent=None):
super().__init__(parent)
self.setWindowTitle("Select Elevation Column")
layout = QtWidgets.QVBoxLayout(self)
self.comboBox = QtWidgets.QComboBox()
self.comboBox.addItems(column_names)
layout.addWidget(self.comboBox)
selectButton = QtWidgets.QPushButton("Select")
selectButton.clicked.connect(self.accept)
layout.addWidget(selectButton)
self.setLayout(layout)
def selected_column(self):
return self.comboBox.currentText()
class PlotWindow(QtWidgets.QMainWindow): # Graphic log plot window
def __init__(self, parent, data, hole_ids, parameters, initial_unit="ft"):
super().__init__()
self.setWindowModality(QtCore.Qt.NonModal)
self.data = data # Store lithology column
self.hole_ids = hole_ids # Store the list of hole IDs
self.parameters = parameters # Store the selected parameters
self.figure = Figure(figsize=(8, 12))
self.canvas = FigureCanvas(self.figure)
self.lith_depth_unit = initial_unit
self.main_window_reference = parent
# Create buttons
self.display_legend_button = QtWidgets.QPushButton("Display Legend")
self.display_legend_button.clicked.connect(self.display_legend)
self.use_elevation_button = QtWidgets.QPushButton("Use Elevation")
self.use_elevation_button.clicked.connect(self.use_elevation)
self.change_order_button = QtWidgets.QPushButton("Change Order")
self.change_order_button.clicked.connect(self.change_order)
self.save_button = QtWidgets.QPushButton("Save Plot")
self.save_button.clicked.connect(self.save_plot)
# Create a horizontal layout for the buttons
button_layout = QtWidgets.QHBoxLayout()
button_layout.addWidget(self.display_legend_button)
button_layout.addWidget(self.use_elevation_button)
button_layout.addWidget(self.change_order_button)
button_layout.addWidget(self.save_button)
# Set the main layout
layout = QtWidgets.QVBoxLayout()
layout.addLayout(button_layout) # Add the horizontal layout of buttons at the top
layout.addWidget(self.canvas) # Add the canvas below the buttons
# Create a central widget, set the layout, and make it the central widget of the window
widget = QtWidgets.QWidget()
widget.setLayout(layout)
self.setCentralWidget(widget)
# Adjust the window size
base_width = 500
max_width = 2000
required_width = base_width * len(hole_ids)
final_width = min(required_width, max_width)
self.resize(final_width, 1200)
self.create_graphic_log()
def use_elevation(self):
column_names = list(self.data.columns)
dialog = ElevationDialog(column_names, self)
if dialog.exec_():
elevation_column = dialog.selected_column()
self.calculate_and_apply_elevation_offsets(elevation_column)
self.create_graphic_log() # Recreate the graphic log with elevation adjustments
def calculate_and_apply_elevation_offsets(self, elevation_column):
# Extract elevation data for the selected holes
elevation_data = self.data[self.data['hole_id'].isin(self.hole_ids)].groupby('hole_id')[elevation_column].max()
highest_elevation = elevation_data.max()
# Calculate offsets using the correct method to iterate over Series objects
self.elevation_offsets = {hole_id: highest_elevation - elevation for hole_id, elevation in elevation_data.items()}
def updateLithDepthUnit(self, value): # Choose m of ft
self.lith_depth_unit = "ft" if value == 0 else "m" # Meter to ft slider
def create_graphic_log(self): # Function to create graphic log
# Clear Previous figure
self.figure.clear()
# Check if elevation offsets are available
elevation_offsets_available = hasattr(self, 'elevation_offsets')
# Compute the maximum depth across all selected hole_ids
max_depth = self.data[self.data['hole_id'].isin(self.hole_ids)][self.parameters['to_column']].max()
# Adjust for elevation offsets if available
if elevation_offsets_available:
max_elevation_offset = max(self.elevation_offsets.values())
max_depth += max_elevation_offset
num_holes = len(self.hole_ids)
for idx, hole_id in enumerate(self.hole_ids):
hole_data = self.data[self.data['hole_id'] == hole_id]
ax = self.figure.add_subplot(1, num_holes, idx+1)
# Apply elevation offset if available
elevation_offset = self.elevation_offsets[hole_id] if elevation_offsets_available else 0
for _, row in hole_data.iterrows():
from_depth = row[self.parameters['from_column']] - elevation_offset
to_depth = row[self.parameters['to_column']] - elevation_offset
# Rest of the plotting logic remains the same, using adjusted from_depth and to_depth
# Adjust y-axis limits based on elevation offset
if len(self.hole_ids) == 1:
hole_min_depth = min(hole_data[self.parameters['from_column']] - elevation_offset)
ax.set_ylim((max_depth - elevation_offset), hole_min_depth)
else:
ax.set_ylim(max_depth - elevation_offset, 0 - elevation_offset)
self.figure.subplots_adjust(left=0.15, wspace=0.45)
# Sore variables
previous_lithology = None
previous_end_depth = None
segment_start_depth = None
y_positions = [] # List to store y-coordinates of plotted labels
depth_range = hole_data[self.parameters['to_column']].max() - hole_data[self.parameters['from_column']].min()
label_buffer_percentage = 0.015
label_buffer = depth_range * label_buffer_percentage
# Find lith columns and colors
for _, row in hole_data.iterrows():
lithology = row[self.parameters['lithology_column']]
from_depth = row[self.parameters['from_column']]
to_depth = row[self.parameters['to_column']]
color = self.parameters['colors'].get(lithology, 'white')
length = self.parameters['lengths'].get(lithology, 0.0)
# Check if the lithology has changed
if lithology != previous_lithology:
# If the previous lithology is not None, draw the span for the previous sequence
if previous_lithology is not None:
ax.axhspan(previous_end_depth, segment_start_depth, xmin=0, xmax=prev_length, facecolor=color_prev, edgecolor='k', linewidth=0.5, alpha=0.7)
y_center = (segment_start_depth + previous_end_depth) / 2
if all(abs(y - y_center) > label_buffer for y in y_positions):
ax.text(0.45, y_center, previous_lithology, fontsize=8)
y_positions.append(y_center)
# Reset segment_start_depth for the new lithology
segment_start_depth = from_depth
color_prev = color # Store the color of the current row to be used in the next iteration
prev_length = length # Store the length of the current row to be used in the next iteration
previous_lithology = lithology
previous_end_depth = to_depth
# Plot the last segment
if previous_lithology is not None:
ax.axhspan(previous_end_depth, segment_start_depth, xmin=0, xmax=prev_length, facecolor=color_prev, edgecolor='k', linewidth=0.5, alpha=0.7)
y_center = (segment_start_depth + previous_end_depth) / 2
if all(abs(y - y_center) > label_buffer for y in y_positions):
ax.text(0.45, y_center, previous_lithology, fontsize=8)
ax.set_xlim(0, 0.7) # Full range of X-axis
ax.set_xlabel('')
ax.set_xticks([])
if self.lith_depth_unit == "ft":
ax.annotate(f'{max_depth} ft', xy=(0, max_depth), xytext=(10, -10), textcoords='offset points')
else:
ax.annotate(f'{max_depth} m', xy=(0, max_depth), xytext=(10, -10), textcoords='offset points')
ax.set_title(f"Hole ID: {hole_id}")
self.figure.subplots_adjust(left=0.15)
self.canvas.draw()
self.show()
self.setWindowTitle("Graphic Log Generator")
def change_order(self):
dialog = OrderDialog(self.hole_ids, self)
if dialog.exec_() == QtWidgets.QDialog.Accepted:
new_order = dialog.get_order()
if len(set(new_order)) != len(self.hole_ids):
# Ensure there are no duplicate selections
QtWidgets.QMessageBox.warning(self, "Invalid Order", "Please select distinct holes for each order position.")
return
self.hole_ids = new_order
self.create_graphic_log()
def save_plot(self):
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
file_name, _ = QFileDialog.getSaveFileName(self, "Save Plot", "", "All Files (*);;JPEG (*.jpeg);;PNG (*.png);;SVG (*.svg)", options=options)
if file_name:
self.figure.savefig(file_name, dpi=200)
def display_legend(self):
# Check if a legend window already exists and is visible; if so, bring it to the front
if hasattr(self, 'legendWindow') and self.legendWindow.isVisible():
self.legendWindow.raise_()
self.legendWindow.activateWindow()
else:
# Create a new legend window
self.legendWindow = LegendWindow(self.parameters)
self.legendWindow.show()
def closeEvent(self, event):
if self in self.main_window_reference.plot_windows:
self.main_window_reference.plot_windows.remove(self)
event.accept() # window close
def closeEvent(self, event):
if self in self.main_window_reference.plot_windows:
self.main_window_reference.plot_windows.remove(self)
event.accept() # window close
class DownholePlotWindow(QtWidgets.QMainWindow): # Plot window for downhole geochem
def __init__(self, main_window, data, hole_id, column_data, column_name, depth_column, plot_bars=False):
super().__init__()
self.setWindowModality(QtCore.Qt.NonModal)
# Store viariables
self.data = data
self.hole_id = hole_id
self.column_data = column_data
self.column_name = column_name
self.main_window = main_window
self.plot_bars = plot_bars
self.figure = Figure(figsize=(8, 12))
self.canvas = FigureCanvas(self.figure)
self.toolbar = NavigationToolbar(self.canvas, self)
self.depth_column = depth_column # Save depth column
self.geochem_depth_unit = "ft" # Default to feet
# Set the layout
layout = QtWidgets.QVBoxLayout()
layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
widget = QtWidgets.QWidget()
widget.setLayout(layout)
self.setCentralWidget(widget)
self.resize(400, 1000)
self.setGeometry(0, 0, 400, 1000)
self.plot()
def updategeochemDepthUnit(self, value):
self.geochem_depth_unit = "ft" if value == 0 else "m"
self.update_labels()
def closeEvent(self, event):
# Disconnect the signal for updating y-axis label
self.main_window.geochem_ft_m.valueChanged.disconnect(self.updategeochemDepthUnit)
# Construct the key for this window
window_key = f"{self.hole_id}_{self.column_name}"
# Remove the reference of this window from the geochem_plot_windows dictionary
if window_key in self.main_window.geochem_plot_windows:
del self.main_window.geochem_plot_windows[window_key]
event.accept() # let the window close
def plot(self):
self.plot_data()
self.update_labels()
self.canvas.draw()
self.show()
def plot_data(self):
# Create a mask where the column_data is not zero
mask = self.column_data != 0
# Use the mask to filter the x data
y = self.data[self.depth_column]
x = self.column_data[mask]
y = y[mask] # Ensures y-values correspond to the filtered x-values
self.ax = self.figure.add_subplot(111)
if self.plot_bars:
width = 3 # Adjust as necessary
self.ax.barh(y, x, align='center', height=width, color='gray') # Using horizontal bars
else:
self.ax.plot(x, y)
self.ax.invert_yaxis() # To display depth with min at the top and max at the bottom
# Set the y-axis limits based on the minimum and maximum depth values in the data
self.ax.set_ylim(y.max(), y.min()) # Use the actual depth data
# Set the x-axis limits based on the minimum and maximum values in the data
upper_limit = x.max() + 0.10 * x.max()
self.ax.set_xlim(0, upper_limit)
self.setWindowTitle(f"Hole: {self.hole_id} - {self.column_name}") # Updated
# make the plot fit the pop up window
self.figure.subplots_adjust(left=0.18)
def update_labels(self):
self.ax.set_xlabel(self.column_name)
self.ax.set_ylabel(f'Depth ({self.geochem_depth_unit})')
self.ax.set_title(f"Hole ID: {self.hole_id}")
class CorrelationMatrixWindow(QtWidgets.QMainWindow): # window for correlation matrix
def __init__(self, data, hole_id, tag='_ppm', parent=None):
super(CorrelationMatrixWindow, self).__init__(parent)
# Create the matplotlib Figure and FigCanvas objects.
self.hole_id = hole_id
self.fig, self.ax = plt.subplots(figsize=(9, 12))
self.canvas = FigureCanvas(self.fig)
# add save button
self.save_button = QtWidgets.QPushButton(self)
self.save_button.setText("Save plot")
# Adjust the button size and position
self.save_button.resize(100,30) # Size of button
self.save_button.move(20,20)
self.save_button.clicked.connect(self.save_plot)
# Set the layout
layout = QtWidgets.QVBoxLayout()
# Create and add the toolbar
self.toolbar = NavigationToolbar(self.canvas, self)
layout.addWidget(self.toolbar)
layout.addWidget(self.save_button)
layout.addWidget(self.canvas)
widget = QtWidgets.QWidget()
widget.setLayout(layout)
self.setCentralWidget(widget)
# Compute and draw the correlation matrix
self.draw_correlation_matrix(data, tag)
self.ax.set_title(f"Correlation Matrix - {self.hole_id}")
def draw_correlation_matrix(self, data, tag):
# Select columns with the specified tag in their names
selected_columns = [col for col in data.columns if tag in col]
data_selected = data[selected_columns]
# Compute the correlation matrix
corr_matrix = data_selected.corr()
# Generate a mask for the upper triangle
mask = np.triu(np.ones_like(corr_matrix, dtype=bool))
# Generate a custom diverging colormap
cmap = sns.diverging_palette(230, 20, as_cmap=True)
# Draw the heatmap with the mask and correct aspect ratio, without annotations
sns.heatmap(corr_matrix, mask=mask, cmap=cmap, vmax=1, vmin=-1, center=0,
square=True, linewidths=.5, cbar_kws={"shrink": .5}, ax=self.ax)
self.canvas.draw()
self.show() # Show the window
def save_plot(self):
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
file_name, _ = QFileDialog.getSaveFileName(self,"Save Plot","","All Files (*);;JPEG (*.jpeg);;PNG (*.png)", options=options)
if file_name:
self.fig.savefig(file_name)
class ColumnSelectionDialog(QtWidgets.QDialog, Ui_ColumnSelectionDialog): # Window for downhole plot selection
def __init__(self, parent=None):
super(ColumnSelectionDialog, self).__init__(parent)
self.setupUi(self)
self.plot_button.clicked.connect(self.accept)
# Initialize depth column combo box
self.depth_column_combo = QtWidgets.QComboBox(self)
# Initialize QLabel for depth column
self.depth_column_label = QLabel("Select Depth Column")
# Initialize QLabel for attributes
self.attributes_label = QLabel("Select Attributes to Plot")
# Initialize checkbox for bar plot
self.plot_bars_checkbox = QtWidgets.QCheckBox("Plot using bars", self)
# Layout to organize widgets
layout = QVBoxLayout(self)
# Add QLabel and QComboBox to layout
layout.addWidget(self.depth_column_label)
layout.addWidget(self.depth_column_combo)
# Add QLabel and QListWidget to layout
layout.addWidget(self.attributes_label)
layout.addWidget(self.plot_bars_checkbox)
layout.addWidget(self.column_listWidget)
# Add the plot button
layout.addWidget(self.plot_button)
# Set layout
self.setLayout(layout)
def load_columns(self, columns):
for column in columns:
item = QListWidgetItem(column)
item.setCheckState(Qt.Unchecked)
self.column_listWidget.addItem(item)
def load_depth_columns(self, depth_columns):
self.depth_column_combo.addItems(depth_columns)
class CrossSection(QDialog): # Cross section window
MAX_BAR_LENGTH = 50 # for auxiliary bar plot
def __init__(self, data, hole_ids, azimuth, attribute_column=None, attributes_model=None, attributes_dict=None, DEM_data=None, remove_outliers=True, remove_outliers_auxiliary=True, checkbox_add_grid_lines=True, checkbox_add_change_tick=True, upper_quantile=75.0, lower_quantile=25.0, IQR=3.0, x_buffer=120.0, y_buffer=0.05, line_width=3, selected_hole_ids_for_labels=None):
super().__init__()
print(selected_hole_ids_for_labels)
# Storing the data, hole_ids, and azimuth as instance variables
self.data = data
self.hole_ids = hole_ids
self.azimuth = azimuth
self.attribute_column = attribute_column
self.attributes_dict = attributes_dict or {}
self.categorical_encodings = {}
manage_attributes_dialog = ManageAttributesDialog(data)
self.drag_region = None
self.is_plan_view = False
self.generate_contours_flag = False
self.isolate_flag = False
self.canvases = []
self.DEM_data = DEM_data
if DEM_data is not None:
self.DEM_loaded = True
else:
self.DEM_loaded = False
self.overlay_image_state = {
'x': None,
'y': None,
'width': None,
'height': None,
}
self.remove_outliers = remove_outliers
self.upper_quantile = upper_quantile
self.lower_quantile = lower_quantile
self.IQR = IQR
self.x_buffer = x_buffer
self.y_buffer = y_buffer
self.line_width = line_width
self.selected_hole_ids_for_labels = selected_hole_ids_for_labels
print("CrossSection - selected_hole_ids_for_labels:", self.selected_hole_ids_for_labels)
self.filtered_bar_data = self.data
self.remove_outliers_auxiliary = remove_outliers_auxiliary
self.bar_vmin = None
self.bar_vmax = None
self.checkbox_add_grid_lines = checkbox_add_grid_lines
self.checkbox_add_change_tick = checkbox_add_change_tick
self.attributes_model = attributes_model
self.setup_attribute_list_view()
self.attributes_model.itemChanged.connect(self.on_attribute_selection_changed)
self.pencil_mode = False
self.sky_color = 'lightsteelblue'
self.remove_topo_and_sky = False
self.currently_drawing = False
self.drawing_lines = []
self.current_overlay_image_display = None
self.overlay_image = None
self.overlay_image_state = {'x': 0, 'y': 0, 'width': 0, 'height': 0}
self.use_user_defined_grid = False
self.filtered_grid_points = None
self.y_axis_scale_factor = 1
self.selected_hole_id_for_topo = None
# Set up the main vertical layout for the QDialog
main_layout = QVBoxLayout(self)
# Create a Figure that will hold the plot
self.figure = Figure(figsize=(10, 15))
# Create a FigureCanvasQTAgg widget that will hold the Figure
self.canvas = FigureCanvas(self.figure)
# Connect press events and click events
self.cid_key = self.canvas.mpl_connect('key_press_event', self.on_key_press)
self.cid_press = self.canvas.mpl_connect('button_press_event', self.on_mouse_press)
self.cid_move = self.canvas.mpl_connect('motion_notify_event', self.on_mouse_move)
self.cid_release = self.canvas.mpl_connect('button_release_event', self.on_mouse_release)
self.dragging_overlay = False
# Create and add the toolbar
self.toolbar = NavigationToolbar(self.canvas, self)
main_layout.addWidget(self.toolbar)
# Create a QHBoxLayout for canvas and buttons
self.layout = QHBoxLayout()
# Create a QVBoxLayout for the buttons
button_layout = QVBoxLayout()
# Add "Topo Line Settings" button
self.topo_line_settings_button = QPushButton("Topo Line Settings", self)
self.topo_line_settings_button.clicked.connect(self.on_topo_line_settings_clicked)
button_layout.addWidget(self.topo_line_settings_button)
# Add 'Y-axis Scale Factor' label and input
y_axis_scale_label = QLabel("Vertical Exaggeration")
button_layout.addWidget(y_axis_scale_label)
# QLineEdit for scale factor input
self.y_axis_scale_factor_input = QLineEdit(self)
self.y_axis_scale_factor_input.setPlaceholderText("Enter vertical exaggeration (e.g., 2)")
button_layout.addWidget(self.y_axis_scale_factor_input)
# Add hover tool
hover_tool_btn = QPushButton("Hover Tool")
hover_tool_btn.clicked.connect(self.activate_hover_tool)
button_layout.addWidget(hover_tool_btn)
# Add isolate button
self.isolate_button = QPushButton("Isolate Data", self)
self.isolate_button.clicked.connect(self.isolate)
button_layout.addWidget(self.isolate_button)
# Add image overlay
add_image_btn = QPushButton("Add Image Overlay")
add_image_btn.clicked.connect(self.add_image_overlay)
button_layout.addWidget(add_image_btn)
# Add plan view
self.toggle_view_button = QPushButton("Change to Plan View", self)
self.toggle_view_button.clicked.connect(self.toggle_view)
button_layout.addWidget(self.toggle_view_button)
# Add bar plot
self.secondary_bar_plot_button = QPushButton("Auxiliary Bar Plot", self)
self.secondary_bar_plot_button.clicked.connect(self.secondary_bar_plot)
button_layout.addWidget(self.secondary_bar_plot_button)
# Add Generate Contours button
self.generate_contours_button = QPushButton("Interpolate Contours (RBF)", self)
self.generate_contours_button.clicked.connect(self.generate_contours)
button_layout.addWidget(self.generate_contours_button)
# Add Pencil tool button
self.pencil_tool_button = QPushButton("Pencil", self)
self.pencil_tool_button.setCheckable(True) # Make the button toggleable
self.pencil_tool_button.clicked.connect(self.toggle_pencil_tool)
button_layout.addWidget(self.pencil_tool_button)
# Add "Save to CSV" button
self.save_to_csv_button = QPushButton("Export Plot to CSV", self)
self.save_to_csv_button.clicked.connect(self.on_save_to_csv_clicked)
button_layout.addWidget(self.save_to_csv_button)
# Create the QLabel for the title
attribute_list_label = QLabel("Change Attribute")
attribute_list_label.setAlignment(Qt.AlignCenter) # Center align the text
# Set the font to bold
font = attribute_list_label.font()
font.setBold(True)
attribute_list_label.setFont(font)
# Add space above the label
button_layout.addSpacing(20) # Adjust the spacing value as needed
# Add the QLabel to the layout
button_layout.addWidget(attribute_list_label)
# Add space below the label
button_layout.addSpacing(10) # Adjust the spacing value as needed
# Add the attribute list
button_layout.addWidget(self.attribute_list_view)
# Add a label for the azimuth control
azimuth_label = QLabel("Change Azimuth")
azimuth_label.setAlignment(Qt.AlignCenter) # Center align the text
button_layout.addWidget(azimuth_label)
# Set the font to bold
font = azimuth_label.font()
font.setBold(True)
azimuth_label.setFont(font)
# Add QSpinBox for azimuth
self.azimuth_spin_box = QSpinBox(self)
self.azimuth_spin_box.setRange(0, 360) # Assuming azimuth range is 0-360 degrees
# Set the value of azimuth spin box as an integer
self.azimuth_spin_box.setValue(int(self.azimuth))
self.azimuth_spin_box.valueChanged.connect(self.on_azimuth_changed)
button_layout.addWidget(self.azimuth_spin_box)
# Add "Redraw Plot" button
self.redraw_plot_button = QPushButton("Redraw Plot", self)
self.redraw_plot_button.clicked.connect(self.on_redraw_button_clicked)
button_layout.addWidget(self.redraw_plot_button)
# Add a stretch to push the buttons to the top
button_layout.addStretch(1)
# Add the QVBoxLayout to the QHBoxLayout
self.layout.addLayout(button_layout, stretch=1)
# Add the canvas to the QHBoxLayout
self.layout.addWidget(self.canvas, stretch=5)
# Add the QHBoxLayout to the main QVBoxLayout
main_layout.addLayout(self.layout)
# Set the main QVBoxLayout as the layout for the QDialog
self.setLayout(main_layout)
# Resize the QDialog
self.resize(1200, 825)
# Include maximize and minimize buttons
self.setWindowFlags(self.windowFlags() | Qt.WindowMaximizeButtonHint | Qt.WindowMinimizeButtonHint)
self.plot() # Create the plot
self.setWindowTitle("Cross Section Visualizer")
def set_y_axis_scale_factor(self):
try:
# Get scale factor from input and store it in the class variable
self.y_axis_scale_factor = float(self.y_axis_scale_factor_input.text())
# Check if scale factor is positive
if self.y_axis_scale_factor <= 0:
raise ValueError("Scale factor must be positive")
self.plot()
except ValueError as e:
QMessageBox.warning(self, "Input Error", str(e))
self.y_axis_scale_factor = 1 # Reset to default if there's an error
def on_save_to_csv_clicked(self):
# Open a file dialog to choose where to save the CSV
options = QFileDialog.Options()
fileName, _ = QFileDialog.getSaveFileName(self, "Save CSV File", "",
"CSV Files (*.csv)", options=options)
if fileName:
try:
# Save the extended data to CSV
self.export_data.to_csv(fileName, index=False)
except Exception as e:
# Handle exceptions (e.g., IOError)
print("Error saving file:", e)
def toggle_pencil_tool(self):
self.pencil_mode = self.pencil_tool_button.isChecked()
if not self.pencil_mode:
self.clear_drawings()
def on_topo_line_settings_clicked(self):
dialog = QDialog(self)
layout = QVBoxLayout(dialog)
# Color picker for the sky
color_label = QLabel("Select Sky Color:")
color_picker = QPushButton("Choose Color")
color_picker.clicked.connect(lambda: self.choose_sky_color(color_picker))
# Checkboxes for removing sky and both topo line and sky
remove_sky_checkbox = QCheckBox("Remove Sky")
remove_topo_and_sky_checkbox = QCheckBox("Remove Topo Line and Sky")
# Offset input
offset_label = QLabel("Topo Line Offset: Postive values to move up, negative values to move down")