示例#1
0
def _getData(fluid, keys, phase=True, unit=None, table=True):
    """Procedure to get values of properties in fluid
    Input:
        fluid: fluid instance to get values
        keys: array with desired parameter to get
        phase: boolean to get the properties values for both phases
        unit: unidades subclass
        table: boolean if the values are for a table, the none values are repr
            as text msg
    """
    fila = []
    for i, key in enumerate(keys):
        if not key:
            continue
        p = fluid.__getattribute__(key)

        if isinstance(p, list):
            p = p[0]

        if isinstance(p, str):
            txt = p
        # elif isinstance(p, list):
        # txt = repr(p)
        else:
            if unit and unit[i]:
                txt = p.__getattribute__(unit[i])
            else:
                txt = p.config()
        fila.append(txt)

        # Add two phases properties is requested
        if phase and key in ThermoAdvanced.propertiesPhase():
            # Liquid
            p = fluid.Liquido.__getattribute__(key)
            if isinstance(p, str):
                txt = p
            elif isinstance(p, unidades.unidad):
                if unit and unit[i]:
                    txt = p.__getattribute__(unit[i])
                else:
                    txt = p.config()
            else:
                txt = p
            fila.append(txt)
            # Gas
            p = fluid.Gas.__getattribute__(key)
            if isinstance(p, str):
                txt = p
            elif isinstance(p, unidades.unidad):
                if unit and unit[i]:
                    txt = p.__getattribute__(unit[i])
                else:
                    txt = p.config()
            else:
                txt = p
            fila.append(txt)
    return fila
示例#2
0
def saveProperties(fluids):
    """Save all available properties of a list of fluids"""
    dat = {}
    for key in ThermoAdvanced.propertiesKey():
        prop = []
        for fluid in fluids:
            if fluid is not None and fluid.status in [1, 3]:
                p = fluid.__getattribute__(key)
                if key in ["fi", "f"]:
                    p = p[0]
                prop.append(p)
        dat[key] = prop
    return dat
示例#3
0
 def plot3D(self):
     """Add a generic 3D plot to project"""
     dlg = Plot3D(self.parent())
     if dlg.exec_():
         i = dlg.ejeX.currentIndex()
         j = dlg.ejeY.currentIndex()
         k = dlg.ejeZ.currentIndex()
         if k >= i:
             k += 1
         if k >= j:
             k += 1
         if j >= i:
             j += 1
         prop = ThermoAdvanced.propertiesKey()
         x = prop[i]
         y = prop[j]
         z = prop[k]
         self.plot(x, y, z=z)
示例#4
0
    def plot2D(self):
        """Add a generic 2D plot to project"""
        dlg = Plot2D(self.parent())
        if dlg.exec_():
            i = dlg.ejeX.currentIndex()
            j = dlg.ejeY.currentIndex()
            if j >= i:
                j += 1
            prop = ThermoAdvanced.propertiesKey()
            x = prop[i]
            y = prop[j]

            if dlg.Xscale.isChecked():
                xscale = "log"
            else:
                xscale = "linear"
            if dlg.Yscale.isChecked():
                yscale = "log"
            else:
                yscale = "linear"
            self.plot(x, y, xscale, yscale)
示例#5
0
def get_propiedades(config):
    """Procedure to get the properties to show in tables
    Input:
        config: configparser instance with mainwindow preferences
    Output:
        array with properties, key and units
    """
    booleanos = config.get("MEoS", "properties")
    order = config.get("MEoS", "propertiesOrder")
    if isinstance(booleanos, str):
        booleanos = eval(booleanos)
    if isinstance(order, str):
        order = eval(order)

    propiedades = []
    keys = []
    units = []
    for indice, bool in zip(order, booleanos):
        if bool:
            name, key, unit = ThermoAdvanced.properties()[indice]
            propiedades.append(name)
            keys.append(key)
            units.append(unit)
    return propiedades, keys, units
