JungHulk / Hulk-Engineering

1 stars 0 forks source link

Hulk Engineering #5

Open JungHulk opened 1 year ago

JungHulk commented 1 year ago

Background.py

# -*- coding: utf-8 -*-
"""
Created on Fri Feb 25 15:34:25 2022

@author: 252914
"""
import os, numpy as np
import math
# import matplotlib.pyplot as plt

# from win32com.client import Dispatch
import pandas as pd
import numpy as np
import pickle

# import csv
# import openpyxl

from ctREFPROP.ctREFPROP import REFPROPFunctionLibrary

import sys
from PyQt5 import uic
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5 import QtCore, QtGui, QtWidgets

## 그래프 그리기 위한
# from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
# from matplotlib.figure import Figure

import pipe_dimension_rc

import Pipe_tableview as View
import Module as Md
# os.chdir('..')
# import air_prop_rev1 as AP

Comp_name = "Nitrogen;Methane;Ethane;Propane;Butane;Isobutane;Pentane;Isopentane"   
Comp_name_index = Comp_name.replace(';',' ').split()

Comp_value = np.zeros((len(Comp_name_index)))   
Comp_nor_value = np.zeros((len(Comp_name_index)))

#-------------------------- oNE FILE 재시도
def resource_path(relative_path):
    """ Get absolute path to resource, works for dev and for PyInstaller """
    base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
    return os.path.join(base_path, relative_path)

# def resource_path(relative):
#     return os.path.join(
#         os.environ.get(
#             "_MEIPASS2",
#             os.path.abspath(".")
#         ),
#         relative
#     )
Path = resource_path("source")
Path1 = resource_path("REFPROP.DLL")

# print(Path)
# print(Path1)

df1 = pd.read_pickle(Path+'\\Pipetable.p')    
dfcol= list(map(str, list(df1.columns))) # column 모두 string으로 만들기
df1.columns=dfcol

df2 = pd.read_pickle(Path+'\\Fitting_loss_coeff.p')
fit_index = df2.index # fitting table index (fitting button 비활성화 위한 사전작업)

form_class = uic.loadUiType(Path+'\\Pipe_engineer_rev3.ui')[0]

#--------------------------- One file 용

# BASE_DIR = os.path.dirname(sys.executable)
# Path = BASE_DIR +"\\source"
# # print(Path)
# # # os.chdir('source') #item 폴더로 이동
# # RP = REFPROPFunctionLibrary(Path)
# # RP.SETPATHdll(Path)

# df1 = pd.read_pickle(Path+'\\Pipetable.p')    
# dfcol= list(map(str, list(df1.columns))) # column 모두 string으로 만들기
# df1.columns=dfcol

# df2 = pd.read_pickle(Path+'\\Fitting_loss_coeff.p')
# fit_index = df2.index # fitting table index (fitting button 비활성화 위한 사전작업)

# # form_class = uic.loadUiType(Path+'\\Pipe_engineer_rev2.ui')[0]
# form_class = uic.loadUiType(BASE_DIR+'\\Pipe_engineer_rev2.ui')[0]
#--------------------------- One file 용

# df1 = pd.read_pickle('Pipetable.p')    
# dfcol= list(map(str, list(df1.columns))) # column 모두 string으로 만들기
# df1.columns=dfcol

# df2 = pd.read_pickle('Fitting_loss_coeff.p')
# fit_index = df2.index # fitting table index (fitting button 비활성화 위한 사전작업)
# form_class = uic.loadUiType("./Pipe_engineer_rev2.ui")[0]

MSG = ''

# os.chdir('source') #item 폴더로 이동

