Exemple #1
0
    def OnGridEditStore(self, event):
        value = self.grid1.GetCellValue(self.lastEditRow, self.lastEditCol)
        row = self.table.select({self.table.keys()[0]:self.grid1.GetCellValue(self.lastEditRow,0)})[0]
        row[self.lastEditCol] = check(value)

        self.lastEditRow = 0
        self.lastEditCol = 0
        event.Skip()
    def __storeTCAContingenciesDataEntry(self):
        #print "Store Data (Contingencies)"
        for contingency in self.contingencies:
#            query = u"""INSERT INTO tcacontingencies (TcaID, Description, Value, TimeFrame)
#                       VALUES(%s,\"%r\",%s,%s)"""
#            query = query %(self.tcaid,contingency[0],contingency[1],contingency[2])
#            Status.DB.sql_query(query)                          

            tmp = {"TcaID": self.tcaid,
                   "Description": check(contingency[0]),
                   "Value": contingency[1],
                   "TimeFrame": contingency[2]}
            Status.DB.tcacontingencies.insert(tmp)
            Status.SQL.commit()
    def __storeTCAEnergyDataEntry(self):
        #print "Store Data (Energy)"
        for energycost in self.energycosts:
#            query = """INSERT INTO tcaenergy (TcaID, Description, EnergyDemand, EnergyPrice, DevelopmentOfEnergyPrice)
#                       VALUES(%s,\"%r\",%s,%s,%s)"""
#            query = query %(self.tcaid,energycost[0],energycost[1],energycost[2],energycost[3])
#            Status.DB.sql_query(query)

            tmp = {"TcaID": self.tcaid,
                   "Description": check(energycost[0]),
                   "EnergyDemand": energycost[1],
                   "EnergyPrice": energycost[2],
                   "DevelopmentOfEnergyPrice": energycost[3]}
            Status.DB.tcaenergy.insert(tmp)
    def __storeTCANonDataEntry(self):
        #print "Store Data (Non reocurring costs)"
        for cost in self.nonreoccuringcosts:
#            query = u"""INSERT INTO tcanonreoccuringcosts (TcaID, Description, Value, Year, Type)
#                       VALUES(%s,\"%r\",%s,%s,\"%s\")"""
#            query = query %(self.tcaid,cost[0],cost[1],cost[2],cost[3])
#            Status.DB.sql_query(query)  

            tmp = {"TcaID": self.tcaid,
                   "Description": check(cost[0]),
                   "Value": cost[1],
                   "Year": cost[2],
                   "Type": cost[3]}
            Status.DB.tcanonreoccuringcosts.insert(tmp)
            Status.SQL.commit()
    def __storeTCAInvestmentDataEntry(self):
        #print "Store Data (Investment)"
        for investment in self.investment:
#            query = """INSERT INTO tcainvestments (TcaID, Description, Investment, FundingPerc, FundingFix)
#                       VALUES(%s,\"%r\",%s,%s,%s)"""
#            query = query %(self.tcaid,investment[0],investment[1],investment[2],investment[3])
#            Status.DB.sql_query(query)

# insert command subsituted by the following. -> has no problems with non-ascii characters in description !!!
            tmp = {"TcaID":self.tcaid,
                   "Description":check(investment[0]),
                   "Investment":investment[1],
                   "FundingPerc":investment[2],
                   "FundingFix":investment[3]}
            
            Status.DB.tcainvestments.insert(tmp)
    def __storeTCADetailedOpCostDataEntry(self):
        #print "Store Data (Detailed operting cost)"
        for i in range(0,7): #7 categorys in detailed opcost
            for opcost in self.detailedopcost[i]:
#                query = u"""INSERT INTO tcadetailedopcost (TcaID, Description, Value, Category)
#                           VALUES(%s,\"%r\",%s,%s)"""
#                query = query %(self.tcaid,opcost[0],opcost[1],i)
#                Status.DB.sql_query(query) 

                tmp = {"TcaID": self.tcaid,
                       "Description": check(opcost[0]),
                       "Value": opcost[1],
                       "Category": i}
                Status.DB.tcadetailedopcost.insert(tmp)
                Status.SQL.commit()
        
        query = """UPDATE tcageneraldata 
                SET TotalOperatingCost = %s
                WHERE IDTca=%s"""
        query = query %(self.totalopcost,self.tcaid)
        Status.DB.sql_query(query)                                       
Exemple #7
0
def getConnections():
#------------------------------------------------------------------------------
#   Gets the connections from the entries in the SQL
#------------------------------------------------------------------------------
        
#..............................................................................
# get list of sub-systems

    fuels = Status.prj.getFuels()
    Status.NFuels = len(fuels)
    Status.NFET = Status.NFuels+1
    NI = Status.NFET
    
    equipments = Status.prj.getEquipments()
    Status.NEquipe = len(equipments)
    NJ = Status.NEquipe
    
    pipes = Status.prj.getPipes()
    Status.NPipeDuct = len(pipes)
    NM = Status.NPipeDuct

    processes = Status.prj.getProcesses()
    Status.NThProc = len(processes)
    NK = Status.NThProc
    
    hxes = Status.prj.getHXes()
    Status.NHX = len(hxes)
    NH = Status.NHX
    
    whees = Status.prj.getWHEEs()
    Status.NWHEE = len(whees)
    NN = Status.NWHEE

#..............................................................................
# 1. FETi-FETj-Link: fuels used in equipment

    fuelIDs_i = Status.prj.getFuelList("DBFuel_id")
    
    fuelIDs_j = Status.prj.getEquipmentList("DBFuel_id")

#    print "Connect: fuelIDs_i",fuelIDs_i
#    print "Connect: fuelIDs_j",fuelIDs_j
   

    Status.FETFuelLink = arange((NI-1)*NJ).reshape(NJ,(NI-1))  # reshape(rows,cols)
    Status.FETelLink = arange(1*NJ).reshape(NJ,1)  # reshape(rows,cols)
    
    check_j = []
    check_i = []
    for i in range(NI-1):
        check_i.append(0)
        
    for j in range(NJ):
        check_j.append(0)
        
        for i in range(NI-1):
            if fuelIDs_i[i] == fuelIDs_j[j]:
                Status.FETFuelLink[j][i] = 1
                check_j[j] = 1
                check_i[i] = 1
            else:
                Status.FETFuelLink[j][i] = 0
        Status.FETelLink[j][0] = 1  #all equipments potentially consume something of (parasitic) electricity.

#    print "Connect: FETLink created"
#    print Status.FETFuelLink
#    print Status.FETelLink
    for j in range(NJ):
        if check_j[j] == 0 and fuelIDs_j[j] is not None:
            showError(_("Fuel used in equipment no. %s is not specified or is not in fuel list")%(j+1))
        
#..............................................................................
# 2. USHj-USHm-Link: conecction equipment to pipe

    pipes_j = Status.prj.getEqList("PipeDuctEquip")
        
    pipeID_m = Status.prj.getPipeList("QDistributionHC_ID")

#    print "Connect: pipes_j",pipes_j
#    print "Connect: pipeID_m",pipeID_m
       
    Status.USHLink = arange(NJ*NM).reshape(NM,NJ)  # reshape(rows,cols)

    check_j = []
    for j in range(NJ):
        check_j.append(0)

    for m in range(NM):        
        for j in range(NJ):
            pipeIDs_j = []
            if pipes_j[j] is not None:
                pipesSplit = pipes_j[j].split(';')
                for i in range(len(pipesSplit)):
                    try:
                        pipeIDs_j.append(long(pipesSplit[i]))
                    except:
                        logDebug("Connect: erroneous value in pipe-string [%s][%s]"%\
                                 (pipesSplit[i],pipes_j[j]))
#                print "Connect: pipeIDs_j[%s]"%j,pipeIDs_j
                
            if pipeID_m[m] in pipeIDs_j:
                Status.USHLink[m][j] = 1
                check_j[j] = 1
            else:
                Status.USHLink[m][j] = 0
        
#    print "Connect: USHLink created"
#    print Status.USHLink
    for j in range(NJ):
        if check_j[j] == 0:
            showError(_("Equipment no. %s is not connected to any pipe")%(j+1))

#..............................................................................
# 3. UPHm-UPHk Link: conecction pipe to process

    check_k = []

    pipeName_k = Status.prj.getProcessList("PipeDuctProc")    
    pipeName_m = Status.prj.getPipeList("Pipeduct")