示例#6
0
    def calculo(self):
        T = self.kwargs["T"]
        rho = self.kwargs["rho"]
        P = self.kwargs["P"]
        v = self.kwargs["v"]
        h = self.kwargs["h"]
        s = self.kwargs["s"]
        u = self.kwargs["u"]
        x = self.kwargs["x"]

        self.comp = []
        for i in self.kwargs["componente"]:
            c = self.componentes[i](eq="GERG", **self.kwargs)
            self.comp.append(c)
        self.id = self.kwargs["componente"]
        self.xi = self.kwargs["fraccion"]

        # Critic properties for mixture,
        # eq. 7.9, 7.10 pag.125, Tabla 7.10 pag 136
        bt = self.Prop_c["beta_t"]
        bv = self.Prop_c["beta_v"]
        gt = self.Prop_c["gamma_t"]
        gv = self.Prop_c["gamma_v"]
        c_T = zeros((len(self.comp), len(self.comp)))
        c_rho = zeros((len(self.comp), len(self.comp)))
        for i, cmpi in enumerate(self.comp):
            for j, cmpj in enumerate(self.comp):
                c_T[i, j] = 2*bt[i][j]*gt[i][j]*(cmpi.Tc*cmpj.Tc)**0.5
                c_rho[i, j] = 2*bv[i][j]*gv[i][j]/8. * \
                    (1./cmpi.rhoc**(1./3)+1./cmpj.rhoc**(1./3))**3

        f_T = zeros((len(self.comp), len(self.comp)))
        f_rho = zeros((len(self.comp), len(self.comp)))
        dFT_ik = zeros((len(self.comp), len(self.comp)))
        dFT_ki = zeros((len(self.comp), len(self.comp)))
        dFrho_ik = zeros((len(self.comp), len(self.comp)))
        dFrho_ki = zeros((len(self.comp), len(self.comp)))
        for i, x_i in enumerate(self.xi):
            for j, x_j in enumerate(self.xi):
                f_T[i, j] = x_i*x_j*(x_i+x_j)/(bt[i][j]**2*x_i+x_j)
                f_rho[i, j] = x_i*x_j*(x_i+x_j)/(bv[i][j]**2*x_i+x_j)
                dFT_ik[i, j] = x_j*(x_j+x_i)/(bt[i][j]**2*x_i+x_j) + \
                    x_j*x_i/(bt[i][j]**2*x_i+x_j) * \
                    (1-bt[i][j]**2*(x_j+x_i)/(bt[i][j]**2*x_i+x_j))
                dFrho_ik[i, j] = x_j*(x_j+x_i)/(bv[i][j]**2*x_i+x_j) + \
                    x_j*x_i/(bv[i][j]**2*x_i+x_j) * \
                    (1-bv[i][j]**2*(x_j+x_i)/(bv[i][j]**2*x_i+x_j))
                dFT_ki[j, i] = x_j*(x_j+x_i)/(bt[i][j]**2*x_j+x_i)+x_j*x_i / \
                    (bt[i][j]**2*x_j+x_i)*(1-(x_j+x_i)/(bt[i][j]**2*x_j+x_i))
                dFrho_ki[j, i] = x_j*(x_j+x_i)/(bv[i][j]**2*x_j+x_i)+x_j*x_i /\
                    (bv[i][j]**2*x_j+x_i)*(1-(x_j+x_i)/(bv[i][j]**2*x_j+x_i))

        sumai_v = sumaij_v = sumai_T = sumaij_T = m = 0
        for i, componentei in enumerate(self.comp):
            sumai_v += self.xi[i]**2/componentei.rhoc
            sumai_T += self.xi[i]**2*componentei.Tc
            m += self.xi[i]*componentei.M
            for j, componentej in enumerate(self.comp):
                if j > i:
                    sumaij_v += c_rho[i, j]*f_rho[i, j]
                    sumaij_T += c_T[i, j]*f_T[i, j]

        self.rhoc = unidades.Density(1./(sumai_v+sumaij_v))
        self.Tc = unidades.Temperature(sumai_T+sumaij_T)
        self.M = m  # g/mol
        self.R = unidades.SpecificHeat(R/self.M, "kJkgK")

        Tcxi = rhocxi = []
        for i, componentei in enumerate(self.comp):
            sumav1 = sumat1 = 0
            for k in range(i):
                sumav1 += c_rho[k, i]*dFrho_ki[k, i]
                sumat1 += c_T[k, i]*dFT_ki[k, i]
            sumav2 = sumat2 = 0
            for k in range(i+1, len(self.xi)):
                sumav2 += c_rho[i, k]*dFrho_ik[i, k]
                sumat2 += c_T[i, k]*dFT_ik[i, k]

            Tcxi.append(2*self.xi[i]*componentei.Tc+sumat1+sumat2)
            rhocxi.append(2*self.xi[i]/componentei.rhoc+sumav1+sumav2)
        self.Tcxi = Tcxi
        self.rhocxi = rhocxi

        if v and not rho:
            rho = 1./v

        if T and x is not None:
            pass
        else:
            if T and P:
                rhoo = 2.
                rho = fsolve(lambda rho: self._solve(rho, T)["P"]-P*1e6, rhoo)
            elif T and rho:
                pass
            elif T and h is not None:
                rho = fsolve(lambda rho: self._solve(rho, T)["h"]-h, 200)
            elif T and s is not None:
                rho = fsolve(lambda rho: self._solve(rho, T)["s"]-s, 200)
            elif T and u is not None:
                rho = fsolve(lambda rho: self._solve(rho, T)["u"]-u, 200)
            elif P and rho:
                T = fsolve(lambda T: self._solve(rho, T)["P"]-P*1e6, 600)
            elif P and h is not None:
                rho, T = fsolve(lambda par: (
                    self._solve(par[0], par[1])["P"]-P*1e6, self._solve(
                        par[0], par[1])["h"]-h), [200, 600])
            elif P and s is not None:
                rho, T = fsolve(lambda par: (
                    self._solve(par[0], par[1])["P"]-P*1e6, self._solve(
                        par[0], par[1])["s"]-s), [200, 600])
            elif P and u is not None:
                rho, T = fsolve(lambda par: (
                    self._solve(par[0], par[1])["P"]-P*1e6, self._solve(
                        par[0], par[1])["u"]-u), [200, 600])
            elif rho and h is not None:
                T = fsolve(lambda T: self._solve(rho, T)["h"]-h, 600)
            elif rho and s is not None:
                T = fsolve(lambda T: self._solve(rho, T)["s"]-s, 600)
            elif rho and u is not None:
                T = fsolve(lambda T: self._solve(rho, T)["u"]-u, 600)
            elif h is not None and s is not None:
                rho, T = fsolve(lambda par: (
                    self._solve(par[0], par[1])["h"]-h, self._solve(
                        par[0], par[1])["s"]-s), [200, 600])
            elif h is not None and u is not None:
                rho, T = fsolve(lambda par: (
                    self._solve(par[0], par[1])["h"]-h, self._solve(
                        par[0], par[1])["u"]-u), [200, 600])
            elif s is not None and u is not None:
                rho, T = fsolve(lambda par: (
                    self._solve(par[0], par[1])["s"]-s, self._solve(
                        par[0], par[1])["u"]-u), [200, 600])
            else:
                raise IOError

        fio, fiot, fiott, fiod, fiodd, fiodt, fir, firt, firtt, fird, firdd,\
            firdt, firdtt, nfioni, nfirni = self._eq(rho, T)

        # Tabla 7.1 pag 127
        tau = self.Tc/T
        delta = rho/self.rhoc

        self.T = unidades.Temperature(T)
        self.rho = unidades.Density(rho)
        self.v = unidades.SpecificVolume(1./rho)
        self.P = unidades.Pressure((1+delta*fird)*self.R.JkgK*T*rho)
        self.Z = 1+delta*fird
        self.s = unidades.SpecificHeat(self.R.kJkgK*(tau*(fiot+firt)-fio-fir))
        self.u = unidades.Enthalpy(self.R*T*tau*(fiot+firt))
        self.h = unidades.Enthalpy(self.R*T*(1+tau*(fiot+firt)+delta*fird))
        self.cp = unidades.SpecificHeat(self.R*(
            -tau**2*(fiott+firtt)+(1+delta*fird-delta*tau*firdt)**2 /
            (1+2*delta*fird+delta**2*firdd)))
        self.cv = unidades.SpecificHeat(-self.R*tau**2*(fiott+firtt))
        self.g = unidades.Enthalpy(self.R*T*(1+fio+fir+delta*fird))
        self.w = unidades.Speed((self.R*T*(
            1+2*delta*fird+delta**2*firdd-(1+delta*fird-delta*tau*firdt)**2 /
            tau**2/(fiott+firtt)))**0.5)

        f, FI = self.fug(rho, T, nfirni)
        Ki, xi, yi, Q = self.flash()
        self.x = unidades.Dimensionless(Q)
        self.xl = xi
        self.xv = yi
        if self.kwargs["mezcla"]:
            self.Pc = self.kwargs["mezcla"].Pc
        self.Liquido = ThermoAdvanced()
        self.Gas = ThermoAdvanced()