class MyWindow(QMainWindow, form_class):

    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.setWindowTitle("Hulk Engineer")

        self.Comp_OK_Button.clicked.connect(self.Click_Comp_OK_Button2) 
        self.Normalize_Button.clicked.connect(self.Click_Normalize_Button)
        self.Comp_Initialize_Button.clicked.connect(self.Click_Comp_Initialize_Button)        

        self.Comp_Nitrogen.textChanged.connect(self.Click_Comp_OK_Button)
        self.Comp_Methane.textChanged.connect(self.Click_Comp_OK_Button)
        self.Comp_Ethane.textChanged.connect(self.Click_Comp_OK_Button)
        self.Comp_Propane.textChanged.connect(self.Click_Comp_OK_Button)
        self.Comp_Butane.textChanged.connect(self.Click_Comp_OK_Button)
        self.Comp_i_butane.textChanged.connect(self.Click_Comp_OK_Button)
        self.Comp_Pentane.textChanged.connect(self.Click_Comp_OK_Button)
        self.Comp_i_Pentane.textChanged.connect(self.Click_Comp_OK_Button)

        self.Pipe_Initialize_Button.clicked.connect(self.Click_Pipe_Initialize_button)
        self.Pipe_ND.currentIndexChanged.connect(self.Input_Pipe_information)
        self.Pipe_schedule.currentIndexChanged.connect(self.Input_Pipe_information)
        self.Pipe_length.textChanged.connect(self.Input_Pipe_information)
        self.Pipe_ND.currentIndexChanged.connect(self.Click_Check_Information)       # heat leak 활성/비활성
        self.Pipe_schedule.currentIndexChanged.connect(self.Click_Check_Information) # heat leak 활성/비활성
        self.Pipe_length.textChanged.connect(self.Click_Check_Information)           # heat leak 활성/비활성

        self.Properties_flowrate.textChanged.connect(self.Pipe_Velocity)
        self.Properties_flowrate.returnPressed.connect(self.Pipe_Velocity)
        self.Properties_flowrate.textChanged.connect(self.Click_Check_Information) # heat leak 활성/비활성
        self.units_flowrate_list.currentIndexChanged.connect(self.Pipe_Velocity)

        Pipe_ND_list = list(df1.index)

        for i in range(0,len(Pipe_ND_list)) :
            self.Pipe_ND.addItem(str(Pipe_ND_list[i]))          
        Pipe_Sch_list = list(df1.columns)
        del Pipe_Sch_list[0:2] # inch, Out_dia 삭제      
        for i in range(0,len(Pipe_Sch_list)) :
            self.Pipe_schedule.addItem(str(Pipe_Sch_list[i]))
        # self.Pipe_length.returnPressed.connect(self.Input_Pipe_length)

        self.Prop_Cal_Button.clicked.connect(self.Click_Calculate_Button)          
        self.Properties_pressure.returnPressed.connect(self.Click_Calculate_Button)
        self.Properties_temperature.returnPressed.connect(self.Click_Calculate_Button)
        self.Properties_quality.returnPressed.connect(self.Click_Calculate_Button)   
        self.units_pressure_list.currentIndexChanged.connect(self.Click_Calculate_Button)
        self.units_temperature_list.currentIndexChanged.connect(self.Click_Calculate_Button)
        self.radioBtn.toggled.connect(self.Properties_quality.setDisabled)
        self.radioBtn_1.toggled.connect(self.Properties_temperature.setDisabled)
        self.radioBtn_1.toggled.connect(self.Properties_quality.setDisabled)        
        self.radioBtn_2.toggled.connect(self.Properties_temperature.setDisabled)
        self.radioBtn_2.toggled.connect(self.Properties_quality.setDisabled)
        self.Prop_Cal_Button.clicked.connect(self.Click_Check_Information)               # heat leak 활성/비활성
        self.Properties_pressure.returnPressed.connect(self.Click_Check_Information)     # heat leak 활성/비활성
        self.Properties_temperature.returnPressed.connect(self.Click_Check_Information)  # heat leak 활성/비활성
        self.Properties_quality.returnPressed.connect(self.Click_Check_Information)      # heat leak 활성/비활성

        self.Pipe_table.clicked.connect(self.Click_Pipe_information_table)
        self.Fittling_loss_table.clicked.connect(self.Click_Fitting_friction_coef_table)

        self.Comp_OK_Button.clicked.connect(self.Click_Calculate_Button)
        self.Normalize_Button.clicked.connect(self.Click_Calculate_Button)
        self.Comp_Initialize_Button.clicked.connect(self.Click_Calculate_Button)
        self.Comp_OK_Button.clicked.connect(self.Click_Check_Information)
        self.Normalize_Button.clicked.connect(self.Click_Check_Information)
        self.Comp_Initialize_Button.clicked.connect(self.Click_Check_Information)

        self.Air_condition_button.clicked.connect(self.Click_Air_table)
        self.Heat_leak_pipe_button.clicked.connect(self.Click_Heat_leak_pipe)
        self.Heat_leak_pipe_button.setDisabled(True) # 초기값은 비활성화

        Heat_pipe_input = [self.Properties_air_pressure, self.Properties_air_temperature, self.Heat_pipe_air_vel, self.Heat_pipe_ins_thk,\
                           self.Heat_pipe_pipe_TCX, self.Heat_pipe_ins_TCX, self.Properties_air_pressure, self.Properties_air_temperature]
        for n, i in enumerate(Heat_pipe_input):
            i.textChanged.connect(self.Input_Heat_transfer_check) 
            # i.returnPressed.connect(self.Click_Heat_leak_pipe) # 불편해도 Calucalte 눌러야 되도록.

        # self.Properties_air_pressure.textChanged.connect(self.Input_Heat_transfer_check)
        # self.Properties_air_temperature.textChanged.connect(self.Input_Heat_transfer_check)
        # self.Heat_pipe_air_vel.textChanged.connect(self.Input_Heat_transfer_check)
        # self.Heat_pipe_ins_thk.textChanged.connect(self.Input_Heat_transfer_check)
        # self.Heat_pipe_pipe_TCX.textChanged.connect(self.Input_Heat_transfer_check)
        # self.Heat_pipe_ins_TCX.textChanged.connect(self.Input_Heat_transfer_check)
        # self.Properties_air_pressure.textChanged.connect(self.Input_Heat_transfer_check)
        # self.Properties_air_temperature.textChanged.connect(self.Input_Heat_transfer_check)

        self.Heat_leak_default_button.clicked.connect(self.Click_Heat_leak_default_button)
        # for n, i in enumerate(self.Input_Heat_transfer_call()[1]):
        #     i.textChanged.connect(self.Input_Heat_transfer_call) 
        self.Fitting_Cal_Button.clicked.connect(self.Click_Friction_cal_Button)
        self.Fitting_Cal_Button.setDisabled(True)

        # if self.MSG_comp.text() = ""

    def Click_Comp_OK_Button(self):
        # Composition = [self.Comp_Nitrogen,self.Comp_Methane, self.Comp_Ethane, self.Comp_Propane, self.Comp_Butane, self.Comp_i_butane,
        #                 self.Comp_Pentane, self.Comp_i_Pentane]
        Composition = self.Composition_call()
        Comp = Md.Comp_OK_Button(Composition, Comp_value, MSG) # Composition Input

        self.Comp_Total.setNum(Comp[0])
        self.MSG_comp.setText(Comp[1])                      
        self.MSG_comp.adjustSize()

        if self.MSG_comp.text() == "Please Click OK button":
            self.Procedure_1.setStyleSheet('color:red')
        else:
            self.Procedure_1.setStyleSheet('color:black')

        return Comp[1]

    def Click_Comp_OK_Button2(self): # 실제 ok button 누를시 작동
        MSG = self.Click_Comp_OK_Button()

        if self.MSG_comp.text() == "Please Click OK button":
            MSG = "Complete"
            self.Procedure_1.setStyleSheet('color:red')
        else:
            self.Procedure_1.setStyleSheet('color:black')

        self.MSG_comp.setText(MSG)
        self.MSG_comp.adjustSize()

    def Click_Normalize_Button(self): # Composition Normalize Button        
        # Composition = [self.Comp_Nitrogen,self.Comp_Methane, self.Comp_Ethane, self.Comp_Propane, self.Comp_Butane, self.Comp_i_butane,
        #                 self.Comp_Pentane, self.Comp_i_Pentane]
        Comp_total = float(self.Comp_Total.text())
        Comp_nor_value = np.zeros((len(Comp_name_index)))
        # print(Comp_total)
        # print(Comp_nor_value)
        Composition = self.Composition_call()
        Normalize = Md.Normalize_Button(Composition, Comp_total, Comp_nor_value, MSG)

        self.Comp_Total.setNum(Normalize[0]*100)     
        self.MSG_comp.setText(Normalize[1])                      
        self.MSG_comp.adjustSize()

    def Click_Comp_Initialize_Button(self):
        # Composition = [self.Comp_Nitrogen,self.Comp_Methane, self.Comp_Ethane, self.Comp_Propane, self.Comp_Butane, self.Comp_i_butane,
        #                 self.Comp_Pentane, self.Comp_i_Pentane]
        Composition = self.Composition_call()
        for n,i in enumerate(Composition):            
            i.setText(str(0))
        Comp_nor_value = np.zeros((len(Comp_name_index)))
        self.MSG_comp.setText('Please input Compositions')
        self.MSG_comp.adjustSize()
        self.Procedure_1.setStyleSheet('color:black')

    def Input_Pipe_information(self):
        Pipe_info = [float(self.Pipe_ND.currentText()), self.Pipe_schedule.currentText(), 
                      self.Pipe_length.text()]     

        # try:
        #     length = float(self.Pipe_length.text())
        # except ValueError:
        #     self.Pipe_length.setText(str(0))

        Pipe = Md.Pipe_information(Pipe_info, df1)
    #     return ND, Sch, ND_inch, OD, Thickness, Length, ID, Sec_area, Volume, MSG, Surface_area
                # 0   1      2      3       4       5      6       7      8      9       10

        self.Pipe_OD.display(float(Pipe[3]))
        self.Pipe_OD.adjustSize()
        self.Pipe_ND_inch.setText(str(Pipe[2]))
        self.Pipe_ND_inch.adjustSize()
        self.Pipe_thickness.display(Pipe[4])
        self.Pipe_thickness.adjustSize()      
        # self.Pipe_length.setText(str(Pipe[5]))
        self.Pipe_length_2.display(float(Pipe[5]))
        self.Pipe_length_2.adjustSize()
        self.Pipe_ID.display(float(Pipe[6]))
        self.Pipe_ID.adjustSize()
        self.Pipe_secarea.setNum(float("%.5f"%(Pipe[7])))
        self.Pipe_volume.setNum(float("%.5f"%(Pipe[8])))
        self.MSG_pipe.setText(Pipe[9]) 
        self.Pipe_surfacearea.setNum(float("%.5f"%(Pipe[10])))

        if not float(self.Pipe_ND.currentText()) in fit_index :
            self.Fitting_Cal_Button.setDisabled(True)

        elif str(self.MSG_prop.text()) == "Out of boundary":
            self.Fitting_Cal_Button.setDisabled(True)

        else: 
            self.Fitting_Cal_Button.setEnabled(True)