#    print "Connect: pipeName_k",pipeName_k
#    print "Connect: pipeName_m",pipeName_m
       
    Status.UPHLink = arange(NM*NK).reshape(NK,NM)  # reshape(rows,cols)

    for k in range(NK):
        check_k.append(0)
        for m in range(NM):
            if pipeName_m[m] == pipeName_k[k]:
                Status.UPHLink[k][m] = 1
                check_k[k] = 1
            else:
                Status.UPHLink[k][m] = 0
        
#    print "Connect: UPHLink created"
#    print Status.UPHLink

#..............................................................................
# 4. QHX/QWH - Eq/Pipe/Proc Links

    sourceName_h = Status.prj.getHXList("HXSource")    
    sinkName_h = Status.prj.getHXList("HXSink")

    procName_k = Status.prj.getProcessList("Process")
    pipeName_m = Status.prj.getPipeList("Pipeduct")
    equipeName_j = Status.prj.getEquipmentList("Equipment")
    wheeName_n = Status.prj.getWHEEList("WHEEName")

#    print "Connect: sourceName_h",sourceName_h
#    print "Connect: sinkName_h",sinkName_h
#    print "Connect: procName_k",procName_k
#    print "Connect: pipeName_m",pipeName_m
#    print "Connect: equipeName_j",equipeName_j
#    print "Connect: wheeName_n",wheeName_n
       
    Status.QWHEqLink = arange(NJ*NH).reshape(NJ,NH)  
    Status.QWHPipeLink = arange(NM*NH).reshape(NM,NH)
    Status.QWHProcLink = arange(NK*NH).reshape(NK,NH)
    Status.QWHEELink = arange(NN*NH).reshape(NN,NH)

    Status.QHXEqLink = arange(NJ*NH).reshape(NJ,NH)
    Status.QHXPipeLink = arange(NM*NH).reshape(NM,NH)
    Status.QHXProcLink = arange(NK*NH).reshape(NK,NH)
    
    for h in range(NH):
        sourceFluidID = None
        sinkFluidID = None
        
        for j in range(NJ):
            if sourceName_h[h] == equipeName_j[j]:
                Status.QWHEqLink[j][h] = 1
                sourceFluidID = None
            else:
                Status.QWHEqLink[j][h] = 0
                
            if sinkName_h[h] == equipeName_j[j]:
                Status.QHXEqLink[j][h] = 1
                sinkFluidID = None
            else:
                Status.QHXEqLink[j][h] = 0
        
        for m in range(NM):
            if sourceName_h[h] == pipeName_m[m]:
                Status.QWHPipeLink[m][h] = 1

                pipes = Status.DB.qdistributionhc.\
                        Questionnaire_id[Status.PId].\
                        AlternativeProposalNo[Status.ANo].\
                        Pipeduct[sourceName_h[h]]
                if len(pipes) > 0:
                    sourceFluidID = pipes[0].HeatDistMedium

            else:
                Status.QWHPipeLink[m][h] = 0
                
            if sinkName_h[h] == pipeName_m[m]:
                Status.QHXPipeLink[m][h] = 1

                pipes = Status.DB.qdistributionhc.\
                        Questionnaire_id[Status.PId].\
                        AlternativeProposalNo[Status.ANo].\
                        Pipeduct[sinkName_h[h]]
                if len(pipes) > 0:
                    sinkFluidID = pipes[0].HeatDistMedium

            else:
                Status.QHXPipeLink[m][h] = 0
        
        for k in range(NK):
            if sourceName_h[h] == procName_k[k]:
                Status.QWHProcLink[k][h] = 1

                processes = Status.DB.qprocessdata.\
                        Questionnaire_id[Status.PId].\
                        AlternativeProposalNo[Status.ANo].\
                        Process[sourceName_h[h]]
                if len(processes) > 0:
                    sourceFluidID = processes[0].ProcMedOut

            else:
                Status.QWHProcLink[k][h] = 0
                
            if sinkName_h[h] == procName_k[k]:
                Status.QHXProcLink[k][h] = 1
                check_k[k] = 1

                processes = Status.DB.qprocessdata.\
                        Questionnaire_id[Status.PId].\
                        AlternativeProposalNo[Status.ANo].\
                        Process[sinkName_h[h]]
                if len(processes) > 0:
                    sinkFluidID = processes[0].SupplyMedDBFluid_id
            else:
                Status.QHXProcLink[k][h] = 0
        
        for n in range(NN):                         #WHEE can only be source, not sink !!!
            if sourceName_h[h] == wheeName_n[n]:
                Status.QWHEELink[n][h] = 1

                whees = Status.DB.qwasteheatelequip.\
                        ProjectID[Status.PId].\
                        AlternativeProposalNo[Status.ANo].\
                        WHEEName[sourceName_h[h]]
                if len(whees) > 0:
                    sourceFluidID = whees[0].WHEEMedium
            else:
                Status.QWHEELink[n][h] = 0


        hxes = Status.DB.qheatexchanger.\
                        ProjectID[Status.PId].\
                        AlternativeProposalNo[Status.ANo].\
                        HXNo[h+1]
        if len(hxes) > 0:
            hxes[0].FluidIDSource = check(sourceFluidID)
            hxes[0].FluidIDSink = check(sinkFluidID)

    Status.SQL.commit()
    
#    print "Connect: QWHEqLink created"
#    print Status.QWHEqLink
#    print "Connect: QHXEqLink created"
#    print Status.QHXEqLink
#    print "Connect: QWHPipeLink created"
#    print Status.QWHPipeLink
#    print "Connect: QHXPipeLink created"
#    print Status.QHXPipeLink
#    print "Connect: QWHProcLink created"
#    print Status.QWHProcLink
#    print "Connect: QHXProcLink created"
#    print Status.QHXProcLink
#    print "Connect: QWHEELink created"
#    print Status.QWHEELink

    for k in range(NK):
        if check_k[k] == 0:
            showError(_("No heat supply (pipe or heat exchanger) connected to process no. %s")%(k+1))
    def updatePanel(self):
#------------------------------------------------------------------------------
#   send information to the GUI necessary for updating the panel
#------------------------------------------------------------------------------

#..............................................................................
# first collect the information for all the alternatives in the project

        sqlQuery = "Questionnaire_id = '%s' ORDER BY AlternativeProposalNo ASC"%(Status.PId)
        generalData = Status.DB.cgeneraldata.sql_select(sqlQuery)

        sqlQuery = "ProjectID = '%s' ORDER BY AlternativeProposalNo ASC"%(Status.PId)
        salternatives = Status.DB.salternatives.sql_select(sqlQuery)

        sqlQuery = "Questionnaire_id = '%s' ORDER BY AlternativeProposalNo ASC"%(Status.PId)
        qelectricity = Status.DB.qelectricity.sql_select(sqlQuery)

        qq = Status.DB.questionnaire.Questionnaire_ID[Status.PId]
        if len(qq) > 0:
            questionnaire = qq[0]
        else:
            questionnaire = None

######XXX TEST TEST TEST TEST TEST ###########################################3
        Status.StatusECO = 1
        logDebug("ModuleCS: WARNING -- StatusECO always set to 1 !!!!")


        PEC = []

        PECTable = []
        PECPlot = []
        
#Panel CS1: Primary energy
        if self.keys[0] == "CS1_Plot":
            
            PEC0 = 0.0

            presentAlternative = Status.ANo
                    
            for ANo in range(len(generalData)-1):
                i = ANo+1

                if salternatives[i].StatusEnergy == 0:
                    Status.prj.setActiveAlternative(ANo)
                    Status.mod.moduleEA.update()

                if salternatives[i].StatusEnergy > 0:
                    dPEC = generalData[i].PEC                
                
                    if dPEC is None:
                        dPEC = 0.0
                        dPEC_Table = "---"
                    else:
                        dPEC /= 1000.0  #conversion kWh -> MWh
                        dPEC_Table = dPEC

                    if ANo == 0:
                        PEC0 = dPEC

                    PECSaving = PEC0 - dPEC #SD corrected, was inverted
                    if PEC0 > 0:
                        RelSaving = PECSaving/PEC0
                    else:
                        RelSaving = 0.0

                else:
                    dPEC = 0.0
                    dPEC_Table = "---"
                    PECSaving = "---"
                    RelSaving = "---"
                        
                PEC.append(dPEC)

                if ANo != 0: #SD corrected, was ==
                    tableEntry = noneFilter([unicode(salternatives[i].ShortName,"utf-8"),dPEC_Table,PECSaving,RelSaving*100])
                else:
                    tableEntry = noneFilter([unicode(salternatives[i].ShortName,"utf-8"),dPEC_Table,"---","---"])
                plotEntry = noneFilter([unicode(salternatives[i].ShortName,"utf-8"),dPEC])
                
                PECTable.append(tableEntry)
                PECPlot.append(plotEntry)
                            
            if Status.ANo <> presentAlternative:
                Status.prj.setActiveAlternative(presentAlternative)