示例#7
0
    def calculo(self):
        fluido = self._name()
        args = self.args()
        estado = CP.AbstractState("HEOS", fluido)
        if self._multicomponent:
            estado.set_mole_fractions(self.kwargs["fraccionMolar"])
        estado.update(self._par, *args)

        self.M = unidades.Dimensionless(estado.molar_mass()*1000)

        if self._multicomponent:
            # Disabled CoolProp critical properties for multicomponent,
            # see issue #1087

            # Calculate critical properties with mezcla method
            # Coolprop for mixtures can fail and it's slow
            Cmps = [Componente(int(i)) for i in self.kwargs["ids"]]

            # Calculate critic temperature, API procedure 4B1.1 pag 304
            V = sum([xi*cmp.Vc for xi, cmp in
                     zip(self.kwargs["fraccionMolar"], Cmps)])
            k = [xi*cmp.Vc/V for xi, cmp in
                 zip(self.kwargs["fraccionMolar"], Cmps)]
            Tcm = sum([ki*cmp.Tc for ki, cmp in zip(k, Cmps)])
            self.Tc = unidades.Temperature(Tcm)

            # Calculate pseudocritic temperature
            tpc = sum([x*cmp.Tc for x, cmp in
                       zip(self.kwargs["fraccionMolar"], Cmps)])

            # Calculate pseudocritic pressure
            ppc = sum([x*cmp.Pc for x, cmp in
                       zip(self.kwargs["fraccionMolar"], Cmps)])

            # Calculate critic pressure, API procedure 4B2.1 pag 307
            sumaw = 0
            for xi, cmp in zip(self.kwargs["fraccionMolar"], Cmps):
                sumaw += xi*cmp.f_acent
            pc = ppc+ppc*(5.808+4.93*sumaw)*(self.Tc-tpc)/tpc
            self.Pc = unidades.Pressure(pc)

            # Calculate critic volume, API procedure 4B3.1 pag 314
            sumaxvc23 = sum([xi*cmp.Vc**(2./3) for xi, cmp in
                             zip(self.kwargs["fraccionMolar"], Cmps)])
            k = [xi*cmp.Vc**(2./3)/sumaxvc23 for xi, cmp in
                 zip(self.kwargs["fraccionMolar"], Cmps)]

            # TODO: Calculate C value from component type.
            # For now it suppose all are hidrycarbon (C=0)
            C = 0

            V = [[-1.4684*abs((cmpi.Vc-cmpj.Vc)/(cmpi.Vc+cmpj.Vc))+C
                  for cmpj in Cmps] for cmpi in Cmps]
            v = [[V[i][j]*(cmpi.Vc+cmpj.Vc)/2. for j, cmpj in enumerate(
                Cmps)] for i, cmpi in enumerate(Cmps)]
            suma1 = sum([ki*cmp.Vc for ki, cmp in zip(k, Cmps)])
            suma2 = sum([ki*kj*v[i][j] for j, kj in enumerate(k)
                         for i, ki in enumerate(k)])
            self.rhoc = unidades.Density((suma1+suma2)*self.M)

        else:
            self.Tc = unidades.Temperature(estado.T_critical())
            self.Pc = unidades.Pressure(estado.p_critical())
            self.rhoc = unidades.Density(estado.rhomass_critical())

        self.R = unidades.SpecificHeat(estado.gas_constant()/self.M)
        self.Tt = unidades.Temperature(estado.Ttriple())
        estado2 = CP.AbstractState("HEOS", fluido)
        if self._multicomponent:
            estado2.set_mole_fractions(self.kwargs["fraccionMolar"])
        estado2.update(CP.PQ_INPUTS, 101325, 1)
        self.Tb = unidades.Temperature(estado2.T())
        self.f_accent = unidades.Dimensionless(estado.acentric_factor())

        # Dipole moment only available for REFPROP backend
        # self.momentoDipolar(estado.keyed_output(CP.idipole_moment))

        self.phase, x = self.getphase(estado)
        self.x = unidades.Dimensionless(x)
        if self._multicomponent:
            string = fluido.replace("&", " (%0.2f), ")
            string += " (%0.2f)"
            self.name = string % tuple(self.kwargs["fraccionMolar"])
            self.CAS = ""
            self.synonim = ""
            self.formula = ""
        else:
            self.name = fluido
            self.CAS = estado.fluid_param_string("CAS")
            self.synonim = estado.fluid_param_string("aliases")
            self.formula = estado.fluid_param_string("formula")

        self.P = unidades.Pressure(estado.p())
        self.T = unidades.Temperature(estado.T())
        self.Tr = unidades.Dimensionless(self.T/self.Tc)
        self.Pr = unidades.Dimensionless(self.P/self.Pc)
        self.rho = unidades.Density(estado.rhomass())
        self.v = unidades.SpecificVolume(1./self.rho)

        cp0 = self._prop0(estado)
        self._cp0(cp0)

        self.Liquido = ThermoAdvanced()
        self.Gas = ThermoAdvanced()
        if self.x == 0:
            # liquid phase
            self.fill(self.Liquido, estado)
            self.fill(self, estado)
            self.fillNone(self.Gas)
        elif self.x == 1:
            # vapor phase
            self.fill(self.Gas, estado)
            self.fill(self, estado)
            self.fillNone(self.Liquido)
        else:
            # Two phase
            liquido = CP.AbstractState("HEOS", fluido)
            if self._multicomponent:
                xi = estado.mole_fractions_liquid()
                liquido.set_mole_fractions(xi)
            liquido.specify_phase(CP.iphase_liquid)
            liquido.update(CP.QT_INPUTS, 0, self.T)
            self.fill(self.Liquido, liquido)

            vapor = CP.AbstractState("HEOS", fluido)
            if self._multicomponent:
                yi = estado.mole_fractions_vapor()
                vapor.set_mole_fractions(yi)
            vapor.specify_phase(CP.iphase_gas)
            vapor.update(CP.QT_INPUTS, 1, self.T)
            self.fill(self.Gas, vapor)
            self.fill(self, estado)

        # Calculate special properties useful only for one phase
        if self._multicomponent:
            self.sigma = unidades.Tension(None)
        elif x < 1 and self.Tt <= self.T <= self.Tc:
            self.sigma = unidades.Tension(estado.surface_tension())
        else:
            self.sigma = unidades.Tension(None)

        self.virialB = unidades.SpecificVolume(estado.Bvirial())
        self.virialC = unidades.SpecificVolume_square(estado.Cvirial())
        self.invT = unidades.InvTemperature(-1/self.T)

        if 0 < self.x < 1:
            self.Hvap = unidades.Enthalpy(self.Gas.h-self.Liquido.h)
            self.Svap = unidades.SpecificHeat(self.Gas.s-self.Liquido.s)
        else:
            self.Hvap = unidades.Enthalpy(None)
            self.Svap = unidades.SpecificHeat(None)