#------------- Procedure color setting ----------------------------------------
        if self.MSG_pipe.text() == "Done":
            self.Procedure_3.setStyleSheet('color:red')
        else:
            self.Procedure_3.setStyleSheet('color:black')

    def Pipe_Velocity(self):
        # Flow = [self.Properties_flowrate.text(), self.units_flowrate_list.currentText(), self.Pipe_secarea.text(),
        #         self.Properties_density.text()]
        Flow = self.Input_Velocity_call()
        # print(Flow)
        Vel = Md.Velocity(Flow) # 해당 함수를 사용하면 [0]은 무조건 m3/h 값으로 반환하므로 필요시 사용.

        self.Pipe_velocity.setNum(Vel[1])
        self.MSG_2_pipe.setText(Vel[2])
        self.MSG_2_pipe.adjustSize()

    def Click_Pipe_Initialize_button(self):
        self.Pipe_ND.setCurrentIndex(0) # QCombobox 초기 값으로 세팅하는 표현
        self.Pipe_schedule.setCurrentIndex(0)
        self.Pipe_length.setText('0')
        self.Properties_flowrate.setText('0')
        # self.MSG_comp.setText('Please input Compositions')

    def Click_Calculate_Button(self): # Properties
        Composition = self.Composition_call()
        Comp = []
        for n, i in enumerate (Composition):
            Comp.append(float(i.text()))

        P = 0
        T = 0
        try:
            P = float(self.Properties_pressure.text()) / 1000
        except ValueError:
            self.Properties_pressure.setText(str(0))
        try:
            T = float(self.Properties_temperature.text())
        except ValueError:
            self.Properties_temperature.setText(str(0))        

        # Pressure unit convert
        if self.units_pressure_list.currentText() == 'kPaA' :
            P = float(self.Properties_pressure.text()) / 1000
        elif self.units_pressure_list.currentText() == 'barA' :
            P = float(self.Properties_pressure.text()) / 10
        else:
            P = (float(self.Properties_pressure.text()) + 1.01325 ) / 10

        if self.radioBtn.isChecked(): # 1번 버튼 누를 때,          
            if self.units_temperature_list.currentText() == '℃' :
                T = float(self.Properties_temperature.text())
            else:
                T = float(self.Properties_temperature.text()) - 273.15

            df = Md.Properties(Comp_name, Comp, "PT", P, T)[1]  
            value = Md.Properties(Comp_name, Comp, "PT", P, T)[0]

        if self.radioBtn_1.isChecked(): # 2번 버튼 누를 때,    
            self.Properties_quality.setText(str(0))
            Quality = float(self.Properties_quality.text())

            df = Md.Properties(Comp_name,Comp, "PQmass", P, Quality)[1]
            value = Md.Properties(Comp_name, Comp, "PQmass", P, Quality)[0]
            T = float("%.2f"%(df.at['T','Values']))
            self.Properties_temperature.setText(str(T))

        if self.radioBtn_2.isChecked(): # 3번 버튼 누를 때,    
            self.Properties_quality.setText(str(1))
            Quality = float(self.Properties_quality.text())

            df = Md.Properties(Comp_name,Comp, "PQmass", P, Quality)[1] 
            value = Md.Properties(Comp_name, Comp, "PQmass", P, Quality)[0]
            T = float("%.2f"%(df.at['T','Values']))
            self.Properties_temperature.setText(str(T))

        self.Properties_phase.setText(df.at['Phase','Units'])
        Phase = self.Properties_phase.text()

        self.Properties_density.setNum(df.at['D','Values']) 
        self.Properties_enthalpy.setNum(df.at['H','Values'])

        if Phase == 'Superheated gas' or Phase == 'Subcooled liquid':
            self.Properties_quality.setText('single phase')
        else:
            Quality = float("%.4f"%(df.at['Qmass','Values']))
            self.Properties_quality.setText(str(Quality))

        DV = df.at['DV','Values']
        KV = df.at['KV','Values'] / (100**2)

        self.Properties_latentheat.setNum(df.at['Heatvapz_P','Values'])     
        self.Properties_dynamicvis.setNum(DV)
        self.Properties_kineticvis.setNum(KV)