#..............................................................................
# then send everything to the GUI

            data1 = array(PECTable)
                              
            Status.int.setGraphicsData("CS1_Table", data1)

            matrix2 = transpose(PECPlot)
            data2 = array(PECPlot)

            Status.int.setGraphicsData("CS1_Plot", data2)

#            print 'Table: data1\n',data1
#            print 'Plot: data2\n',data2

            PECReport = copy.deepcopy(PECTable)
            for i in range(len(PECTable),11):
                PECReport.append([" "," "," "," "])
            dataReport1 = array(PECReport)                  
            Status.int.setGraphicsData("CS1_REPORT", dataReport1)

#------------------------------------------------------------------------------

#------------------------------------------------------------------------------
# Panel CS2: Process & supply heat
        elif self.keys[0] == "CS2_Plot":

#............................................................................
# charge UPH and USH data from SQL
            UPH = []
            USH = []
            Alternative = []

            CS2Table = []
            CS2Plot = []

            USH0 = 0.0
            UPH0 = 0.0
            
            for ANo in range(len(generalData)-1):
                i = ANo+1

                if salternatives[i].ShortName is None:
                    Alternative.append('--')
                else:
                    Alternative.append(unicode(salternatives[i].ShortName,"utf-8"))

                if salternatives[i].StatusEnergy > 0:
                    dUSH = generalData[i].USH
                    dUPH = generalData[i].UPH
                    if dUSH is None:
                        dUSH = 0.0
                        dUSH_Table = "---"
                    else:
                        dUSH /= 1000.0  #conversion kWh -> MWh
                        dUSH_Table = dUSH

                    if dUPH is None:
                        dUPH = 0.0
                        dUPH_Table = "---"
                    else:
                        dUPH /= 1000.0  #conversion kWh -> MWh
                        dUPH_Table = dUPH #SD: gazapo aqui, era (= dUSH)!!!

                    if ANo == 0: #SD: here passes the first time only and calculates USH0, UPH0
                        USH0 = dUSH #can be assigned once, why check each time?
                        UPH0 = dUPH

                    USHSaving = USH0 - dUSH #SD: inverted-changed sign
                    if USH0 > 0:
                        RelSavingUSH = USHSaving/USH0
                        if dUSH_Table == "---":
                            RatioUSH = 0.0
                        else:
                            RatioUSH = dUSH*100.0/USH0 #SD in %
                    else:
                        RelSavingUSH = 0.0
                        RatioUSH = 0.0 #SD in %

                    UPHSaving = UPH0 - dUPH #SD: inverted-changed sign
                    if UPH0 > 0:
                        RelSavingUPH = UPHSaving/UPH0
                        if dUPH_Table == "---":
                            RatioUPH = 0.0
                        else:
                            RatioUPH = dUPH*100.0/UPH0 #SD in %
                    else:
                        RelSavingUPH = 0.0
                        RatioUPH = 0.0 #SD in %

                else:
                    dUSH = 0.0
                    dUPH = 0.0
                    dUSH_Table = "---"
                    dUPH_Table = "---"
                    USHSaving = "---"
                    UPHSaving = "---"
                    RelSavingUSH = 0.0 #SD: before "---" (could be plot data)
                    RelSavingUPH = 0.0 #SD: before "---" (could be plot data)
                    RatioUSH = 0.0
                    RatioUPH = 0.0
                        
                USH.append(dUSH) #SD: these are not used
                UPH.append(dUPH) #SD: these are not used


                if ANo == 0:
                    tableEntry = noneFilter([unicode(salternatives[i].ShortName,"utf-8"),
                                             dUPH_Table,"---",
                                             dUSH_Table,"---"])
                else:
                    tableEntry = noneFilter([unicode(salternatives[i].ShortName,"utf-8"),
                                             dUPH_Table,UPHSaving,
                                             dUSH_Table,USHSaving])
                plotEntry = noneFilter([unicode(salternatives[i].ShortName,"utf-8"),RatioUSH,RatioUPH]) #SD: before: dUSH, dUPH

                CS2Table.append(tableEntry)
                CS2Plot.append(plotEntry)
#..............................................................................
# then send everything to the GUI

            data1 = array(CS2Table)
                              
            Status.int.setGraphicsData("CS2_Table", data1)

##            matrix2 = transpose(CS2Plot)
            data2 = array(CS2Plot)

            Status.int.setGraphicsData("CS2_Plot", data2)
##            print 'CS2 table =', data1
##            print 'CS2 plot =', data2
##            print 'USH =', USH
##            print 'UPH =', UPH

            CS2Report = copy.deepcopy(CS2Table)
            for i in range(len(CS2Table),11):
                CS2Report.append([" "," "," "," "," "])
            dataReport2 = array(CS2Report)                  
            Status.int.setGraphicsData("CS2_REPORT", dataReport2)

#------------------------------------------------------------------------------

#------------------------------------------------------------------------------
# Panel CS3: Ambiental impact
        elif self.keys[0] == "CS3_Plot":

#............................................................................
# charge UPH and USH data from SQL
            CO2El = []
            CO2Fuel = []
            CO2Total = []
            NucWaste = []
            WaterConsum = []
            Alternative = []

            CS3Table = []
            CS3Plot = []

            CO2_0 = 0
            NucWaste0 = 0
            WatConsum0 = 0

            for ANo in range(len(generalData)-1):
                i = ANo+1

                if salternatives[i].ShortName is None:
                    Alternative.append('--')
                else:
                    Alternative.append(unicode(salternatives[i].ShortName,"utf-8"))

                if generalData[i].ProdCO2el is None: #protection against None
                    CO2El.append(0.0)
                else:
                    CO2El.append(generalData[i].ProdCO2el/1000.0)   #kg -> tons

                if generalData[i].ProdCO2Fuels is None:
                    CO2Fuel.append(0.0)
                else:
                    CO2Fuel.append(generalData[i].ProdCO2Fuels/1000.0)  #kg -> tons

                CO2Total.append(CO2El[i-1]+CO2Fuel[i-1])#to i-1 (list from 0 to ANo)

                #nuclear waste from sql
                if generalData[i].ProdNoNukesEl is None:
                    NucWaste.append(0.0)
                else:
                    NucWaste.append(generalData[i].ProdNoNukesEl*1.e-6) #conversion mg-> kg

                WaterConsum.append(0.0)
                
                if salternatives[i].StatusEnergy > 0:
                    dCO2 = CO2Total[i-1]#to i-1 (list from 0 to ANo)
                    if dCO2 == 0.0:
                        dCO2_Table = "--"
                    else:
                        dCO2_Table = dCO2

                    dNucWaste = generalData[i].ProdNoNukesEl
                    if dNucWaste is None:
                        dNucWaste = 0.0
                        dNucWaste_Table = "---"
                    else:
                        dNucWaste = dNucWaste*1.e-6 #conversion mg-> kg
                        dNucWaste_Table = dNucWaste

                    dWatConsum = WaterConsum[i-1]#to i-1 (list from 0 to ANo)
                    dWatConsum_Table = dWatConsum
            
                    if ANo == 0:
                        CO2_0 = dCO2
                        NucWaste0 = dNucWaste
                        WatConsum0 = dWatConsum

                    CO2Saving = CO2_0 - dCO2
                    if CO2_0 > 0:
                        RelSavingCO2 = CO2Saving/CO2_0
                        RatioCO2 = dCO2*100.0/CO2_0 #in %
                    else:
                        RelSavingCO2 = 0.0
                        RatioCO2 = 0.0

                    NucWasteSaving = NucWaste0 - dNucWaste
                    if NucWaste0 > 0:
                        RelSavingNucWaste = NucWasteSaving/NucWaste0
                        RatioNucWaste = dNucWaste*100.0/NucWaste0 #in %
                    else:
                        RelSavingNucWaste = 0.0
                        RatioNucWaste = 0.0

                    WatConsumSaving = WatConsum0 - dWatConsum
                    if WatConsum0 > 0:
                        RelSavingWatConsum = WatConsumSaving/WatConsum0
                        RatioWatConsum = dWatConsum*100.0/WatConsum0 #in %
                    else:
                        RelSavingWatConsum = 0.0
                        RatioWatConsum = 0.0

                else:
                    dCO2 = 0.0
                    dNucWaste = 0.0
                    dWatConsum = 0.0
                    dCO2_Table = "---"
                    dNucWaste_Table = "---"
                    dWatConsum_Table = "---"
                    CO2Saving = "---"
                    NucWasteSaving = "---"
                    WatConsumSaving = "---"
                    RelSavingCO2 = 0.0
                    RelSavingNucWaste = 0.0
                    RelSavingWatConsum = 0.0
                    RatioCO2 = 0.0
                    RatioNucWaste = 0.0
                    RatioWatConsum = 0.0                    
                    

                tableEntry = noneFilter([unicode(salternatives[i].ShortName,"utf-8"),
                                         dCO2_Table,dNucWaste_Table,dWatConsum_Table])

                plotEntry = noneFilter([unicode(salternatives[i].ShortName,"utf-8"),RatioCO2,RatioNucWaste,RatioWatConsum])
               
                CS3Table.append(tableEntry)
                CS3Plot.append(plotEntry)
