프로젝트

일반

사용자정보

통계
| 브랜치(Branch): | 개정판:

hytos / DTI_PID / DTI_PID / HMBDialog.py @ 46d5088b

이력 | 보기 | 이력해설 | 다운로드 (11.4 KB)

1
# coding: utf-8
2
"""This is HMB dialog module"""
3
import os
4
import sys
5

    
6
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Commands'))
7
import FenceCommand
8

    
9
from PyQt5.QtCore import *
10
from PyQt5.QtGui import *
11
from PyQt5.QtWidgets import *
12
import openpyxl
13
from openpyxl.styles import *
14

    
15
from AppDocData import AppDocData, Config
16

    
17
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Shapes'))
18

    
19

    
20
class HMBDelegate(QStyledItemDelegate):
21
    def createEditor(self, parent, option, index):
22
        editor = super(HMBDelegate, self).createEditor(parent, option, index)
23
        if index.column() != 0 and index.column() != 1:
24
            return editor
25

    
26

    
27
class HmbModel(QStandardItemModel):
28
    def __init__(self, parent=None, *args):
29
        QStandardItemModel.__init__(self, parent, *args)
30

    
31
    '''
32
    def data(self, index, role):
33
        if not index.isValid():
34
            return None
35
        if role in [Qt.EditRole]:
36
            print('a')
37

38
        return super(HmbModel, self).data(index, role)
39
    '''
40

    
41
class QHMBDialog(QDialog):
42
    def __init__(self, parent):
43
        from HMB_UI import Ui_HMBDialog
44
        from TableWidgetEx import QTableWidgetEx
45
        from WaitingSpinnerWidget import QtWaitingSpinner
46

    
47
        QDialog.__init__(self, parent)
48
        try:
49
            self.ui = Ui_HMBDialog()
50
            self.ui.setupUi(self)
51
            self.waiting_spinner = QtWaitingSpinner(self)
52

    
53
            self.ui.buttonBox.button(QDialogButtonBox.Ok).setIcon(QIcon(':/newPrefix/OK.svg'))
54
            self.ui.buttonBox.button(QDialogButtonBox.Ok).setText(self.tr('Import'))
55
            self.ui.buttonBox.button(QDialogButtonBox.Close).setIcon(QIcon(':/newPrefix/Remove.svg'))
56

    
57
            self.hmbs = None
58

    
59
            self.tabs = []
60
            self.layouts = []
61
            self.views = []
62

    
63
            self.dataChanged_original = None
64

    
65
            if self.fill_hmb_data():
66
                self.ui.buttonBox.button(QDialogButtonBox.Ok).setText(self.tr('Save'))
67

    
68
            self.ui.toolButtonHMBFilePath.clicked.connect(self.on_open_hmb_file)
69
        except Exception as ex:
70
            from App import App
71
            from AppDocData import MessageType
72

    
73
            message = f"error occurred({repr(ex)}) in {sys.exc_info()[-1].tb_frame.f_code.co_filename}:" \
74
                      f"{sys.exc_info()[-1].tb_lineno}"
75
            App.mainWnd().addMessage.emit(MessageType.Error, message)
76

    
77
    def dataChanged(self, *args):
78
        """ when cell data change update hmb data"""
79
        try:
80
            if self.hmbs:
81
                #currentTabIndex = self.ui.tabWidget.currentIndex()
82
                #tabText = self.ui.tabWidget.tabText(currentTabIndex)
83
                tab = self.ui.tabWidget.currentWidget()
84
                tab_index = self.tabs.index(tab)
85
                
86
                view = self.views[tab_index]
87
                cell_index = args[0]
88
                row = cell_index.row()
89
                col = cell_index.column()
90
                
91
                value = view.model().itemFromIndex(cell_index).text()
92

    
93
                # change stream no
94
                if col == 1:
95
                    pass
96
                # change list value
97
                else:
98
                    stream_no = view.model().item(row, 1).text()
99
                    for hmb in self.hmbs:
100
                        if hmb.stream_no == stream_no:
101
                            hmb.datas[tab_index][col - 2].value = value
102
                            break
103

    
104
        except Exception as ex:
105
            from App import App
106
            from AppDocData import MessageType