#-----------------------  Out of boundary ------------------------------------

        if Phase == "PHASE" :
            MSG = "Out of boundary"
            self.Properties_density.setText('-')
            self.Properties_enthalpy.setText('-')
            self.Properties_quality.setText('-')
            self.Properties_latentheat.setText('-')
        elif DV < 0 or KV < 0:
            MSG = "Out of boundary"
        else:
            MSG = "Done"

#-----------------------------------------------------------------------------
        self.MSG_prop.setText(MSG)                      
        self.MSG_prop.adjustSize()  

#--------------Fitting calculation 비활성화----------------------------------------    
        if not float(self.Pipe_ND.currentText()) in fit_index :
            self.Fitting_Cal_Button.setDisabled(True)

        elif str(self.MSG_prop.text()) == "Out of boundary":
            self.Fitting_Cal_Button.setDisabled(True)

        else: 
            self.Fitting_Cal_Button.setEnabled(True)       

#------------- Procedure color setting ----------------------------------------
        if self.MSG_prop.text() == "Done":
            self.Procedure_2.setStyleSheet('color:red')
        else:
            self.Procedure_2.setStyleSheet('color:black')

        return  value, df 

 # #--------------Heat in leak 비활성화----------------------------------------
 #        if str(self.MSG_prop.text()) == "Out of boundary":
 #            self.Heat_leak_pipe_button.setDisabled(True)
 #        else:
 #            self.Heat_leak_pipe_button.setEnabled(True)

    def Click_Air_table(self):
        global Air_Table
        P = float(self.Properties_air_pressure.text())/1000
        T = float(self.Properties_air_temperature.text())
        df = Md.Properties("Air", [1], "PT", P, T)
        Table = View.PandasModel(df[1])
        Air_Table = QtWidgets.QTableView()
        Air_Table.setModel(Table)
        Air_Table.resize(290,450)
        Air_Table.show()

    def Click_Pipe_information_table(self):
        global Pipe_Table
        Table = View.PandasModel(df1)
        Pipe_Table = QtWidgets.QTableView()
        Pipe_Table.setModel(Table)
        Pipe_Table.resize(800,600)
        Pipe_Table.show()

    def Click_Fitting_friction_coef_table(self):
        global Fitting_Table
        Table = View.PandasModel(df2)
        Fitting_Table = QtWidgets.QTableView()
        Fitting_Table.setModel(Table)
        Fitting_Table.resize(800,500)
        Fitting_Table.show()

    def Click_Check_Information(self):

        length = self.Pipe_length.text()
        flowrate = self.Properties_flowrate.text()

        # Check length, flowarate
        try:
            float(length)
            float(flowrate)

            if length != str(0) :
                # Check flowrate
                if flowrate !=str(0):
                    # Check Properties
                    if str(self.MSG_prop.text()) == "Done":
                        self.Heat_pipe_fluid_temp.setText(self.Properties_temperature.text())
                        # Check Pipe information
                        if str(self.MSG_pipe.text()) == "Done":
                            self.MSG_get_information.setText("Done")
                            self.Heat_leak_pipe_button.setEnabled(True)
                        else:
                            self.MSG_get_information.setText("Please select schedule again")
                            self.Heat_leak_pipe_button.setDisabled(True)        
                    else :
                        self.MSG_get_information.setText("Please modify properties")
                        self.Heat_leak_pipe_button.setDisabled(True)
                else:
                    self.MSG_get_information.setText("Please input Flowrate")
                    self.Heat_leak_pipe_button.setDisabled(True)                
            else:
                self.Heat_leak_pipe_button.setDisabled(True)
                self.MSG_get_information.setText("Please input Length")          

        except:
            self.Heat_leak_pipe_button.setDisabled(True)
            self.MSG_get_information.setText("Plase input Number only")                   

        # Check length

    def Click_Heat_leak_pipe(self):