示例#8
0
def createTabla(config, title, fluidos=None, parent=None):
    """Create TablaMEoS to add to mainwindow
        config: configparser instance with project configuration
        title: title for the table
        fluidos: optional array with meos instances to fill de table
        parent: mainwindow pointer
        """
    propiedades, keys, units = get_propiedades(config)

    # Add the unit suffix to properties title
    for i, unit in enumerate(units):
        sufx = unit.text()
        if not sufx:
            sufx = "[-]"
        propiedades[i] = propiedades[i] + os.linesep + sufx

    # Add two phases properties if requested
    if config.getboolean("MEoS", "phase"):
        for i in range(len(propiedades) - 1, -1, -1):
            if keys[i] in ThermoAdvanced.propertiesPhase():
                txt = [propiedades[i]]
                prefix = QtWidgets.QApplication.translate("pychemqt", "Liquid")
                txt.append(prefix + os.linesep + propiedades[i])
                prefix = QtWidgets.QApplication.translate("pychemqt", "Vapour")
                txt.append(prefix + os.linesep + propiedades[i])
                propiedades[i:i + 1] = txt
                units[i:i + 1] = [units[i]] * 3

    # Define common argument for TableMEoS
    kw = {}
    kw["horizontalHeader"] = propiedades
    kw["stretch"] = False
    kw["units"] = units
    kw["parent"] = parent
    kw["keys"] = keys

    if fluidos:
        # Generate a readOnly table filled of data
        tabla = TablaMEoS(len(propiedades), readOnly=True, **kw)
        data = []
        for fluido in fluidos:
            fila = _getData(fluido, keys, config.getboolean("MEoS", "phase"))
            data.append(fila)
        tabla.setData(data)

    else:
        # Generate a dinamic table empty
        columnInput = []
        for key in keys:
            if key in ["P", "T", "x", "rho", "v", "h", "s"]:
                columnInput.append(False)
            else:
                columnInput.append(True)
            if config.getboolean("MEoS", "phase") and \
                    key in ThermoAdvanced.propertiesPhase():
                columnInput.append(True)
                columnInput.append(True)
        kw["columnReadOnly"] = columnInput
        kw["dinamica"] = True

        # Discard the keys from single phase state as input values
        if config.getboolean("MEoS", "phase"):
            for i in range(len(keys) - 1, -1, -1):
                if keys[i] in ThermoAdvanced.propertiesPhase():
                    keys[i:i + 1] = [keys[i], "", ""]

        tabla = TablaMEoS(len(propiedades), filas=1, **kw)

    prefix = QtWidgets.QApplication.translate("pychemqt", "Table")
    tabla.setWindowTitle(prefix + ": " + title)
    tabla.resizeColumnsToContents()
    return tabla