107

    
108
            message = f"error occurred({repr(ex)}) in {sys.exc_info()[-1].tb_frame.f_code.co_filename}:" \
109
                      f"{sys.exc_info()[-1].tb_lineno}"
110
            App.mainWnd().addMessage.emit(MessageType.Error, message)
111

    
112
        self.dataChanged_original(args[0], args[1], args[2])
113

    
114
    def fill_hmb_data(self):
115
        """load hmb data and fill table view"""
116
        import uuid
117

    
118
        try:
119
            hmbs = AppDocData.instance().get_hmb_data(None)
120

    
121
            count = self.ui.tabWidget.count()
122
            for i in range(count):
123
                self.ui.tabWidget.removeTab(0)
124
            self.tabs = []
125
            self.layouts = []
126
            self.views = []
127

    
128
            if not hmbs:
129
                self.hmbs = None
130
                return False
131

    
132
            for index in range(len(hmbs[0].datas)):
133
                tab = QWidget()
134
                tab.setObjectName('tab' + '_d' + str(index))
135
                gridLayout = QGridLayout(tab)
136
                gridLayout.setObjectName('gridLayout_3' + '_d' + str(index))
137
                tableViewHMB = QTableView(tab)
138
                tableViewHMB.setObjectName('tableViewHMB' + '_d' + str(index))
139
                gridLayout.addWidget(tableViewHMB, 0, 0, 1, 1)
140
                self.ui.tabWidget.addTab(tab, "")
141

    
142
                self.tabs.append(tab)
143
                self.layouts.append(gridLayout)
144
                self.views.append(tableViewHMB)
145

    
146
                model = HmbModel()
147
                header = ['UID', 'StreamNumber']
148

    
149
                for hmb in hmbs:
150
                    UID = hmb.uid
151
                    STREAM_NO = hmb.stream_no
152
                    items = [QStandardItem(UID)]
153
                    item =  QStandardItem(STREAM_NO)
154
                    #item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsEditable | Qt.ItemIsSelectable)
155
                    items.append(item)
156

    
157
                    for data in sorted(hmb.datas[index], key=lambda param: param.index):
158
                        if hmbs.index(hmb) == 0:
159
                            header.append(f"{data.name}\n({data.unit})" if data.unit else f"{data.name}")
160
                        item =  QStandardItem(data.value)
161
                        #item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsEditable)
162
                        items.append(item)
163
                    model.appendRow(items)
164

    
165
                model.setHorizontalHeaderLabels(header)
166

    
167
                self.views[index].setModel(model)
168
                delegate = HMBDelegate(self.views[index])
169
                self.views[index].setItemDelegate(delegate)
170
                self.dataChanged_original = self.views[index].dataChanged
171
                self.views[index].dataChanged = self.dataChanged
172
                self.views[index].resizeColumnsToContents()
173
                #self.views[index].setEditTriggers(QAbstractItemView.NoEditTriggers)
174
                self.views[index].setAlternatingRowColors(True)
175
                self.ui.tabWidget.setTabText(self.ui.tabWidget.indexOf(self.tabs[index]), hmbs[0].datas[index][0].case)
176
            
177
            self.hmbs = hmbs
178
            return True
179
        except Exception as ex:
180
            from App import App
181
            from AppDocData import MessageType
182

    
183
            message = f"error occurred({repr(ex)}) in {sys.exc_info()[-1].tb_frame.f_code.co_filename}:" \
184
                      f"{sys.exc_info()[-1].tb_lineno}"
185
            App.mainWnd().addMessage.emit(MessageType.Error, message)
186

    
187
            return False
188

    
189
    class Worker(QThread):
190
        finished = pyqtSignal()
191

    
192
        def __init__(self, file_path: str, keywords: list, keywords_match: list):
193
            super().__init__()
194

    
195
            self._file_path = file_path
196
            self.keywords = keywords
197
            self.keywords_match = keywords_match
198

    
199
        def run(self):
200
            """execute thread"""
201
            import math
202
            import pandas as pd
203
            from HMBTable import HMBData, StreamData
204

    
205
            allowed_error = 0.00001
206
            hmb_list = []
207
            sheets = pd.read_excel(self._file_path, sheet_name=None, header=None, convert_float=False)
208
            sheets = list(sheets.items())
209

    
210
            if sheets:
211
                sheets_name, df_m = sheets[0]
212

    
213
                rows, cols = df_m.shape[0], df_m.shape[1]
214
                for col in range(2, cols):
215
                    stream_no = df_m.iloc[0, col]
216
                    from_ = df_m.iloc[1, col]
217
                    to_ = df_m.iloc[2, col]
218

    
219
                    hmb = HMBData()
220
                    hmb.stream_no = stream_no
221
                    hmb.hfrom = from_
222
                    hmb.hto = to_
223

    
224
                    datas = []
225

    
226
                    for case, df in sheets:
227
                        data = []
228
                        name_type = ''
229
                        for row in range(3, rows):
230
                            value_ = df.iloc[row, 0]
231
                            name = value_ if value_ else ''
232

    
233
                            if name in self.keywords and name != name_type:
234
                                name_type = self.keywords_match[self.keywords.index(name)]
235
                                continue
236

    
237
                            value_ = df.iloc[row, 1]
238
                            unit = value_ if value_ else ''
239
                            value_ = df.iloc[row, col]
240
                            value = value_ if (type(value_) is str) or (type(value_) is float and not math.isnan(value_)) else ''
241

    
242
                            data.append(StreamData(name, unit, value, row, name_type, case))
243
                        
244
                        datas.append(data)
245

    
246
                    hmb.datas = datas
247
                    hmb_list.append(hmb)
248

    
249
            app_doc_data = AppDocData.instance()
250
            app_doc_data.save_hmb_data(hmb_list)
251

    
252
            self.finished.emit()
253

    
254
    def on_open_hmb_file(self):
255
        """open hmb file"""
256
        #from HMBTable import HMBData, StreamData
257

    
258
        options = QFileDialog.Options()
259
        options |= QFileDialog.DontUseNativeDialog
260
        file, _ = QFileDialog.getOpenFileName(self, self.tr('Import', "Select Excel File"),
261
                                               os.getcwd(), "excel files (*.xlsx)", options=options)
262
        if file:
263
            self.ui.lineEditHMBFilePath.setText(file)
264
            self.ui.buttonBox.button(QDialogButtonBox.Ok).setText(self.tr('Import'))
265
        else:
266
            self.ui.buttonBox.button(QDialogButtonBox.Ok).setText(self.tr('Save'))
267

    
268
    def accept(self):
269
        """accept dialog"""
270

    
271
        if self.ui.buttonBox.button(QDialogButtonBox.Ok).text() == 'Import':
272
            self.import_hmb()
273
        else:
274
            self.save_hmb()
275

    
276
    def save_hmb(self):
277
        """ save hmb data """
278
        if self.hmbs:
279
            app_doc_data = AppDocData.instance()
280
            app_doc_data.save_hmb_data(self.hmbs)
281

    
282
    def import_hmb(self):
283
        """ import hmb excel """
284

    
285
        def on_finished():
286
            self.fill_hmb_data()
287
            self.waiting_spinner.stop()
288

    
289
        try:
290
            file_path = self.ui.lineEditHMBFilePath.text()
291

    
292
            keywords = [self.ui.lineEditTotalKeyword.text(), self.ui.lineEditLiquidPhaseKeyword.text(), self.ui.lineEditVaporPhaseKeyword.text(), self.ui.lineEditCompositionKeyword.text()]
293
            keywords_match = ['TOTAL', 'LIQUID', 'VAPOR', 'COMPOSITION']
294

    
295
            if file_path:
296
                self.worker = QHMBDialog.Worker(file_path, keywords, keywords_match)
297
                self.worker.finished.connect(on_finished)
298
                self.waiting_spinner.start()
299
                self.worker.start()
300
            else:
301
                QMessageBox.warning(self, self.tr('Warning'), self.tr('Please, select a HMB excel file'))
302
        except Exception as ex:
303
            message = f"error occurred({repr(ex)}) in {sys.exc_info()[-1].tb_frame.f_code.co_filename}:" \
304
                      f"{sys.exc_info()[-1].tb_lineno}"
305
            QMessageBox.warning(self, self.tr('Warning'), message)
306

    
307
    def reject(self):
308
        """reject dialog"""
309
        QDialog.reject(self)
클립보드 이미지 추가 (최대 크기: 500 MB)