#..............................................................................
# then send everything to the GUI

            data1 = array(CS3Table)
                              
            Status.int.setGraphicsData("CS3_Table", data1)

##            matrix2 = transpose(CS3Plot)
            data2 = array(CS3Plot)

            Status.int.setGraphicsData("CS3_Plot", data2)

            CS3Report = copy.deepcopy(CS3Table)
            for i in range(len(CS3Table),11):
                CS3Report.append([" "," "," "," "])
            dataReport3 = array(CS3Report)                  
            Status.int.setGraphicsData("CS3_REPORT", dataReport3)

#------------------------------------------------------------------------------

##########################################################################
#------------------------------------------------------------------------------
# Panel CS4: Investment cost
        elif self.keys[0] == "CS4_Plot":

#............................................................................
# charge data from SQL
            TotalCost = []
            OwnCost = []
            Subsidies = []
            Alternative = []

            CS4Table = []
            CS4Plot = []

            TotalCost0 = 0
            OwnCost0 = 0
            Subsidies0 = 0

            for ANo in range(len(generalData)-1):
                    
                i = ANo+1

                if salternatives[i].ShortName is None:
                    Alternative.append('--')
                else:
                    Alternative.append(unicode(salternatives[i].ShortName,"utf-8"))

                if generalData[i].TotalInvCost is None: #protection against None
                    TotalCost.append(0.0)
                else:
                    TotalCost.append(generalData[i].TotalInvCost)

                if generalData[i].OwnInvCost is None:
                    OwnCost.append(0.0)
                else:
                    OwnCost.append(generalData[i].OwnInvCost)

                if generalData[i].Subsidies is None:
                    Subsidies.append(0.0)
                else:
                    Subsidies.append(generalData[i].Subsidies)

                
#                if salternatives[i].StatusECO > 0:
                dTotalCost = generalData[i].TotalInvCost
                if dTotalCost is None:
                    dTotalCost = 0.0
                    dTotalCost_Table = "---"
                else:
                    dTotalCost_Table = dTotalCost

                dOwnCost = generalData[i].OwnInvCost
                if dOwnCost is None:
                    dOwnCost = 0.0
                    dOwnCost_Table = "---"
                else:
                    dOwnCost_Table = dOwnCost

                dSubsidies = generalData[i].Subsidies
                if dSubsidies is None:
                    dSubsidies = 0.0
                    dSubsidies_Table = "---"
                else:
                    dSubsidies_Table = dSubsidies
        
                if ANo == 0:
                    TotalCost0 = dTotalCost
                    OwnCost0 = dOwnCost
                    Subsidies0 = dSubsidies


#            else:
#                dTotalCost = 0.0
#                dOwnCost = 0.0
#                dSubsidies = 0.0
#                dTotalCost_Table = "---"
#                dOwnCost_Table = "---"
#                dSubsidies_Table = "---"  
                

                tableEntry = noneFilter([unicode(salternatives[i].ShortName,"utf-8"),
                                         dTotalCost_Table,dOwnCost_Table,dSubsidies_Table])

#                plotEntry = noneFilter([unicode(salternatives[i].ShortName,"utf-8"),dOwnCost,dSubsidies])
                plotEntry = noneFilter([unicode(salternatives[i].ShortName,"utf-8"),dTotalCost,dOwnCost])
               
                CS4Table.append(tableEntry)
                CS4Plot.append(plotEntry)
#..............................................................................
# then send everything to the GUI

            data1 = array(CS4Table)
                              
            Status.int.setGraphicsData("CS4_Table", data1)

            data2 = array(CS4Plot)

            Status.int.setGraphicsData("CS4_Plot", data2)

            CS4Report = copy.deepcopy(CS4Table)
            for i in range(len(CS4Table),11):
                CS4Report.append([" "," "," "," "])
            dataReport4 = array(CS4Report)                  
            Status.int.setGraphicsData("CS4_REPORT", dataReport4)


#------------------------------------------------------------------------------

#------------------------------------------------------------------------------
# Panel CS5: Annual cost
        elif self.keys[0] == "CS5_Plot":

            print "CS5"
#............................................................................
# charge data from SQL

            Amortization = []
            ElCost = []

            FuelCost = [] # holds the fuels EnergyCost from ANo=0 to the ANo=last (all fuels)

            EnergyCost = []
            OMCost = []
            Alternative = []

            CS5Table = []
            CS5Plot = []

            Amortization0 = 0
            OMCost0 = 0
            EnergyCost0 = 0

            for ANo in range(len(generalData)-1):
                i = ANo+1

                if salternatives[i].ShortName is None:
                    Alternative.append('--')
                else:
                    Alternative.append(unicode(salternatives[i].ShortName,"utf-8"))

                if generalData[i].Amortization is None: #protection against None
                    Amortization.append(0.0)
                else:
                    Amortization.append(generalData[i].Amortization)

##### 2B CHECKED ... AT THE MOMENT OMTHERMAL FOR ANo = 0 IS IN QUESTIONNAIRE !!!
                if ANo == 0:
                    qq = Status.DB.questionnaire.Questionnaire_ID[Status.PId]
                    if len(qq) > 0:
                        generalData[i].OMThermal = check(qq[0].OMThermal)
                    
                if generalData[i].OMThermal is None: #here O&M costs for heat/cold generation and dist. considered
                    if ANo == 0:
                        logWarning(_("No OandM cost specified for present state"))
                    OMCost.append(0.0)
                else:
                    OMCost.append(generalData[i].OMThermal)

                if qelectricity[i].ElCostYearTot is None:
                    if ANo == 0:
                        logWarning(_("No electricity cost specified for present state"))
                        
                    ElCost.append(0.0)
                else:
                    ElCost.append(qelectricity[i].ElCostYearTot)

                sumcost = 0.0
                sqlQuery = "Questionnaire_id = '%s' AND AlternativeProposalNo = '%s'"%\
                           (Status.PId,ANo)
                fuelsByANo = Status.DB.qfuel.sql_select(sqlQuery)
                for fuel in fuelsByANo:
                    fuelcost = fuel['FuelCostYear']
                    if fuelcost is not None:
                        sumcost += fuelcost
                    else:
                        if ANo == 0:
                            logWarning(_("No fuel cost specified for  for present state for fuel no. %s ")%fuel.FuelNo)
                FuelCost.append(sumcost)

                if ANo == 0:
                    EnergyCost.append(ElCost[i-1]
                                      +FuelCost[i-1])

                else:
                    if generalData[i].EnergyCost is None:
                        EnergyCost.append(0.0)
                    else:
                        EnergyCost.append(generalData[i].EnergyCost)
                
#                if salternatives[i].StatusECO > 0: #SD: changed control 13/07/2008
                dAmortization = generalData[i].Amortization
                if dAmortization is None:
                    dAmortization = 0.0
                    dAmortization_Table = "---"
                else:
                    dAmortization_Table = dAmortization

                dOMCost = OMCost[ANo]
                if dOMCost is None or dOMCost == 'NULL':
                    dOMCost = 0.0
                    dOMCost_Table = "---"
                else:
                    dOMCost_Table = dOMCost
                print "dOMCost = ",dOMCost,dOMCost_Table

                dEnergyCost = EnergyCost[ANo]#to i-1 (list from 0 to ANo)
                if dEnergyCost == 0.0:
                    dEnergyCost_Table = "--"
                else:
                    dEnergyCost_Table = dEnergyCost

                if ANo == 0:
                    Amortization0 = dAmortization
                    OMCost0 = dOMCost
                    EnergyCost0 = dEnergyCost