示例#9
0
    def add(self, row):
        """Add point to a table and to saved file"""
        pref = QtWidgets.QApplication.translate("pychemqt", "Table from ")
        if pref in self.windowTitle():
            title = self.windowTitle().split(pref)[1]
            melting = title == QtWidgets.QApplication.translate(
                "pychemqt", "Melting Line")
        else:
            melting = False

        dlg = AddPoint(self.Point._new(), melting, self.parent)
        if dlg.exec_():
            self.blockSignals(True)
            if dlg.checkBelow.isChecked():
                row += 1

            plot = self.Plot
            if plot is None:
                plot = self._getPlot()

            if plot is None:
                # If table has no associated plot, define as normal point
                units = []
                for ui, order in zip(self.units, self.orderUnit):
                    if ui is unidades.Dimensionless:
                        units.append("")
                    else:
                        units.append(ui.__units__[order])
                phase = self.parent.currentConfig.getboolean("MEoS", "phase")
                datatoTable = _getData(dlg.fluid, self.keys, phase, units)
            else:
                # If table has a associated plot, use the values of that
                datatoTable = []
                datatoTable.append(dlg.fluid.__getattribute__(plot.x).config())
                datatoTable.append(dlg.fluid.__getattribute__(plot.y).config())

            # Add point to table
            self.addRow(index=row)
            self.setRow(row, datatoTable)

            # Update verticalHeader
            for row in range(self.rowCount()):
                self.setVHeader(row)

            # Add point to data plot
            if plot is None:
                return

            data = plot._getData()
            if title == QtWidgets.QApplication.translate(
                    "pychemqt", "Melting Line"):
                for x in ThermoAdvanced.propertiesKey():
                    data["melting"][x].insert(row,
                                              dlg.fluid.__getattribute__(x))
            elif title == QtWidgets.QApplication.translate(
                    "pychemqt", "Sublimation Line"):
                for x in ThermoAdvanced.propertiesKey():
                    data["sublimation"][x].insert(
                        row, dlg.fluid.__getattribute__(x))
            elif title == QtWidgets.QApplication.translate(
                    "pychemqt", "Saturation Line") or \
                    title == QtWidgets.QApplication.translate(
                        "pychemqt", "Liquid Saturation Line"):
                for x in ThermoAdvanced.propertiesKey():
                    data["saturation_0"][x].insert(
                        row, dlg.fluid.__getattribute__(x))
            elif title == QtWidgets.QApplication.translate(
                    "pychemqt", "Vapor Saturation Line"):
                for x in ThermoAdvanced.propertiesKey():
                    data["saturation_1"][x].insert(
                        row, dlg.fluid.__getattribute__(x))
            else:
                units = {
                    "P": unidades.Pressure,
                    "T": unidades.Temperature,
                    "h": unidades.Enthalpy,
                    "s": unidades.Enthalpy,
                    "v": unidades.SpecificVolume,
                    "rho": unidades.Density
                }
                var = str(title.split(" = ")[0])
                txt = title.split(" = ")[1]
                unit = units[var]
                value = float(txt.split(" ")[0])
                stdValue = str(unit(value, "conf"))

                for x in ThermoAdvanced.propertiesKey():
                    data[var][stdValue][x].insert(
                        row, dlg.fluid.__getattribute__(x))
            plot._saveData(data)

            # Add point to data
            for line in plot.plot.ax.lines:
                if str(line.get_label()) == str(title):
                    xdata = insert(line._x, row, datatoTable[0])
                    ydata = insert(line._y, row, datatoTable[1])
                    line.set_xdata(xdata)
                    line.set_ydata(ydata)
                    plot.plot.draw()
                    break

            self.blockSignals(False)