##______________________________________ input
        # air properties
        P = float(self.Properties_air_pressure.text())/1000
        T = float(self.Properties_air_temperature.text())
        df_air = Md.Properties("Air",[1], "PT", P, T)[0]
        # fluid properties        
        df_fluid = self.Click_Calculate_Button()[0]

        Pipe_info = [float(self.Pipe_ND.currentText()), self.Pipe_schedule.currentText(), 
                      self.Pipe_length.text()]        
        Input_pipe = Md.Pipe_information(Pipe_info, df1)  
        # ND, Sch, ND_inch, OD, Thickness, Length, ID, Sec_area, Volume, MSG, Surface_area     

        Flow = self.Input_Velocity_call() # Input parameter call
        Input_vel = Md.Velocity(Flow)
        # Flowrate , Velocity
        self.Input_Heat_transfer_check()
        Input_heat = self.Input_Heat_transfer_call()
        # air_vel, fluid_temp, int_TCX, INS_thk, pipe_TCX, resuslt

        Heat_leak = Md.Pipe_heat(Input_pipe, Input_heat[0], Input_vel, df_air, df_fluid)  
        # Heat_leak_pipe, MSG, Conv_heat_coef_air, Conv_heat_coef_flu

        self.Heat_pipe_result.setNum(Heat_leak[0])

#------ Outlet temperature 계산하기
        Composition = self.Composition_call()
        Comp = []
        for n, i in enumerate (Composition):
            Comp.append(float(i.text()))       
        T_flu_out = Md.Properties(Comp_name, Comp, "Ph", df_fluid[0], Heat_leak[1])[0]
        print(df_fluid[0], Heat_leak[1], T_flu_out)
        # print(T_flu_out)
        # print(Heat_leak)
        self.LED_Pipe_ND.display(Input_pipe[0])
        self.LED_Pipe_ND.adjustSize()
        self.LED_Ins_thickness.display(Input_heat[0][3])
        self.LED_Ins_thickness.adjustSize()
        self.LED_Air_temp.setDigitCount(7)
        self.LED_Air_temp.display('{:.01f}'.format(df_air[1]))
        # self.lcdNumber_2.display('{:.02f}'.format(value))
        self.LED_Air_temp.adjustSize()
        self.LED_Pipe_in_temp.setDigitCount(7)
        self.LED_Pipe_in_temp.display('{:.01f}'.format(df_fluid[1]))
        self.LED_Pipe_in_temp.adjustSize()
        self.LED_Pipe_out_temp.setDigitCount(7)
        self.LED_Pipe_out_temp.display('{:.01f}'.format(T_flu_out[1]))
        self.LED_Pipe_out_temp.adjustSize()
        self.LED_Heat_leak.setDigitCount(7)
        self.LED_Heat_leak.display('{:.01f}'.format(float(Heat_leak[0])))
        self.LED_Heat_leak.adjustSize()
        self.MSG_heat_transfer.setText(Heat_leak[2])

    def Click_Heat_leak_default_button(self): # heat leak default button (table 로 reference 추가 하도록)
        Input = self.Input_Heat_transfer_check()
        del Input[5]
        del Input[1]
        Default = [6, 0.04, 0, 15, 101.325, 45]
        for n,i in enumerate(Input):
            eval(i).setText(str(Default[n]))
            # print(eval(i).text())

    def Click_Friction_cal_Button(self):
        roughness = float(self.Pipe_roughness.text()) 

        k = np.array((df2.loc[float(self.Pipe_ND.currentText())]), dtype = np.float) # ND에 따른 k 값 list로 받기       

        temp_fitting = [] #Fitting 이름들 list
        for i in range(1,len(df2.columns)+1):
            temp_fitting.append('self.Globe_num_'+str(i))

        temp_loss = []    # Fitting loss 입력되는 곳 이름 list
        for i in range(1,len(df2.columns)+1): 
            temp_loss.append('self.Globe_loss_'+str(i))       

        for n, i in enumerate (temp_loss): # ND 에 맞는 loss 값을 뿌려주기
            eval(i).setNum(k[n]) 

        nof = [] # number of fitting
        for n,i in enumerate (temp_fitting) :
            nof.append(eval(i).value())

        Pipe_info = [float(self.Pipe_ND.currentText()), self.Pipe_schedule.currentText(), self.Pipe_length.text()]  
        Pipe = Md.Pipe_information(Pipe_info, df1)

        Vel_input = self.Input_Velocity_call()
        Vel = Md.Velocity(Vel_input)[1]

        Property = self.Click_Calculate_Button()[0]
        Height = float(self.Pipe_netheightvar.text())

        fric = Md.Friction(k, nof, Pipe, Vel, Property, roughness, Height)