#            else:
#                dAmortization = 0.0
#                dOMCost = 0.0
#                dEnergyCost = 0.0
#                dAmortization_Table = "---"
#                dOMCost_Table = "---"
#                dEnergyCost_Table = "---"  
                

            
                tableEntry = noneFilter([unicode(salternatives[i].ShortName,"utf-8"),
                                         dAmortization_Table,dEnergyCost_Table,dOMCost_Table])

                plotEntry = noneFilter([unicode(salternatives[i].ShortName,"utf-8"),\
                                        dAmortization+dEnergyCost+dOMCost,\
                                        dEnergyCost+dOMCost,\
                                        dOMCost])
               
                CS5Table.append(tableEntry)
                CS5Plot.append(plotEntry)

# economic parameters used in the analysis (for the report)

            if questionnaire is not None:
                if questionnaire.InterestExtFinancing is not None:
                    i = questionnaire.InterestExtFinancing
                else:
                    i = 0.06
                    
                if questionnaire.AmortisationTime is not None:
                    N = int(questionnaire.AmortisationTime)
                else:
                    N = 15
            else:
                i = 0.06
                N = 15

            sum = 0
            for n in range(1,N+1):
                sum += 1/pow(1.0+i,n)

            if sum > 0:
                annuity = 1./sum
            else:
                annuity = 1.0
                
            ecopars = [i*100.0,
                       N,
                       annuity*100.0]
#..............................................................................
# then send everything to the GUI

            data1 = array(CS5Table)
                              
            Status.int.setGraphicsData("CS5_Table", data1)

            data2 = array(CS5Plot)

            Status.int.setGraphicsData("CS5_Plot", data2)

            CS5Report = copy.deepcopy(CS5Table)
            for i in range(len(CS5Table),11):
                CS5Report.append([" "," "," "," "])
            dataReport5 = array(CS5Report)                  
            Status.int.setGraphicsData("CS5_REPORT", dataReport5)

            Status.int.setGraphicsData("CS5_REPORT_PARS", array(ecopars))

#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
# Panel CS6: Annual cost
        elif self.keys[0] == "CS6_Plot":

#............................................................................
# charge data from SQL

            EnergySystemCost = []
            PEC = []
            AddedCost = []
            AddedCost_Table = []
            AddedCostSavedPEC = []#SD check
            AddedCostSavedPEC_Table = []#SD check
            SavedPEC = []
            Alternative = []

            CS6Table = []
            CS6Plot = []


            PEC0 = 0.0
            EnergySystemCost0 = 0.0

            for ANo in range(len(generalData)-1):
                i = ANo+1

                if salternatives[i].ShortName is None:
                    Alternative.append('--')
                else:
                    Alternative.append(unicode(salternatives[i].ShortName,"utf-8"))

                if generalData[i].EnergySystemCost is None: #protection against None
                    EnergySystemCost.append(0.0)
                else:
                    EnergySystemCost.append(generalData[i].EnergySystemCost)

#                if salternatives[i].StatusEnergy > 0 and salternatives[i].StatusECO > 0:
                if salternatives[i].StatusEnergy > 0:
                    dPEC = generalData[i].PEC                
                    if dPEC is None:
                        dPEC = 0.0
                    else:
                        dPEC /= 1000.0  #conversion kWh -> MWh

                    dEnergySystemCost = generalData[i].EnergySystemCost
                    if dEnergySystemCost is None:
                        dEnergySystemCost = 0.0
                        dEnergySystemCost_Table = "---"
                    else:
                        dEnergySystemCost_Table = dEnergySystemCost
                    
                    if ANo == 0:
                        PEC0 = dPEC
                        EnergySystemCost0 = dEnergySystemCost


                    PECSaving = PEC0 - dPEC

       
                    AddCost = dEnergySystemCost - EnergySystemCost0
                    if dEnergySystemCost_Table == "---":
                        AddCost_Table = "---"
                    else:
                        AddCost_Table = AddCost


                    if PECSaving == 0.0:
                        AddCostSavedPEC = 0.0
                        AddCostSavedPEC_Table = "---"
                    else:
                        AddCostSavedPEC = AddCost/PECSaving
                        AddCostSavedPEC_Table = AddCostSavedPEC
   

                else:
                    dPEC = 0.0
                    PECSaving = 0.0
                    dEnergySystemCost = 0.0
                    AddCost = 0.0
                    AddCostSavedPEC = 0.0
                    dEnergySystemCost_Table = "---"
                    AddCost_Table = "---"
                    AddCostSavedPEC_Table = "---"
                        
                PEC.append(dPEC)
                SavedPEC.append(PECSaving)
                AddedCost.append(AddCost)
                AddedCost_Table.append(AddCost_Table)#SD check

                AddedCostSavedPEC.append(AddCostSavedPEC)#SD check


                tableEntry = noneFilter([unicode(salternatives[i].ShortName,"utf-8"),
                                         dEnergySystemCost_Table,AddCost_Table,AddCostSavedPEC_Table])

                plotEntry = noneFilter([unicode(salternatives[i].ShortName,"utf-8"),AddCostSavedPEC])
               
                CS6Table.append(tableEntry)
                CS6Plot.append(plotEntry)
#..............................................................................
# then send everything to the GUI
#            print 'AddedCost_Table =', AddedCost_Table
#            print 'PEC =', PEC
#            print 'AddedCostSavedPEC_Table =', AddedCostSavedPEC_Table
#            print '\n'
#            print 'AddedCost =', AddedCost
#            print 'SavedPEC =', SavedPEC
#            print 'PEC =', PEC
#            print 'AddedCostSavedPEC =', AddedCostSavedPEC          

            data1 = array(CS6Table)
                              
            Status.int.setGraphicsData("CS6_Table", data1)

            data2 = array(CS6Plot)

            Status.int.setGraphicsData("CS6_Plot", data2)

            CS6Report = copy.deepcopy(CS6Table)
            for i in range(len(CS6Table),11):
                CS6Report.append([" "," "," "," "])
            dataReport6 = array(CS6Report)                  
            Status.int.setGraphicsData("CS6_REPORT", dataReport6)
#------------------------------------------------------------------------------

#------------------------------------------------------------------------------
# Panel CS7: Annual cost
        elif self.keys[0] == "CS7_Plot":

#............................................................................
# charge data from SQL

            IRR = []
            IRR_Table = []
            PayBack = []
            PayBack_Table = []
            BCR = []
            BCR_Table = []
            
            Alternative = []

            CS7Table = []
            CS7Plot = []


            for ANo in range(len(generalData)-1):
                i = ANo+1

                if salternatives[i].ShortName is None:
                    Alternative.append('--')
                else:
                    Alternative.append(unicode(salternatives[i].ShortName,"utf-8"))

#### TEST TEST TEST TEST ###################
                salternatives[i].StatusECO = 1
                if salternatives[i].StatusECO > 0:
                    dIRR = generalData[i].IRR
                    dBCR = generalData[i].BCR
                    dPayBack = generalData[i].PayBack
                    if dIRR is None:
                        dIRR = 0.0
                        dIRR_Table = "---"
                    else:
                        dIRR *= 100
                        dIRR_Table = dIRR

                    if dPayBack is None:
                        dPayBack = 0.0
                        dPayBack_Table = "---"
                    else:
                        dPayBack_Table = dPayBack

                    if dBCR is None:
                        dBCR = 0.0
                        dBCR_Table = "---"
                    else:
                        dBCR_Table = dBCR


                else:
                    dIRR = 0.0
                    dIRR_Table = "---"
                    dPayBack = 0.0
                    dPayBack_Table = "---"
                    dBCR = 0.0
                    dBCR_Table = "---"
                        
                IRR.append(dIRR)
                IRR_Table.append(dIRR_Table)

                PayBack.append(dPayBack)
                PayBack_Table.append(dPayBack_Table)

                BCR.append(dBCR)
                BCR_Table.append(dBCR_Table)

                tableEntry = noneFilter([unicode(salternatives[i].ShortName,"utf-8"), \
                                         dIRR_Table,dPayBack_Table,dBCR_Table])

                plotEntry = noneFilter([unicode(salternatives[i].ShortName,"utf-8"), \
                                        dIRR])
               
                CS7Table.append(tableEntry)
                CS7Plot.append(plotEntry)