示例#10
0
    def delete(self, rows):
        """Delete rows from table and for saved data"""
        self.parent.statusbar.showMessage(
            QtWidgets.QApplication.translate("pychemqt", "Deleting point..."))
        QtWidgets.QApplication.processEvents()

        # Delete point from table
        for row in rows:
            self.removeRow(row)
            delete(self.data, row)

        # Update verticalHeader
        for row in range(self.rowCount()):
            self.setVHeader(row)

        # Delete point from data plot
        plot = self._getPlot()
        if plot:
            data = plot._getData()
            pref = QtWidgets.QApplication.translate("pychemqt", "Table from")
            title = self.windowTitle().split(pref)[1][1:]
            for row in rows:
                if title == QtWidgets.QApplication.translate(
                        "pychemqt", "Melting Line"):
                    for x in ThermoAdvanced.propertiesKey():
                        del data["melting"][x][row]
                elif title == QtWidgets.QApplication.translate(
                        "pychemqt", "Sublimation Line"):
                    for x in ThermoAdvanced.propertiesKey():
                        del data["sublimation"][x][row]
                elif title == QtWidgets.QApplication.translate(
                        "pychemqt", "Saturation Line") or \
                        title == QtWidgets.QApplication.translate(
                            "pychemqt", "Liquid Saturation Line"):
                    for x in ThermoAdvanced.propertiesKey():
                        del data["saturation_0"][x][row]
                elif title == QtWidgets.QApplication.translate(
                        "pychemqt", "Vapor Saturation Line"):
                    for x in ThermoAdvanced.propertiesKey():
                        del data["saturation_1"][x][row]
                else:
                    units = {
                        "P": unidades.Pressure,
                        "T": unidades.Temperature,
                        "h": unidades.Enthalpy,
                        "s": unidades.Enthalpy,
                        "v": unidades.SpecificVolume,
                        "rho": unidades.Density
                    }
                    var = str(title.split(" = ")[0])
                    txt = title.split(" = ")[1]
                    unit = units[var]
                    value = float(txt.split(" ")[0])
                    stdValue = str(unit(value, "conf"))
                    for x in ThermoAdvanced.propertiesKey():
                        del data[var][stdValue][x][row]
            plot._saveData(data)

            # Delete point from data
            for line in plot.plot.ax.lines:
                if str(line.get_label()) == str(title):
                    xdata = line._x
                    ydata = line._y
                    for row in rows:
                        xdata = delete(xdata, row)
                        ydata = delete(ydata, row)
                    line.set_xdata(xdata)
                    line.set_ydata(ydata)
                    plot.plot.draw()
                    break
        self.parent.statusbar.clearMessage()