#    fit_total_loss, head_vel, reynolds, pipe_fric_coef, pipe_loss, fit_loss, total_loss_m, total_loss_pressure

        self.loss_calculation_fitting_friction_coef.setNum(float("%.4f"%(fric[0])))
        self.loss_calculation_velocity_head.setNum(float("%.4f"%(fric[1])))
        self.loss_calculation_reynold.setNum(fric[2])
        self.loss_calculation_pipe_friction_coef.setNum(float("%.4f"%(fric[3])))
        self.loss_calculation_pipe_loss.setNum(float("%.4f"%(fric[4])))
        self.loss_calculationfitting_loss.setNum(float("%.4f"%(fric[5])))
        self.loss_calculation_static_head.setNum(Height)
        self.loss_calculation_friction_loss_system_m.setNum(float("%.4f"%(fric[6])))
        self.loss_calculation_friction_loss_system_bar.setNum(float("%.4f"%(fric[7])))    
        self.loss_calculation_friction_loss_system_bar_2.setNum(float("%.4f"%(fric[7])))
        # i.setText("%.4f"%(Comp_nor_value[n]*100))  #소수점 4자리까지 표현    

    def Composition_call(self):
        Composition = [self.Comp_Nitrogen,self.Comp_Methane, self.Comp_Ethane, self.Comp_Propane, self.Comp_Butane, self.Comp_i_butane,
                       self.Comp_Pentane, self.Comp_i_Pentane]        
        return Composition

    def Input_Heat_transfer_call(self): # Heat_pipe 주소만 전달
        temp = []
        Input = []
        for n, i in enumerate(dir(myWindow)):
            if "Heat_pipe" in i:
                temp.append("self."+i)
        for n, i in enumerate(temp):
            try:
                Input.append(float(eval(i).text())) # check def 에서 call 을 부름. temp[] 클릭시 call 할수 연결하면 myWindow 인식 안되서 부득이 check 함수와 별개로 둠. 
            except:
                eval(i).setText(str(0))
                # self.Heat_leak_pipe_button.setDisabled(True)
#   ['self.Heat_pipe_air_vel', 'self.Heat_pipe_fluid_temp', 'self.Heat_pipe_ins_TCX', 'self.Heat_pipe_ins_thk', 
#    'self.Heat_pipe_pipe_TCX', 'self.Heat_pipe_result']
        return Input, temp

    def Input_Heat_transfer_check(self):
        Input = self.Input_Heat_transfer_call()[1]
        Input.append('self.Properties_air_pressure')
        Input.append('self.Properties_air_temperature')
        for n, i in enumerate(Input):
            try:
                float(eval(i).text())
            except:
                eval(i).setText(str(0))   

        return Input

    def Input_Velocity_call(self):
        Input = [self.Properties_flowrate.text(), self.units_flowrate_list.currentText(), self.Pipe_secarea.text(),
                 self.Properties_density.text()]
        return Input

    def show_graph(self):
        #x_list, y_list, y_err, data_name에 대한 설정 코드 

        self.Tank_shape.canvas.draw()         

if __name__ == "__main__":
    app = QApplication(sys.argv)
    myWindow = MyWindow()
    myWindow.show()
    app.exec_()

# def input_list():

#     var = []
#     for i,n in enumerate(dir(myWindow)):
#         if n[0].isupper():
#             var.append(n)
JungHulk commented 1 year ago

Module.py

# -*- coding: utf-8 -*-
"""
Created on Mon Mar  7 16:10:55 2022

@author: 252914
"""
import os
import pandas as pd
import numpy as np
import math

from ctREFPROP.ctREFPROP import REFPROPFunctionLibrary

import sys

from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5 import QtCore, QtGui, QtWidgets

# from Background_Code import P,T
# Main = Mywindow()

#---------------------------One file 재시도
def resource_path(relative_path):
    """ Get absolute path to resource, works for dev and for PyInstaller """
    base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
    return os.path.join(base_path, relative_path)

Path = resource_path("source")

Ref_path = resource_path(Path)
RP = REFPROPFunctionLibrary(Path)
RP.SETPATHdll(Path)
SI = RP.GETENUMdll(0,"SI WITH C").iEnum

#--------------------------- One file 용
# BASE_DIR = os.path.dirname(sys.executable)
# Path = BASE_DIR +"\\source"
# # # # os.chdir('source') #item 폴더로 이동
# RP = REFPROPFunctionLibrary(Path)
# RP.SETPATHdll(Path)
# SI = RP.GETENUMdll(0,"SI WITH C").iEnum
#--------------------------- One file 용

os.chdir('source') #item 폴더로 이동
RP = REFPROPFunctionLibrary(os.getcwd())
RP.SETPATHdll(os.getcwd())
SI = RP.GETENUMdll(0,"SI WITH C").iEnum

def Comp_OK_Button(Composition, Comp_value,  MSG): # Composition 
    for n,i in enumerate(Composition):
        i.setValidator(
            QtGui.QDoubleValidator(
                0.0, # bottom
                999.0, #top
                4, #decimals
                notation = QtGui.QDoubleValidator.StandardNotation
                )
            )

    for n,i in enumerate(Composition):            
        try:
            Comp_value[n] = float(i.text())
        except ValueError:
            MSG = "Input number only"
            i.setText(str(0))
            Comp_value[n] = float(i.text())

    Sum_comp = float(Comp_value.sum())

    if (abs(Sum_comp - 1.00) <= 1e-8) == True: # 부동소수점 해결
        # MSG = "Composition Setting clear"
        MSG = "Please Click OK button"
    elif (abs(Sum_comp - 100.00) <= 1e-6) == True:
        # MSG = "Composition Setting Clear"
        MSG = "Please Click OK button"
    elif abs(Sum_comp) == 0:
        MSG = "Please input Compositions"
    else:
        MSG = "Need to normalize"     

    return Sum_comp, MSG