#..............................................................................
# then send everything to the GUI

            data1 = array(CS7Table)
                              
            Status.int.setGraphicsData("CS7_Table", data1)

            data2 = array(CS7Plot)

            Status.int.setGraphicsData("CS7_Plot", data2)

            CS7Report = copy.deepcopy(CS7Table)
            for i in range(len(CS7Table),10):
                CS7Report.append([" "," "," "," "])
            dataReport7 = array(CS7Report)                  
            Status.int.setGraphicsData("CS7_REPORT", dataReport7)

#------------------------------------------------------------------------------
# Summary for report
        elif self.keys[0] == "Summary":
            qq = Status.DB.sproject.ProjectID[Status.PId]
            if len(qq) > 0:
                summary = qq[0].Summary
            else:
                summary = _(" ")

            Status.int.setGraphicsData("SUMMARY",array([[summary]]))

# build summary table

            if Status.FinalAlternative is not None:
                ANoList = [0,int(Status.FinalAlternative),None]
            else:
                ANoList = [0,-1,None]
            for ANo in range(1,len(generalData)-1):
                if ANo <> Status.FinalAlternative:
                    ANoList.append(ANo)
            
            summaryTable = []
                             
            for ANo in ANoList:

                if ANo is None:
                    row = [_("Other possible alternatives studied:"),
                           " "," "," "]
                elif ANo == -1:
                    row = [_("No alternative selected"),
                           " "," "," "]
                else:
                    row = []
                    i = ANo + 1

                    if salternatives[i].ShortName is None:
                        row.append('---')
                    else:
                        row.append(salternatives[i].ShortName)

                    if generalData[i].TotalInvCost is None: #protection against None
                        row.append('---')
                    else:
                        row.append(generalData[i].TotalInvCost)

                    if generalData[i].EnergyCost is None: #protection against None
                        row.append('---')
                    else:
                        row.append(generalData[i].EnergyCost)
            
                    if generalData[i].PEC is None: #protection against None
                        row.append('---')
                    else:
                        row.append(generalData[i].PEC/1000.0)

                summaryTable.append(row)

            Status.int.setGraphicsData("SUMMARY_TABLE", array(summaryTable))
    def storeHXData(self, HXPinchConnection, QHX_t, UA, Tloghx, \
                    HXTSinkInlet, HXTSinkOutlet, HXTSourceInlet, HXTSourceOutlet,\
                    inletTSink, outletTSink, HeatFlowPercentSink, inletTSource, outletTSource, \
                    HeatFlowPercentSource, StorageSize):
        
        print inletTSink
        print outletTSink
        print HeatFlowPercentSink
        print inletTSource
        print outletTSource
        print HeatFlowPercentSource
        
        
        HXID = HXPinchConnection.HXID
        HXPinchConnection.StorageSize = StorageSize
        HXPinchConnection.QdotHX = max(QHX_t)
        combinedSink = HXPinchConnection.combinedSink
        combinedSource = HXPinchConnection.combinedSource
        try:      
            sqlQuery = "ProjectID = '%s' AND AlternativeProposalNo = '%s' AND QHeatExchanger_ID = '%s'"%(self.pid,self.ano, HXID)
            self.hexers = [Status.DB.qheatexchanger.sql_select(sqlQuery)]
            
            streamQuery = "qheatexchanger_QHeatExchanger_Id = '%s'"%(HXID)
            hxconn = Status.DB.heatexchanger_pinchstream.sql_select(streamQuery)
        except:
            return
        
        self.sinkName.append(self.getCombinedStreamName(HXPinchConnection.sinkstreams))
        self.sourceName.append(self.getCombinedStreamName(HXPinchConnection.sourcestreams))
#        self.hexers[-1][0]['ColdMedium'] = self.getCombinedStreamName(HXPinchConnection.sinkstreams)
#        self.hexers[-1][0]['HotMedium'] = self.getCombinedStreamName(HXPinchConnection.sourcestreams)
        
        
        hx = self.hexers[-1]
        QHX = sum(QHX_t)
        for i in xrange(len(Status.int.HXPinchConnection)):
            if Status.int.HXPinchConnection[i].HXID == HXID:
                Status.int.HXPinchConnection[i].QHX = QHX
                activeHX = Status.int.HXPinchConnection[i]
                
        SourceName = ""
        for stream in activeHX.sourcestreams:
            SourceName += stream.stream.name    
        SourceName = SourceName[0:300]
        
        SinkName = ""
        for stream in activeHX.sinkstreams:
            SinkName += stream.stream.name
        SinkName = SinkName[0:300]
        
        print "HXNo: ", str(hx.HXNo)
        

        
        tmphx = {"ProjectID":self.pid,
               "AlternativeProposalNo":check(self.ano),
               "HXNo":check(hx[0].HXNo),
               "HXName":check(str(hx[0].HXName)),# + str("_new")
               "HXType":check(hx[0].HXType),
               "QdotHX":check(max(QHX_t)),
               "HXLMTD":check(Tloghx),
               "Area":check(None),
               "QHX":check(QHX),
               "HXSource":check(SourceName),
               "FluidIDSource":check(None),
               "HXTSourceInlet":check(HXTSourceInlet),
               "HXhSourceInlet":check(None),
               "HXTSourceOutlet":check(HXTSourceOutlet),
               "HXhSourceOutlet":check(None),
               "HXSink":check(SinkName),
               "FluidIDSink":check(None),
               "HXTSinkInlet":check(HXTSinkInlet),
               "HXTSinkOutlet":check(HXTSinkOutlet),
               "TurnKeyPrice":check(None),
               "OMFix":check(None),
               "OMVar":check(None),
               "StorageSize":check(StorageSize),
               "StreamStatusSource":check(None),
               "StreamStatusSink":check(None),
               "StreamTypeSink":check(None),
               "StreamTypeSource":check(None),
               "UA":check(UA)}
        
        qhxTable = Status.DB.qheatexchanger
        newHXID = qhxTable.insert(tmphx)
        print newHXID
        
        j=k=0
        for i in xrange(len(hxconn)):
            
            streamQuery = "id = '%s'"%(hxconn[i].pinchstream_id)
            pinchstreams = Status.DB.pinchstream.sql_select(streamQuery)
            HotColdType = pinchstreams[0].Hot_Cold
            
            if HotColdType == "Sink" or HotColdType == "Cold":
                inletTemp = inletTSink[0]
                print "OutletTSink:", str(outletTSink)
                outletTemp = outletTSink[0]
                HeatFlowPercent = HeatFlowPercentSink[0]
                del inletTSink[0]
                del outletTSink[0]
                del HeatFlowPercentSink[0]
            else:
                inletTemp = inletTSource[0]
                print "OutletTSource:", str(outletTSource)
                outletTemp = outletTSource[0]
                HeatFlowPercent = HeatFlowPercentSource[0]
                del inletTSource[0]
                del outletTSource[0]
                del HeatFlowPercentSource[0]
                
            
            tmpconn = {"qheatexchanger_QHeatExchanger_Id":check(newHXID),
                       "pinchstream_id":check(hxconn[i].pinchstream_id),
                       "inletTemp":check(inletTemp),
                       "outletTemp":check(outletTemp),
                       "outletOfHX_id":check(hxconn[i].outletOfHX_id),
                       "inletOfHX_id":check(hxconn[i].inletOfHX_id),
                       "HeatFlowPercent":check(HeatFlowPercent)
                       }
            connTable = Status.DB.heatexchanger_pinchstream
            connTable.insert(tmpconn)
        
        # Update HXIDs from new HX
        for i in xrange(len(Status.int.HXPinchConnection)):
            if Status.int.HXPinchConnection[i].HXID == HXID:
                Status.int.HXPinchConnection[i].HXID = newHXID
        
#        # Delete old HXs from DB
        delquery = "DELETE FROM qheatexchanger  WHERE ProjectID=%s AND AlternativeProposalNo=%s AND QHeatExchanger_ID = '%s'" % (self.pid,self.ano, HXID)
        Status.DB.sql_query(delquery)
    def __storeNewHX(self,listofhexdata):   
    #stores HEXers found in XML document
    #deletes old HEX             
#        try:
        delquery = "DELETE FROM qheatexchanger  WHERE ProjectID=%s AND AlternativeProposalNo=%s" % (self.pid,self.ano)
        Status.DB.sql_query(delquery)

        qhxTable = Status.DB.qheatexchanger
        for hx in listofhexdata:                