示例#11
0
    def __init__(self, config=None, parent=None):
        super(Ui_Properties, self).__init__(parent)
        if config and config.has_option("MEoS", "properties"):
            values = config.get("MEoS", "properties")
            if isinstance(values, str):
                values = eval(values)
            fase = config.getboolean("MEoS", "phase")
            self.order = config.get("MEoS", "propertiesOrder")
            if isinstance(self.order, str):
                self.order = eval(self.order)
        else:
            values = self._default
            fase = False
            self.order = list(range(N_PROP))

        self.setWindowTitle(
            QtWidgets.QApplication.translate("pychemqt", "Select Properties"))
        layout = QtWidgets.QGridLayout(self)
        self.prop = QtWidgets.QTableWidget(len(ThermoAdvanced.properties()), 2)
        self.prop.verticalHeader().hide()
        self.prop.horizontalHeader().hide()
        self.prop.horizontalHeader().setStretchLastSection(True)
        self.prop.setGridStyle(QtCore.Qt.NoPen)
        self.prop.setColumnWidth(0, 18)
        self.prop.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
        self.prop.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
        self.prop.setItemDelegateForColumn(0, CheckEditor(self))
        for i, value in enumerate(values):
            if value == 1:
                val = "1"
            else:
                val = ""
            self.prop.setItem(i, 0, QtWidgets.QTableWidgetItem(val))
            name = ThermoAdvanced.propertiesName()[self.order[i]]
            self.prop.setItem(i, 1, QtWidgets.QTableWidgetItem(name))
            self.prop.setRowHeight(i, 20)
            self.prop.openPersistentEditor(self.prop.item(i, 0))
        self.prop.currentCellChanged.connect(self.comprobarBotones)
        self.prop.cellDoubleClicked.connect(self.toggleCheck)
        layout.addWidget(self.prop, 1, 1, 6, 1)

        self.ButtonArriba = QtWidgets.QToolButton()
        self.ButtonArriba.setIcon(QtGui.QIcon(QtGui.QPixmap(
            os.environ["pychemqt"] +
            os.path.join("images", "button", "arrow-up.png"))))
        self.ButtonArriba.clicked.connect(self.Up)
        layout.addWidget(self.ButtonArriba, 3, 2, 1, 1)
        self.ButtonAbajo = QtWidgets.QToolButton()
        self.ButtonAbajo.setIcon(QtGui.QIcon(QtGui.QPixmap(
            os.environ["pychemqt"] +
            os.path.join("images", "button", "arrow-down.png"))))
        self.ButtonAbajo.clicked.connect(self.Down)
        layout.addWidget(self.ButtonAbajo, 4, 2, 1, 1)

        self.checkFase = QtWidgets.QCheckBox(QtWidgets.QApplication.translate(
            "pychemqt", "Show bulk, liquid and vapor properties"))
        self.checkFase.setChecked(fase)
        layout.addWidget(self.checkFase, 7, 1, 1, 2)
        self.buttonBox = QtWidgets.QDialogButtonBox(
            QtWidgets.QDialogButtonBox.Reset | QtWidgets.QDialogButtonBox.Ok |
            QtWidgets.QDialogButtonBox.Cancel)
        self.buttonBox.addButton(
            QtWidgets.QApplication.translate("pychemqt", "Mark all"),
            QtWidgets.QDialogButtonBox.ResetRole)
        self.buttonBox.addButton(
            QtWidgets.QApplication.translate("pychemqt", "No Mark"),
            QtWidgets.QDialogButtonBox.ResetRole)
        self.btYes = QtWidgets.QPushButton
        self.buttonBox.clicked.connect(self.buttonClicked)
        layout.addWidget(self.buttonBox, 8, 1, 1, 2)
示例#12
0
###############################################################################
# Library function for plugin
#   - getMethod: Return the thermo method name to use
#   - getClassFluid: Return the thermo class to calculate
#   - calcPoint: Calculate point state and check state in P-T range of eq
#   - get_propiedades: Get the properties to show in tables
#   - _getData: Get values of properties in fluid
###############################################################################

from configparser import ConfigParser

from lib import mEoS, coolProp, refProp, config, unidades
from lib.thermo import ThermoAdvanced

N_PROP = len(ThermoAdvanced.properties())
KEYS = ThermoAdvanced.propertiesKey()
UNITS = ThermoAdvanced.propertiesUnit()


def getMethod(pref=None):
    """Return the thermo method name to use"""
    if pref is None:
        pref = ConfigParser()
        pref.read(config.conf_dir + "pychemqtrc")

        if pref.getboolean("MEOS", 'coolprop') and \
                pref.getboolean("MEOS", 'refprop'):
            txt = "refprop"
        elif pref.getboolean("MEOS", 'coolprop'):
            txt = "coolprop"