def Normalize_Button(Composition, Comp_total, Comp_nor_value, MSG): # Composition Normalize Button   
    for n,i in enumerate(Composition) :
        try:
            Comp_nor_value[n] = float(i.text())/ Comp_total  
            MSG = "Normalize complete"
        except ZeroDivisionError:
            MSG = "Please input Composition"

        i.setText("%.4f"%(Comp_nor_value[n]*100)) #소수점 4자리까지 표현
    Sum_comp = float(Comp_nor_value.sum())

    return Sum_comp, MSG

def Pipe_information(Pipe_info, df1):
    # Pipe_info = [float(self.Pipe_ND.currentText()), self.Pipe_schedule.currentText(), self.Pipe_length.text()]

    ND = float(Pipe_info[0])  
    Sch = Pipe_info[1]

    try:
        Length = float(Pipe_info[2])
    except ValueError:
        Length = float(0)

    ND_inch = str(df1.at[ND,'(NPS)'])           
    OD = float(np.array(df1.loc[[(ND)],[df1.columns[1]]]))  
    ID = 0
    Sec_area = 0
    Volume = 0
    Thickness = '-'

    Surface_area = math.pi * float(OD) * Length / 1000000 # 표면적
    try: 
        Thickness = df1.at[ND,Sch]    
        if Thickness == "-":
            MSG = "Select schedule again"
        else:
            MSG = "Done"
            ID = float(OD) - 2*float(Thickness) # 내경
            Sec_area = math.pi * (ID/2)**2 / 1000000 # 단면적
            Volume = Sec_area * float(Length) / 1000 # 배관 내부 부피

    except KeyError:
        MSG ="Select schedule again"        

    return ND, Sch, ND_inch, OD, Thickness, Length, ID, Sec_area, Volume, MSG, Surface_area

def Velocity(Flow):
# Flow = [self.Properties_flowrate.text(), self.units_flowrate_list.currentText(), self.Pipe_secarea.text()
                          # 0                                   1                                  2
          # self.Properties_density.text()]
                           # 3     
    Flowrate = 0
    Velocity = 0

    try : 
        Flowrate = float(Flow[0])
        # Velocity = Flowrate / float(Flow[2]) / 3600

        if Flow[1] == 'm3/h' :
            if str(Flow[0]) == '0':
                Velocity = 0
                MSG_2 = "Please input flowrate"
            elif str(Flow[0]) == '':
                Velocity = 0
                MSG_2 = "Please input flowrate"
            else:
                Velocity = Flowrate / float(Flow[2]) / 3600
                MSG_2 = ' '
        if Flow[1] == 'kg/h' :
            if str(Flow[3]) == '-':
                Velocity = 0
                MSG_2 = "Please calculate properties first"
            elif str(Flow[3]) =='0':
                Velocity = 0
                MSG_2 = "Please calculate properties first"
            else:
                MSG_2 = ' '
                Flowrate = float(Flowrate) / float(Flow[3])
                Velocity = Flowrate / float(Flow[2]) / 3600
                # print (float(self.Properties_density.text()))
    except :
        MSG_2 = "Please input number only"

    # print(Flowrate, Velocity)
    return Flowrate, Velocity, MSG_2 #Flowrate 는 volumetric flowrate

def Properties(Comp_name, Comp_value, Input_prop, input1, input2):
    Prop_list = "P;T;D;H;M;CP;Phase;Qmass;VIS;TCX;PRANDTL;KV;Heatvapz_P"     # VISCOSITY 는 100만 나누어야 함.
    Prop_index = np.array(Prop_list.replace(';',' ').split())

    Prop = []
    Value = []

    for k in Prop_index:   # "P;T;D;H;M;CP;Phase;Qmass;VIS;TCX;PRANDTL;KV;Heatvapz_P"
        r = RP.REFPROPdll(Comp_name, Input_prop , k, SI, 0,0, input1, input2, Comp_value)
        Prop.append([k,r.hUnits,r.Output[0]])
        Value.append(r.Output[0])

    DY = Value[2] * Value[11] / (100**2) # Dynamic viscousity

    df_prop = pd.DataFrame(Prop, index = Prop_index, columns=['Prop','Units','Values'])
    df_prop = df_prop.drop(['Prop'], axis=1)
    df_prop.loc['DV'] = ['kg/m-s', DY]

    return Value, df_prop # Value, dataframe 