#                query = hx.getInsertSQL(self.pid,self.ano)
#                Status.DB.sql_query(query)

            tmp = {"ProjectID":self.pid,
                   "AlternativeProposalNo":self.ano,
                   "HXNo":check(hx.getValue("HXNo")),
                   "HXName":check(hx.getValue("HxName")),
                   "HXType":check(hx.getValue("HXType")),
                   "QdotHX":check(hx.getValue("QdotHX")),
                   "HXLMTD":check(hx.getValue("HXLMTD")),
                   "Area":check(hx.getValue("HEX_area")),
                   "QHX":check(hx.getValue("QHX")),
                   "HXSource":check(hx.getValue("HXSource")),
                   "FluidIDSource":check(hx.getValue("HXSource_FluidID")),
                   "HXTSourceInlet":check(hx.getValue("HXTSourceInlet")),
                   "HXhSourceInlet":check(hx.getValue("HXhSourceInlet")),
                   "HXTSourceOutlet":check(hx.getValue("HXTSourceOutlet")),
                   "HXhSourceOutlet":check(hx.getValue("HXhSourceOutlet")),
                   "HXSink":check(hx.getValue("HXSink")),
                   "FluidIDSink":check(hx.getValue("HXSink_FluidID")),
                   "HXTSinkInlet":check(hx.getValue("HXTSinkInlet")),
                   "HXTSinkOutlet":check(hx.getValue("HXTSinkOutlet")),
                   "TurnKeyPrice":check(hx.getValue("HEX_turnkeyprice")),
                   "OMFix":check(hx.getValue("HX_OandMfix")),
                   "OMVar":check(hx.getValue("HX_OandMvar")),
                   "StorageSize":check(hx.getValue("storage_size")),
                   "StreamStatusSource":check(hx.getValue("StreamStatusSource")),
                   "StreamStatusSink":check(hx.getValue("StreamStatusSink")),
                   "StreamTypeSink":check(hx.getValue("StreamTypeSink")),
                   "StreamTypeSource":check(hx.getValue("StreamTypeSource"))}

            try:
                qhxTable.insert(tmp)
            except:            
                logError(_("Error writing new HX into database.")+" [%s]"%tmp[HXName]) 
Exemple #11
0
    def __init__(self,mode="ignore",infile=None):

        if infile is None:
            infile = openfilecreate('Choose a project file for importing','XML files (*.xml)|*.xml',
                           style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)
            if infile is None:
                return None

        (conn, cursor) = openconnection()
        #
        # get the highest project number so far in the database, add 1, and assign to the
        # imported project

#......................................................................
# ask for confirmation before causing a major desaster

        dialog =  DialogImport(None,_U("import data"),\
                               _U("This will modify your databases\nIf You are sure, specify what to do with duplicate data")+\
                               _U("\nElse press CANCEL"))
        ret = dialog.ShowModal()
        if ret == wx.ID_OK:
            mode = "overwrite"
        elif ret == wx.ID_IGNORE:
            mode = "ignore"
        else:
            return

        logTrack("ImportDB in mode %s"%mode)

        # create a dom and import in it the xml project file
        self.document = xml.dom.minidom.parse(infile)
        # get the elements from the DOM
        dbs = self.document.getElementsByTagName('EinsteinDataBase')
        for db in dbs:
            tables = db.getElementsByTagName("table")
            tabledict = {}
            for table in tables:
                tablename =  str(table.getAttribute('name'))
                tablelist = []
                rows = table.getElementsByTagName("row")
                for row in rows:
                    sqlist = []
                    sqldict = {}
                    newdict = {}
                    nrow =  row.getAttribute('n')
                    elements = row.getElementsByTagName("element")

                    rowName = None #characteristic name of the row
                    rowPar1 = None
                    rowPar2 = None
                    
                    for element in elements:
                        fieldname = element.getAttribute('name').lower()
                        fieldnameCAPS = str(element.getAttribute('name'))
                        fieldnameCapitalLetters = element.getAttribute('name')
                        eltype = element.getAttribute('type')
                        elauto = element.getAttribute('auto')
                        elvalue = element.getAttribute('value')

                        if tablename == "dbfluid" and fieldname == "fluidname":
                            rowName = elvalue
                        elif tablename == "dbfuel" and fieldname == "fuelname":
                            rowName = elvalue
                        elif tablename == "auditor" and fieldname == "name":
                            rowName = elvalue
                        elif tablename == "dbelectricitymix":
                            if fieldname == "country":
                                rowName = elvalue
                            elif fieldname == "year":
                                rowPar1 = elvalue
                        elif tablename == "dbboiler":
                            if fieldname == "boilermanufacturer":
                                rowName = elvalue
                            elif fieldname == "boilermodel":
                                rowPar1 = elvalue
                        elif tablename == "dbchp":
                            if fieldname == "chpequip":
                                rowName = elvalue
                        elif tablename == "dbheatpump":
                            if fieldname == "hpmanufacturer":
                                rowName = elvalue
                            elif fieldname == "hpmodel":
                                rowPar1 = elvalue
                        elif tablename == "dbsolarthermal":
                            if fieldname == "stmanufacturer":
                                rowName = elvalue
                            elif fieldname == "stmodel":
                                rowPar1 = elvalue

                        if elauto != 'auto_increment':
                            newdict.update({fieldnameCapitalLetters:elvalue})

                        # substitute invalid chars in char fields and enclose in ''
                        if eltype.startswith('char') or \
                           eltype.startswith('varchar') or \
                           eltype.startswith('text'):
                            elvalue = elvalue.encode("utf-8")

                        if eltype.startswith('date'):
                            elvalue = "'" + self.subsIllegal(elvalue) + "'"
                        # substitute auto-increment value with NULL
                        if elauto == 'auto_increment':
                            # main key field
                            oldKey = int(elvalue)
                            elvalue = 'NULL'

#                        sqlist.append("%s=%s" % (fieldname,elvalue))
                        sqldict.update({fieldnameCAPS:elvalue})

#......................................................................
# before inserting new entry, check if entry with the same name exists
# (only for questionnaire, dbfluid, dbfuel

                    ignoreRow = False
                    existingRows = []
                    if tablename == "dbfluid":
                        existingRows = Status.DB.dbfluid.FluidName[check(rowName)]

                    elif tablename == "dbfuel":
                        existingRows = Status.DB.dbfuel.FuelName[check(rowName)]

                    elif tablename == "auditor":
                        existingRows = Status.DB.auditor.Name[check(rowName)]

                    elif tablename == "dbelectricitymix":
                        if rowPar1 is None:
                            existingRows = Status.DB.dbelectricitymix.Country[check(rowName)]
                        else:
                            existingRows = Status.DB.dbelectricitymix.Country[check(rowName)].Year[rowPar1]
                            
                    elif tablename == "dbboiler":
                        if rowPar1 is None:
                            existingRows = Status.DB.dbboiler.BoilerManufacturer[check(rowName)]
                        else:
                            existingRows = Status.DB.dbboiler.BoilerManufacturer[check(rowName)].BoilerModel[check(rowPar1)]
                            
                    elif tablename == "dbchp":
                        existingRows = Status.DB.dbchp.CHPequip[check(rowName)]
                            

                    elif tablename == "dbheatpump":
                        if rowPar1 is None:
                            existingRows = Status.DB.dbheatpump.HPManufacturer[check(rowName)]
                        else:
                            existingRows = Status.DB.dbheatpump.HPManufacturer[check(rowName)].HPModel[check(rowPar1)]
                            
                    elif tablename == "dbsolarthermal":
                        if rowPar1 is None:
                            existingRows = Status.DB.dbsolarthermal.STManufacturer[check(rowName)]
                        else:
                            existingRows = Status.DB.dbsolarthermal.STManufacturer[check(rowName)].STModel[check(rowPar1)]
                            
   
                    else:
                        existingRows = []

                    if len(existingRows) > 0:
                        if rowPar2 is None:
                            par2 = ""
                        else:
                            par2 = " " + str(rowPar2)

                        if rowPar1 is None:
                            par1 = ""
                        else:
                            par1 = " "+str(rowPar1)

                        if mode == "overwrite":
                            existingRows[0].update(newdict)
                            logWarning("%s: %s%s%s"%(tablename,check(rowName),par1,par2)+\
                                       _U(" already in database. Data from imported file will be updated"))
                        else:
                            logWarning("%s: %s%s%s"%(tablename,check(rowName),par1,par2)+\
                                       _U(" already in database. Data from imported file will be ignored"))
                            
                                             
                    else:
                        # create sql sentence and update database