# Pipe: ND, Sch, ND_inch, OD, Thickness, Length, ID, Sec_area, Volume, MSG, Surface_area     
# Heat: air_vel, fluid_temp, ins_TCX, INS_thk, pipe_TCX, resuslt
def Pipe_heat(Pipe, Heat, Velocity, Prop_air, Prop_fluid ):  # Temp. Press. air vel, Diameter(ins out), Dia. inner, Temp. fluid    
    Vel_air = Heat[0] # m/s
    T_air = Prop_air[1] # Temperature
    D_air = Prop_air[2] # Density
    TCX_air = Prop_air[9]
    Pr_air = Prop_air[10]

    Vel_flu = Velocity[1] # m/s
    Flowrate = Velocity[0] # m3/h
    T_flu = Prop_fluid[1] # Temperature
    D_flu = Prop_fluid[2] # Density
    TCX_flu = Prop_fluid[9]
    Pr_flu = Prop_fluid[10]
    Phase_flu = Prop_fluid[6]
    H_flu = Prop_fluid[3]

    Dia_ins_out = (Pipe[3] + Heat[3]*2) / 1000 # m
    Dia_in = Pipe[6] / 1000 # ID
    Dia_out = Pipe[3] / 1000 # OD
    T_flu = Heat[1] # 유체 온도
    Length = Pipe[5] / 1000# 배관 길이
    TCX_pipe = Heat[4]
    TCX_ins  = Heat[2]

    Vis_air = Prop_air[8]/1000000 # kg/m-s
    Vis_flu = Prop_fluid[8]/1000000 # kg/m-s
    Reynolds_air = Vel_air * D_air * Dia_ins_out / Vis_air
    Reynolds_flu = Vel_flu * D_flu * Dia_in / Vis_flu
    # Reynolds 에 따른 coef 두개2로 나누기. turbul, lami
    # fluid 의 convective heat tran_coef 도 추가해야할지 고민.

    # print(Pipe)
    # print(Heat)
    # print(Velocity)
    # print(Prop_air)
    # print(Prop_fluid)
    # try:
        # raise ValueError("shit")
    Conv_heat_coef_air = (TCX_air/1000 / Dia_ins_out) * (0.3  +\
                                              (0.62 * Reynolds_air**(1/2) * Pr_air**(1/3)*(1+(Reynolds_air/282000)**(5/8))**(4/5)) / \
                                              (1+(0.4/Pr_air)**(2/3))**(1/4))
    Conv_heat_coef_flu = (TCX_flu/1000 / Dia_in) * (0.3  +\
                                              (0.62 * Reynolds_flu**(1/2) * Pr_air**(1/3)*(1+(Reynolds_flu/282000)**(5/8))**(4/5)) / \
                                              (1+(0.4/Pr_flu)**(2/3))**(1/4))
    Heat_leak_pipe = (2 * 3.14 * Length * (T_air-T_flu)) / ((Dia_ins_out*math.log(Dia_out/Dia_in)/TCX_pipe) +\
                                                  (Dia_ins_out * math.log(Dia_ins_out/Dia_out)/TCX_ins) +\
                                                  (1/Conv_heat_coef_air/(Dia_ins_out/2)) + (1/Conv_heat_coef_flu/(Dia_in/2))) / 1000
    h = H_flu + (Heat_leak_pipe*3600 / (Flowrate*D_flu))
    MSG = "Complete"   

    ### 현재는 배관내부가 고정온도로 되어 있어서 배관이 길어지면 유입되는 열량이 엄청남.
    ## 따라서 배관 후단의 온도는 위의 계산으로는 불가능하며, 시간텀이 들어가서 유량이 흐를때 배출되는 유체의 온도를 계산하는걸로 바꾸어야 함.

    # except:
    #     Conv_heat_coef_air = -99999
    #     Conv_heat_coef_flu = -99999
    #     Heat_leak_pipe = -99999
    #     h = -99999
    #     MSG = "Please check input values"

    print(Heat_leak_pipe)
    return Heat_leak_pipe, h, MSG, Conv_heat_coef_air, Conv_heat_coef_flu

def Friction(k_list, No_f, Pipe, Velocity, Properties, Roughness, Height): # k값 list, fitting 개수, Pipe 정보
# Pipe 정보 ND, Sch, ND_inch, OD, Thickness, Length, ID, Sec_area, Volume, MSG, Surface_area
# Prop  "P;T;D;H;M;CP;Phase;Qmass;VIS;TCX;PRANDTL;KV;Heatvapz_P"
    k = k_list
    nof = No_f
    Vel = float(Velocity)
    fit_total_loss = np.sum(k * nof)
    Prop = Properties   
    head_vel = Vel**2 / 2 / 9.81 # head velocity

    # reynolds = (Pipe[6]/1000) * Vel * Prop[2] / (Prop[11]/1000**2)
    # pipe_fric_coef = 0.25/(math.log10((Roughness / (3.7 * Pipe[6]))+(5.74 / reynolds**0.9)))**2
    # pipe_loss = pipe_fric_coef * Pipe[5]/1000 / (Pipe[6]/1000) * head_vel

    try:
        reynolds = (Pipe[6]/1000) * Vel * Prop[2] / (Prop[11]/1000**2)
    except ZeroDivisionError:
        reynolds = 0

    try:
        pipe_fric_coef = 0.25/(math.log10((Roughness / (3.7 * Pipe[6]))+(5.74 / reynolds**0.9)))**2
    except ZeroDivisionError:
        pipe_fric_coef = 0

    try:
        pipe_loss = pipe_fric_coef * Pipe[5]/1000 / (Pipe[6]/1000) * head_vel
    except ZeroDivisionError:
        pipe_loss = 0

    fit_loss = fit_total_loss * head_vel   
    total_loss_m = Height + pipe_loss + fit_loss   
    total_loss_pressure = total_loss_m * Prop[2] * 9.81 / 100000 #barg

    return fit_total_loss, head_vel, reynolds, pipe_fric_coef, pipe_loss, fit_loss, total_loss_m, total_loss_pressure
JungHulk commented 1 year ago

UI connector

Pipe_Engineer_rev3.ui -> .py

...