#                        sql = 'INSERT INTO %s SET ' % (tablename,) + ', '.join(sqlist)
#                        cursor.execute(sql)

                        table = Table(Status.DB,tablename)
                        table.insert(sqldict)

                        # get last inserted
                        cursor.execute('SELECT LAST_INSERT_ID() AS last')
                        field = cursor.fetchone()
                        
                                                
        conn.close()
Exemple #12
0
    def __init__(self,infile=None):
        self.pid = None
        self.newpid = None

        if infile is None:
            infile = openfilecreate('Choose a project file for importing','XML files (*.xml)|*.xml',
                           style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)
            if infile is None:
                return None

        (conn, cursor) = openconnection()
        #
        # get the highest project number so far in the database, add 1, and assign to the
        # imported project

#NOTE: a dummy row is added and later on deleted in order to obtain the auto-increment
# status of the table. there should be a more elegant way to to this ...
# => to be changed in the future ...

        dummyID = Status.DB.questionnaire.insert({"Name":"dummy"})
        Status.SQL.commit()
        cursor.execute('SELECT MAX(Questionnaire_id) AS n FROM questionnaire')

        nrows = cursor.rowcount
        if nrows <= 0:
            self.newpid = 1
        else:
            field = cursor.fetchone()
            # new pid for this project
            self.newpid = int(field['n']) + 1
        logDebug("ExportData (importProject): dummyID = %s newpid = %s"%(dummyID,self.newpid))

        dummyRows = Status.DB.questionnaire.Questionnaire_ID[dummyID]
        if len(dummyRows) > 0:
            dummyRows[0].delete()

        # create a dom and import in it the xml project file
        self.document = xml.dom.minidom.parse(infile)
        # get the elements from the DOM
        self.projectdict = {}
        projects = self.document.getElementsByTagName('EinsteinProject')
        for project in projects:
            self.pid = project.getAttribute('pid')
            tables = project.getElementsByTagName("table")
            tabledict = {}
            for table in tables:
                tablename =  str(table.getAttribute('name'))
                tablelist = []
                rows = table.getElementsByTagName("row")
                for row in rows:
                    sqlist = []
                    sqldict = {}
                    
                    nrow =  row.getAttribute('n')
                    elements = row.getElementsByTagName("element")

                    rowName = None #characteristic name of the row
                    
                    for element in elements:
                        fieldname = element.getAttribute('name').lower()
                        fieldnameCAPS = str(element.getAttribute('name'))
                        eltype = element.getAttribute('type')
                        elauto = element.getAttribute('auto')
                        elvalue = element.getAttribute('value')

                        if tablename == "questionnaire" and fieldname == "name":
                            rowName = elvalue
                            existingRows = Status.DB.questionnaire.Name[check(rowName)]
                            if len(existingRows) > 0:
                                showWarning(_U("Project with name %s already exists in database\nProject renamed to: IMPORTED PROJECT")%rowName)
                                elvalue = 'IMPORTED PROJECT'
                        elif tablename == "dbfluid" and fieldname == "fluidname":
                            rowName = elvalue
                        elif tablename == "dbfuel" and fieldname == "fuelname":
                            rowName = elvalue
                        elif tablename == "auditor" and fieldname == "name":
                            rowName = elvalue

                        # substitute new pid in id field
                        if fieldname == 'projectid' or \
                             fieldname == 'questionnaire_id':
                            elvalue = self.newpid
                        # substitute invalid chars in char fields and enclose in ''
                        if eltype.startswith('char') or \
                           eltype.startswith('varchar') or \
                           eltype.startswith('text'):

                            elvalue = elvalue.encode("utf-8")

                        if eltype.startswith('date'):
#                            elvalue = "'" + self.subsIllegal(elvalue) + "'"
                            elvalue = self.subsIllegal(elvalue)
                          
                        # substitute auto-increment value with NULL
                        if elauto == 'auto_increment':
                            # main key field
                            oldKey = int(str(elvalue))
                            elvalue = 'NULL'

#                        sqlist.append("%s=%s" % (fieldname,elvalue))
                        sqldict.update({fieldnameCAPS:elvalue})

#......................................................................
# before inserting new entry, check if entry with the same name exists
# (only for questionnaire, dbfluid, dbfuel

                    ignoreRow = False
                    if tablename == "dbfluid":
                        existingRows = Status.DB.dbfluid.FluidName[check(rowName)]
                        if len(existingRows) > 0:
                            showWarning(_U("Fluid %s already in database. Data from imported file will be ignored")%rowName)
                            ignoreRow = True
                            newID = existingRows[0].DBFluid_ID

                    elif tablename == "dbfuel":
                        existingRows = Status.DB.dbfuel.FuelName[check(rowName)]
                        if len(existingRows) > 0:
                            showWarning(_U("Fuel %s already in database. Data from imported file will be ignored")%rowName)
                            ignoreRow = True
                            newID = existingRows[0].DBFuel_ID
                    elif tablename == "auditor":
                        existingRows = Status.DB.auditor.Name[check(rowName)]
                        if len(existingRows) > 0:
                            showWarning(_U("Auditor %s already in database. Data from imported file will be ignored")%rowName)
                            ignoreRow = True
                            newID = existingRows[0].Auditor_ID
                    else:
                        existingRows = []
                                             
                    if ignoreRow == False:
                        # create sql sentence and update database
#substituted the following block by
#                        sql = 'INSERT INTO %s SET ' % (tablename,) + ', '.join(sqlist)
#                        print sql
#                        cursor.execute(sql)
                        table = Table(Status.DB,tablename)
                        newKey = table.insert(sqldict)
                                       
                        # get last inserted
                        cursor.execute('SELECT LAST_INSERT_ID() AS last')
                        field = cursor.fetchone()
# 2009-04-06: line eliminated: gave 0 as result !!! substituted by direct assignment
# of newKey (see above)
#                        newKey = int(field['last'])
                    else:
                        newKey = newID
                    tablelist.append((oldKey,newKey))
                tabledict[tablename] = tablelist
            self.projectdict[self.pid] = tabledict
        conn.close()

#####HS2008-07-14: here restoring links added

        for PId in self.projectdict.keys():
            Status.prj.restoreLinks(self.newpid,self.projectdict[PId])
 def saveToDB(self, processId, ANo=None):
     if ANo is None:
         ANo = Status.ANo
     dbFluidId = findKey(Status.prj.getFluidDict(), self.Medium)
     if self.HeatRecExist is None:
         dbHeatRecExist = None
     else:
         dbHeatRecExist = self.HeatRecExist and 1 or 0
     if self.HeatRecOK is None:
         dbHeatRecOk = None
     else:
         dbHeatRecOk = self.HeatRecOK and 1 or 0
     dbStream  = {'Name'                 : check(self.Name),
                  'dbfluid_id'           : check(dbFluidId),
                  'PTOutFlow'            : check(self.PTOutFlow), 
                  'PTOutFlowRec'         : check(self.PTOutFlowRec), 
                  'PTFinal'              : check(self.PTFinal), 
                  'VOutFlowCycle'        : check(self.VOutFlowCycle),
                  'mOutFlowNom'          : check(self.mOutFlowNom),
                  'HeatRecExist'         : check(dbHeatRecExist), 
                  'HeatRecOk'            : check(dbHeatRecOk), 
                  'HOutFlow'             : check(self.HOutFlow),
                  'XOutFlow'             : check(self.XOutFlow), 
                  'UPHw'                 : check(self.UPHw), 
                  'QdotProc_w'           : check(self.QdotProc_w),
                  'ProjectID'            : Status.PId,
                  'AlternativeProposalNo': ANo} 
     
     try:
         streamsIds = Status.DB.process_streams_out.qprocessdata_QProcessData_Id[processId].streams_out_id.column()
         streamRow  = Status.DB.streams_out.sql_select('id IN (%s) AND Name = "%s"' % (', '.join(str(id) for id in streamsIds), self.Name))[0]
     except ProgrammingError:
         raise InconsistentDataBaseError
     except (LookupError, IndexError): # no input stream with our name found for given processId
         newStreamsOutId = Status.DB.streams_out.insert(dbStream)
         Status.DB.process_streams_out.insert({'qprocessdata_QProcessData_Id' : processId,
                                              'streams_out_id'                : newStreamsOutId,
                                              'ProjectID'                     : Status.PId,
                                              'AlternativeProposalNo'         : Status.ANo})
     else: # found stream with our name for given processId
         streamRow.update(dbStream)