Example #1
0
def main(subArea, runName, chartTitlePre):
    outDir = "C:\\Users\\olsenk\\Dropbox\\FPF\\Envision Runs\\keith_production\\"
    varList = [' Stand Replacing FirePMG1',' Stand Replacing FirePMG2',' Stand Replacing FirePMG3',' Stand Replacing FirePMG4',' Stand Replacing FirePMG5']
    chartTitle = chartTitlePre
    PMG345Ha = reporterFunc.getPMG345Ha(subArea)
    forestedHa = reporterFunc.getPMG12345Ha(subArea)

    # list of ownerships to graphs
    reporterName = r'FireOccurance_by_OWNER_DETL_pivot.csv'
    ownerLabelField = ' OWNER_DETL_label'

    pdfFile = PdfPages(outDir + 'report5bw_HS_Fire_byOwner.pdf')

#    for plotPage in [1,2,3,4,5,6,7,8]:
    # setup plot for all scenarios
    fig = pl.figure(1, figsize=(6.5,6.5))

    for splot in [1,2,3,4]:
        ax = fig.add_subplot(2,2,splot)
        inDir = outDir + runName + "_CurrentPolicy\\"

#        if plotPage % 2 == 1:
        if splot == 1:
            ownersToGraph = ['USFS','State','Corporate Forest']
            ownerLabel = ['USFS','State','Corporate']
        elif splot == 2:
            ownersToGraph = ['Chemult Ranger District (Fremont-Winema NF)','Chiloquin Ranger District (Fremont-Winema NF)','Klamath Ranger District (Fremont-Winema NF)']
            ownerLabel = ['Chemult RD','Chiloquin RD','Klamath RD']
#        else:
        elif splot == 3:
            ownersToGraph = ['ODF Sun Pass','ODF Gilchrist']
            ownerLabel = ownersToGraph
        elif splot == 4:
            ownersToGraph = ['JWTR Timber Holdings','Cascade Timberlands (Mazama Forest)','Jeld-Wen Inc','J-Spear Ranch']
            ownerLabel = ['PC1','PC2','PC3','PC4']

        if os.path.isdir(inDir):
            yearList = list(set(pd.io.parsers.read_csv(inDir + reporterName)[' Year']))
            repList = list(set(pd.io.parsers.read_csv(inDir + reporterName)[' Run']))
            totalArea = pd.io.parsers.read_csv(inDir + reporterName)

            # sum output over selected ownerships
            valueSet = []
            maxValueSet = []
            for ownership in ownersToGraph:
                print ownership

                # get stats from multiple reps
                dataList = []
                for year in range(1,max(yearList) + 1):
                    yearArea = totalArea[totalArea[' Year'] == year]

                    for rep in repList:
                        repArea = yearArea[yearArea[' Run'] == rep]

                        if ownership == 'USFS':
                            ownerArea = pd.DataFrame(repArea[repArea[ownerLabelField] == 'Chemult Ranger District (Fremont-Winema NF)'])
                            fireProneArea345 = PMG345Ha['Chemult Ranger District (Fremont-Winema NF)']
                            fireProneArea = forestedHa['Chemult Ranger District (Fremont-Winema NF)']

                            for subOwner in ['Chiloquin Ranger District (Fremont-Winema NF)','Klamath Ranger District (Fremont-Winema NF)']:
                                tempArea = repArea[repArea[ownerLabelField] == subOwner]
                                fireProneArea345 += PMG345Ha[subOwner]
                                fireProneArea += forestedHa[subOwner]
                                for varName in varList:
                                    ownerArea[varName].iloc[0] += tempArea[varName].iloc[0]

                        elif ownership == 'State':
                            ownerArea = pd.DataFrame(repArea[repArea[ownerLabelField] == 'ODF Sun Pass'])
                            fireProneArea345 = PMG345Ha['ODF Sun Pass']
                            fireProneArea = forestedHa['ODF Sun Pass']

                            for subOwner in ['ODF Gilchrist','ODF Gilchrist (The Conservation Fund)']:
                                tempArea = repArea[repArea[ownerLabelField] == subOwner]
                                fireProneArea345 += PMG345Ha[subOwner]
                                fireProneArea += forestedHa[subOwner]
                                for varName in varList:
                                    ownerArea[varName].iloc[0] += tempArea[varName].iloc[0]

                        elif ownership == 'ODF Gilchrist':
                            ownerArea = pd.DataFrame(repArea[repArea[ownerLabelField] == 'ODF Gilchrist'])
                            fireProneArea = forestedHa['ODF Gilchrist']

                            for subOwner in ['ODF Gilchrist (The Conservation Fund)']:
                                tempArea = repArea[repArea[ownerLabelField] == subOwner]
                                fireProneArea += forestedHa[subOwner]
                                for varName in varList:
                                    ownerArea[varName].iloc[0] += tempArea[varName].iloc[0]

                        elif ownership == 'Corporate Forest':
                            ownerArea = pd.DataFrame(repArea[repArea[ownerLabelField] == 'JWTR Timber Holdings'])
                            fireProneArea345 = PMG345Ha['JWTR Timber Holdings']
                            fireProneArea = forestedHa['JWTR Timber Holdings']

                            for subOwner in ['Cascade Timberlands (Mazama Forest)','Jeld-Wen Inc','J-Spear Ranch']:
                                tempArea = repArea[repArea[ownerLabelField] == subOwner]
                                fireProneArea345 += PMG345Ha[subOwner]
                                fireProneArea += forestedHa[subOwner]
                                for varName in varList:
                                    ownerArea[varName].iloc[0] += tempArea[varName].iloc[0]

                        else:
                            ownerArea = pd.DataFrame(repArea[repArea[ownerLabelField] == ownership])
                            fireProneArea345 = PMG345Ha[ownership]
                            fireProneArea = forestedHa[ownership]

##                        if plotPage in [1,2,5,6]:
##                            if fireProneArea345 > 0:
##                                dataList.append((ownerArea[' Stand Replacing FirePMG3'].iloc[0] + ownerArea[' Stand Replacing FirePMG4'].iloc[0] + ownerArea[' Stand Replacing FirePMG5'].iloc[0]) / fireProneArea345 * 100)
##                            else:
##                                dataList.append(0.0)
##                        else:
                        if fireProneArea > 0:
                            dataList.append((ownerArea[' Stand Replacing FirePMG1'].iloc[0] + ownerArea[' Stand Replacing FirePMG2'].iloc[0] + ownerArea[' Stand Replacing FirePMG3'].iloc[0] + ownerArea[' Stand Replacing FirePMG4'].iloc[0] + ownerArea[' Stand Replacing FirePMG5'].iloc[0]) / fireProneArea * 100)
                        else:
                            dataList.append(0.0)

##                    if plotPage < 5:
##                        topPercent = 1.0
##                    else:
                topPercent = 0.1

                dataList.sort(reverse=True)
                subDataList = []
                for i in range(int(round(len(dataList) * topPercent))):
                    subDataList.append(dataList[i])

                valueSet.append(subDataList)
                maxValueSet.append(max(subDataList))

            if splot == 1:
                labelXaxis = True
                figText = 'a'
            elif splot == 2:
                labelXaxis = True
                figText = 'b'
            elif splot == 3:
                labelXaxis = True
                figText = 'c'
            elif splot == 4:
                labelXaxis = True
                figText = 'd'

##                if plotPage in [1,2]:
##                    yLabelText = 'Fire frequent area (%)'
##                elif plotPage in [3,4]:
##                    yLabelText = 'Forested area (%)'
##                elif plotPage in [5,6]:
##                    yLabelText = 'Top 10% Fire frequent area (%)'
##                elif plotPage in [7,8]:
##                    yLabelText = 'Top 10% Forested area (%)'

            #reporterFunc.plotReporter5bw(fig, ax, '', pdfFile, valueSet, ownersToGraph, subArea, chartTitle, yLabelText, maxValueSet)

            yLabelText = ''
            reporterFunc.plotReporter5bw(fig, ax, '', pdfFile, valueSet, ownerLabel, subArea, chartTitle, yLabelText, maxValueSet, labelXaxis, figText)


    yLabelText = 'Forested area burned (%)'
    reporterFunc.plotFigureText(fig, '', yLabelText)

    pl.savefig(outDir + 'report5bw_HS_Fire_byOwner.png', bbox_inches='tight', dpi=300)
    pdfFile.savefig()
    pl.close()
    pdfFile.close()
    print "Done."
def main(outDir, subArea, runList, chartTitle, ownership):
    varList = [
        ' Prescribed Fire (ha)', ' Mowing and Grinding (ha)', ' Thinning (ha)',
        ' Partial Harvest (ha)'
    ]
    ##    forestedHa = reporterFunc.getOwnerForestedHa(subArea)
    ##    ownerAllHa = reporterFunc.getOwnerHa(subArea)
    figTextList = ['Federal', 'Tribal', 'Corporate Forest', 'Family Forest']

    # list of ownerships to graphs
    #    ownersToGraph = ['Federal','Tribal','Private Industrial','Private Non-Industrial']
    ownersToGraph = ['Federal']

    if ownership == 'SYU':
        pdfFile = PdfPages(outDir + chartTitle +
                           '_syu_Management_area_2x2.pdf')
        varList = [
            ' Prescribed Fire (ha) SYU', ' Mowing and Grinding (ha) SYU',
            ' Thinning (ha) SYU', ' Partial Harvest (ha) SYU'
        ]
    else:
        pdfFile = PdfPages(outDir + chartTitle + '_Management_area_2x2.pdf')

    fig = pl.figure(1, figsize=(11, 8.5))
    for varStruct in varList:
        for owner in ownersToGraph:
            # setup plot for all scenarios
            ax = fig.add_subplot(2, 2, varList.index(varStruct) + 1)
            yLabelText = 'Area of' + varStruct[:-3] + "1000 ha)"

            for scenario in runList:
                inDir = outDir + scenario + "\\"

                if os.path.isdir(inDir):
                    # load area stats by owner
                    areaStats = pd.io.parsers.read_csv(
                        inDir + "AreaStats_by_OWNER_pivot.csv")
                    areaStats = areaStats[areaStats[' Year'] == 1]

                    totalArea = pd.io.parsers.read_csv(
                        inDir + r'ManagementDisturb_by_OWNER_pivot.csv')
                    yearList = list(set(totalArea[' Year']))
                    repList = list(set(totalArea[' Run']))

                    # get stats from multiple reps
                    statsList = []
                    for year in range(1, max(yearList) + 1):
                        yearArea = totalArea[totalArea[' Year'] == year]

                        dataList = []
                        for rep in repList:
                            repArea = yearArea[yearArea[' Run'] == rep]

                            ownerArea = pd.DataFrame(
                                repArea[repArea[' OWNER_label'] == owner])
                            dataList.append(ownerArea[varStruct].iloc[0])

                        # convert to numpy array
                        numpyList = np.array(dataList)
                        lower95th = np.mean(numpyList, axis=0) - (
                            (1.96 * np.std(numpyList, axis=0)) /
                            np.sqrt(len(repList)))
                        upper95th = np.mean(numpyList, axis=0) + (
                            (1.96 * np.std(numpyList, axis=0)) /
                            np.sqrt(len(repList)))

                        if lower95th < 0:
                            lower95th = 0.0

                        # add year data to dictionary
                        dataDict = {
                            'timeStep': year,
                            'mean': np.mean(numpyList, axis=0),
                            'std': np.std(numpyList, axis=0),
                            'lower': lower95th,
                            'upper': upper95th
                        }

                        # convert to list for DataFrame
                        statsList.append(dataDict)

                    # convert to DataFrame
                    dataTable = pd.DataFrame(statsList)

                    if (varList.index(varStruct)) < (len(varList) / 2):
                        labelXtick = False
                    else:
                        labelXtick = True

                    labelYtick = True
                    plotLegend = (0.99, 0.99)
                    xLabelText = ''
                    dataTable['mean'] = dataTable['mean'] / 1000
                    dataTable['lower'] = dataTable['lower'] / 1000
                    dataTable['upper'] = dataTable['upper'] / 1000

                    if owner == 'Tribal':
                        plotLegend = (0.84, 0.33)

                    mnAxis, mxAxis = reporterFunc.plotReporter4(
                        fig, ax, '', pdfFile, dataTable,
                        ['mean', 'lower', 'upper'], xLabelText, yLabelText,
                        scenario, labelXtick, labelYtick, plotLegend,
                        figTextList[ownersToGraph.index(owner)])

            if mxAxis > 7:
                mxAxis += 1
                ax.set_ylim(mnAxis, mxAxis)

    reporterFunc.plotFigureText(fig, 'Simulation Year', '')
    pdfFile.savefig()
    pl.close()

    ## pl.savefig(outDir + 'report4_Vol_Owners.png', bbox_inches='tight', dpi=300)
    pdfFile.close()
    print "Done with Management area."
Example #3
0
def main(subArea, runName, chartTitlePre, ownership):
    outDir = "C:\\Users\\olsenk\\Dropbox\\FPF\\Envision Runs\\keith_production\\"
    varList = [
        ' High Suitability', ' American Marten Good (ha)',
        ' Black-backed Woodpecker Good (ha)',
        ' White-headed Woodpecker Good (ha)', ' Northern Goshawk Good (ha)',
        ' Western Bluebird Good (ha)', ' Pileated Woodpecker Good (ha)',
        'MD High Suitability', ' DownyBrome0.66-1 (ha)'
    ]
    figTextList = [
        'Northern Spotted Owl\n(nest)', 'Pacific Marten', 'Black-backed WP',
        'White-headed WP', 'Northern Goshawk\n(nest)', 'Western Bluebird',
        'Pileated WP', 'Mule Deer', 'Cheatgrass'
    ]
    yLabelText = 'Area (%)'
    chartTitle = chartTitlePre
    forestedHa = reporterFunc.getOwnerForestedHa(subArea)
    ownerAllHa = reporterFunc.getOwnerHa(subArea)

    # list of ownerships to graphs
    if ownership == 'All':
        ownersToGraph = [
            'Federal', 'State', 'Private Non-Industrial', 'Private Industrial',
            'Tribal', 'Homeowner'
        ]
        pdfFile = PdfPages(outDir + 'report4_Wildlife_landscape.pdf')
    else:
        ownersToGraph = [ownership]
        pdfFile = PdfPages(outDir + 'report4_Wildlife_' + ownersToGraph[0] +
                           '.pdf')

    fig = pl.figure(1, figsize=(6.5, 8))
    for varStruct in varList:
        # setup plot for all scenarios
        ax = fig.add_subplot(3, 3, varList.index(varStruct) + 1)

        if varStruct == ' High Suitability':
            yLabelTextStruct = yLabelText + ' VFO Northern Spotted Owl High Suitability'
            modelGroup = 'vfoNSO'
        elif varStruct == 'MD High Suitability':
            yLabelTextStruct = yLabelText + ' Mule Deer High Suitability'
            varStruct = ' High Suitability'
            modelGroup = 'muleDeer'
        elif varStruct == ' DownyBrome0.66-1 (ha)':
            yLabelTextStruct = yLabelText + ' Downy Brome High Suitability'
            modelGroup = 'downyBrome'
        else:
            yLabelTextStruct = yLabelText + varStruct
            yLabelTextStruct = yLabelTextStruct.replace(" (ha)", "")
            modelGroup = 'iLAP'

        for scenario in [
                'CurrentPolicy', 'No_Treatment_Fed', 'Restoration',
                'noFireNoTreatFed'
        ]:
            inDir = outDir + runName + "_" + scenario + "\\"

            if os.path.isdir(inDir):
                if modelGroup == 'vfoNSO':
                    yearList = list(
                        set(
                            pd.io.parsers.read_csv(
                                inDir + r'VFO_Spotted_Owl_by_OWNER_pivot.csv')
                            [' Year']))
                    repList = list(
                        set(
                            pd.io.parsers.read_csv(
                                inDir + r'VFO_Spotted_Owl_by_OWNER_pivot.csv')
                            [' Run']))
                    totalArea = pd.io.parsers.read_csv(
                        inDir + r'VFO_Spotted_Owl_by_OWNER_pivot.csv')
                elif modelGroup == 'muleDeer':
                    yearList = list(
                        set(
                            pd.io.parsers.read_csv(
                                inDir +
                                r'Mule_Deer_by_OWNER_pivot.csv')[' Year']))
                    repList = list(
                        set(
                            pd.io.parsers.read_csv(
                                inDir +
                                r'Mule_Deer_by_OWNER_pivot.csv')[' Run']))
                    totalArea = pd.io.parsers.read_csv(
                        inDir + r'Mule_Deer_by_OWNER_pivot.csv')
                elif modelGroup == 'downyBrome':
                    yearList = list(
                        set(
                            pd.io.parsers.read_csv(
                                inDir +
                                r'Downy_Brome_by_OWNER_pivot.csv')[' Year']))
                    repList = list(
                        set(
                            pd.io.parsers.read_csv(
                                inDir +
                                r'Downy_Brome_by_OWNER_pivot.csv')[' Run']))
                    totalArea = pd.io.parsers.read_csv(
                        inDir + r'Downy_Brome_by_OWNER_pivot.csv')
                else:
                    yearList = list(
                        set(
                            pd.io.parsers.read_csv(
                                inDir +
                                r'ILAP_wildlife_models_by_OWNER_pivot.csv')
                            [' Year']))
                    repList = list(
                        set(
                            pd.io.parsers.read_csv(
                                inDir +
                                r'ILAP_wildlife_models_by_OWNER_pivot.csv')
                            [' Run']))
                    totalArea = pd.io.parsers.read_csv(
                        inDir + r'ILAP_wildlife_models_by_OWNER_pivot.csv')

                # get stats from multiple reps
                statsList = []
                for year in range(1, max(yearList) + 1):
                    yearArea = totalArea[totalArea[' Year'] == year]

                    dataList = []
                    for rep in repList:
                        repArea = yearArea[yearArea[' Run'] == rep]

                        # sum output over selected ownerships
                        for ownerToGraph in ownersToGraph:
                            if ownerToGraph == ownersToGraph[0]:
                                ownerArea = pd.DataFrame(repArea[
                                    repArea[' OWNER_label'] == ownerToGraph])
                                analysisTotalArea = ownerAllHa[ownerToGraph]
                                analysisForestedArea = forestedHa[ownerToGraph]
                            else:
                                tempArea = repArea[repArea[' OWNER_label'] ==
                                                   ownerToGraph]
                                #                                for varName in varList:
                                #                            totalArea.loc[list(ownerArea.index)[0],varName] += tempArea[varName].iloc[0]
                                ownerArea[varStruct].iloc[0] += tempArea[
                                    varStruct].iloc[0]

                                analysisTotalArea += ownerAllHa[ownerToGraph]
                                analysisForestedArea += forestedHa[
                                    ownerToGraph]
                                ownerToGraph = 'All'

                        if varStruct == ' DownyBrome0.66-1 (ha)' or varStruct == ' DownyBrome0.33-0.66 (ha)':
                            if analysisTotalArea > 0:
                                dataList.append(ownerArea[varStruct].iloc[0] /
                                                analysisTotalArea * 100)
                            else:
                                dataList.append(0.0)
                        else:
                            if analysisForestedArea > 0:
                                dataList.append(ownerArea[varStruct].iloc[0] /
                                                analysisForestedArea * 100)
                            else:
                                dataList.append(0.0)

                    # convert to numpy array
                    numpyList = np.array(dataList)
                    lower95th = np.mean(numpyList, axis=0) - (
                        (1.96 * np.std(numpyList, axis=0)) /
                        np.sqrt(len(repList)))
                    upper95th = np.mean(numpyList, axis=0) + (
                        (1.96 * np.std(numpyList, axis=0)) /
                        np.sqrt(len(repList)))

                    if lower95th < 0:
                        lower95th = 0.0

                    # add year data to dictionary
                    dataDict = {
                        'timeStep': year,
                        'mean': np.mean(numpyList, axis=0),
                        'std': np.std(numpyList, axis=0),
                        'lower': lower95th,
                        'upper': upper95th
                    }

                    # convert to list for DataFrame
                    statsList.append(dataDict)

                # convert to DataFrame
                dataTable = pd.DataFrame(statsList)

                figText = figTextList[varList.index(varStruct)]
                if modelGroup == 'muleDeer':
                    figText = 'Mule Deer'

                if varList.index(varStruct) + 1 > 6 or modelGroup == 'muleDeer':
                    labelXtick = True
                else:
                    labelXtick = False

                if figText == 'Black-backed WP':
                    plotLegend = (1.01, 0.87)
                else:
                    plotLegend = (-99, -99)

                if figText == 'Northern Spotted Owl\n(nest)' or figText == 'White-headed WP' or figText == 'Pileated WP':
                    labelYtick = True
                else:
                    labelYtick = False

                labelYtick = True
                xLabelText = yLabelText = ''
                reporterFunc.plotReporter4(fig, ax, '', pdfFile, dataTable,
                                           ['mean', 'lower', 'upper'],
                                           xLabelText, yLabelText, scenario,
                                           labelXtick, labelYtick, plotLegend,
                                           figText)

    reporterFunc.plotFigureText(fig, 'Simulation Year', 'Area (%)')

    pl.savefig(outDir + 'report4_Wildlife_landscape.png',
               bbox_inches='tight',
               dpi=300)
    pdfFile.savefig()
    pl.close()
    pdfFile.close()
    print "Done."
def main(subArea, runName, chartTitlePre):
    outDir = "C:\\Users\\olsenk\\Dropbox\\FPF\\Envision Runs\\keith_production\\"
    varList = [' Potential HighSev Fire (ha) PMG1', ' Potential HighSev Fire (ha) PMG2', ' Potential HighSev Fire (ha) PMG3', ' Potential HighSev Fire (ha) PMG4', ' Potential HighSev Fire (ha) PMG5']
    chartTitle = chartTitlePre
    forestedHa = reporterFunc.getPMG12345Ha(subArea)
#    PMG12345Ha = reporterFunc.getPMG12345Ha(subArea)

    # list of ownerships to graphs
    reporterName = r'PotentialDisturbance_by_OWNER_DETL_pivot.csv'
    ownerLabelField = ' OWNER_DETL_label'

    pdfFile = PdfPages(outDir + 'report5_PMG12345_HS_Hazard_byOwner.pdf')

#    for plotPage in [1,2]:
    # setup plot for all scenarios
    fig = pl.figure(1, figsize=(6.5,6.5))

    for splot in [1, 2, 3, 4]:
        ax = fig.add_subplot(2,2,splot)
        inDir = outDir + runName + "_CurrentPolicy\\"

#        if plotPage == 1:
        if splot == 1:
            ownersToGraph = ['USFS','State','Corporate Forest']
        elif splot == 2:
            ownersToGraph = ['Chemult Ranger District (Fremont-Winema NF)','Chiloquin Ranger District (Fremont-Winema NF)','Klamath Ranger District (Fremont-Winema NF)']
#        elif plotPage == 2:
        if splot == 3:
            ownersToGraph = ['ODF Sun Pass','ODF Gilchrist']
        elif splot == 4:
            ownersToGraph = ['JWTR Timber Holdings','Cascade Timberlands (Mazama Forest)','Jeld-Wen Inc','J-Spear Ranch']

        if os.path.isdir(inDir):
            yearList = list(set(pd.io.parsers.read_csv(inDir + reporterName)[' Year']))
            repList = list(set(pd.io.parsers.read_csv(inDir + reporterName)[' Run']))
            totalArea = pd.io.parsers.read_csv(inDir + reporterName)

            # sum output over selected ownerships
            for ownership in ownersToGraph:
                print ownership

                # get stats from multiple reps
                statsList = []
                for year in range(1,max(yearList) + 1):
                    yearArea = totalArea[totalArea[' Year'] == year]

                    dataList = []
                    for rep in repList:
                        repArea = yearArea[yearArea[' Run'] == rep]

                        if ownership == 'USFS':
                            ownerArea = pd.DataFrame(repArea[repArea[ownerLabelField] == 'Chemult Ranger District (Fremont-Winema NF)'])
                            fireProneArea = forestedHa['Chemult Ranger District (Fremont-Winema NF)']

                            for subOwner in ['Chiloquin Ranger District (Fremont-Winema NF)','Klamath Ranger District (Fremont-Winema NF)']:
                                tempArea = repArea[repArea[ownerLabelField] == subOwner]
                                fireProneArea += forestedHa[subOwner]
                                for varName in varList:
                                    ownerArea[varName].iloc[0] += tempArea[varName].iloc[0]

                        elif ownership == 'State':
                            ownerArea = pd.DataFrame(repArea[repArea[ownerLabelField] == 'ODF Sun Pass'])
                            fireProneArea = forestedHa['ODF Sun Pass']

                            for subOwner in ['ODF Gilchrist','ODF Gilchrist (The Conservation Fund)']:
                                tempArea = repArea[repArea[ownerLabelField] == subOwner]
                                fireProneArea += forestedHa[subOwner]
                                for varName in varList:
                                    ownerArea[varName].iloc[0] += tempArea[varName].iloc[0]

                        elif ownership == 'ODF Gilchrist':
                            ownerArea = pd.DataFrame(repArea[repArea[ownerLabelField] == 'ODF Gilchrist'])
                            fireProneArea = forestedHa['ODF Gilchrist']

                            for subOwner in ['ODF Gilchrist (The Conservation Fund)']:
                                tempArea = repArea[repArea[ownerLabelField] == subOwner]
                                fireProneArea += forestedHa[subOwner]
                                for varName in varList:
                                    ownerArea[varName].iloc[0] += tempArea[varName].iloc[0]

                        elif ownership == 'Corporate Forest':
                            ownerArea = pd.DataFrame(repArea[repArea[ownerLabelField] == 'JWTR Timber Holdings'])
                            fireProneArea = forestedHa['JWTR Timber Holdings']

                            for subOwner in ['Cascade Timberlands (Mazama Forest)','Jeld-Wen Inc','J-Spear Ranch']:
                                tempArea = repArea[repArea[ownerLabelField] == subOwner]
                                fireProneArea += forestedHa[subOwner]
                                for varName in varList:
                                    ownerArea[varName].iloc[0] += tempArea[varName].iloc[0]

                        else:
                            ownerArea = pd.DataFrame(repArea[repArea[ownerLabelField] == ownership])
                            fireProneArea = forestedHa[ownership]

                        if fireProneArea > 0:
                            dataList.append((ownerArea[' Potential HighSev Fire (ha) PMG1'].iloc[0] + ownerArea[' Potential HighSev Fire (ha) PMG2'].iloc[0] + ownerArea[' Potential HighSev Fire (ha) PMG3'].iloc[0] + ownerArea[' Potential HighSev Fire (ha) PMG4'].iloc[0] + ownerArea[' Potential HighSev Fire (ha) PMG5'].iloc[0]) / fireProneArea * 100)
                        else:
                            dataList.append(0.0)

                    # convert to numpy array
                    numpyList = np.array(dataList)
                    lower95th = np.mean(numpyList, axis=0) - ((1.96 * np.std(numpyList, axis=0)) / np.sqrt(len(repList)))
                    upper95th = np.mean(numpyList, axis=0) + ((1.96 * np.std(numpyList, axis=0)) / np.sqrt(len(repList)))

                    if lower95th < 0:
                        lower95th = 0.0

                    # add year data to dictionary
                    dataDict = {'timeStep': year, 'mean': np.mean(numpyList, axis=0), 'std': np.std(numpyList, axis=0), 'lower': lower95th, 'upper': upper95th}

                    # convert to list for DataFrame
                    statsList.append(dataDict)

                # convert to DataFrame
                dataTable = pd.DataFrame(statsList)

                plotLegend = (0.99,0.99)
                labelYtick = True
                if splot == 1:
                    labelXtick = False
                    figText = 'a'
                    plotLegend = (0.99,0.65)
                elif splot == 2:
                    labelXtick = False
                    figText = 'b'
                elif splot == 3:
                    labelXtick = True
                    figText = 'c'
                    plotLegend = (0.68,0.99)
                elif splot == 4:
                    labelXtick = True
                    figText = 'd'
                    plotLegend = (0.9,0.65)

                xLabelText = yLabelText = ''
                reporterFunc.plotReporter5(fig, ax, '', pdfFile, dataTable, ['mean','lower','upper'], xLabelText, yLabelText, ownership, labelXtick, labelYtick, plotLegend, figText)

    reporterFunc.plotFigureText(fig, 'Simulation year', 'Potential fire hazard (%)')

    pl.savefig(outDir + 'report5_PMG12345_HS_Hazard_byOwner.png', bbox_inches='tight', dpi=300)
    pdfFile.savefig()
    pl.close()
    pdfFile.close()
    print "Done."
Example #5
0
def main(subArea, runName, chartTitlePre, ownership):
    outDir = "C:\\Users\\olsenk\\Dropbox\\FPF\\Envision Runs\\keith_production\\"
    #    varList = [' Resilient (ha) PMG345', ' Semi-Resilient (ha) PMG345', ' Low Resilience (ha) PMG345']
    varList = [' Resilient (ha) PMG345', ' Low Resilience (ha) PMG345']
    yLabelText = 'Area (%)'
    chartTitle = chartTitlePre
    PMG345Ha = reporterFunc.getPMG345Ha(subArea)
    forestedHa = reporterFunc.getOwnerForestedHa(subArea)
    #    figTextList = ['High resilience','Moderate resilience','Low resilience']
    figTextList = ['High resilience', 'Low resilience']

    # list of ownerships to graphs
    ownersToGraph = [
        'Federal', 'State', 'Private Non-Industrial', 'Private Industrial',
        'Tribal', 'Homeowner'
    ]
    reporterName = r'ForestStructure2_by_OWNER_pivot.csv'
    ownerLabelField = ' OWNER_label'

    if ownership == 'All':
        pdfFile = PdfPages(outDir + 'report4_Resilience_landscape.pdf')
    elif ownership in ownersToGraph:
        ownersToGraph = [ownership]
        pdfFile = PdfPages(outDir + 'report4_Resilience_' + ownersToGraph[0] +
                           '.pdf')
    else:
        ownersToGraph = [ownership]
        pdfFile = PdfPages(outDir + 'report4_Resilience_' + ownersToGraph[0] +
                           '.pdf')
        ownerLabelField = ' OWNER_DETL_label'
        reporterName = r'ForestStructure2_by_OWNER_DETL_pivot.csv'

    fig = pl.figure(1, figsize=(6.5, 4))
    for varStruct in varList:
        # setup plot for all scenarios
        ax = fig.add_subplot(1, 2, varList.index(varStruct) + 1)

        for scenario in [
                'CurrentPolicy', 'No_Treatment_Fed', 'Restoration',
                'noFireNoTreatFed'
        ]:
            inDir = outDir + runName + "_" + scenario + "\\"

            if os.path.isdir(inDir):
                yearList = list(
                    set(pd.io.parsers.read_csv(inDir + reporterName)[' Year']))
                repList = list(
                    set(pd.io.parsers.read_csv(inDir + reporterName)[' Run']))
                totalArea = pd.io.parsers.read_csv(inDir + reporterName)

                # get stats from multiple reps
                statsList = []
                for year in range(1, max(yearList) + 1):
                    yearArea = totalArea[totalArea[' Year'] == year]

                    dataList = []
                    for rep in repList:
                        repArea = yearArea[yearArea[' Run'] == rep]

                        # sum output over selected ownerships
                        for ownerToGraph in ownersToGraph:
                            if ownerToGraph == ownersToGraph[0]:
                                ownerArea = pd.DataFrame(repArea[
                                    repArea[ownerLabelField] == ownerToGraph])
                                fireProneArea345 = PMG345Ha[ownerToGraph]
                                fireProneArea = forestedHa[ownerToGraph]
                            else:
                                tempArea = repArea[repArea[ownerLabelField] ==
                                                   ownerToGraph]
                                for varName in varList:
                                    #                            totalArea.loc[list(ownerArea.index)[0],varName] += tempArea[varName].iloc[0]
                                    ownerArea[varName].iloc[0] += tempArea[
                                        varName].iloc[0]

                                fireProneArea345 += PMG345Ha[ownerToGraph]
                                fireProneArea += forestedHa[ownerToGraph]
                                ownerToGraph = 'All'

                        if varStruct in [
                                ' Resilient (ha) PMG345',
                                ' Semi-Resilient (ha) PMG345',
                                ' Low Resilience (ha) PMG345'
                        ]:
                            if fireProneArea345 > 0:
                                dataList.append(ownerArea[varStruct].iloc[0] /
                                                fireProneArea345 * 100)
                            else:
                                dataList.append(0.0)
                        else:
                            if fireProneArea > 0:
                                dataList.append(ownerArea[varStruct].iloc[0] /
                                                fireProneArea * 100)
                            else:
                                dataList.append(0.0)

                    # convert to numpy array
                    numpyList = np.array(dataList)
                    lower95th = np.mean(numpyList, axis=0) - (
                        (1.96 * np.std(numpyList, axis=0)) /
                        np.sqrt(len(repList)))
                    upper95th = np.mean(numpyList, axis=0) + (
                        (1.96 * np.std(numpyList, axis=0)) /
                        np.sqrt(len(repList)))

                    if lower95th < 0:
                        lower95th = 0.0

                    # add year data to dictionary
                    dataDict = {
                        'timeStep': year,
                        'mean': np.mean(numpyList, axis=0),
                        'std': np.std(numpyList, axis=0),
                        'lower': lower95th,
                        'upper': upper95th
                    }

                    # convert to list for DataFrame
                    statsList.append(dataDict)

                # convert to DataFrame
                dataTable = pd.DataFrame(statsList)

                plotLegend = (-99, -99)
                if varStruct == ' Pole and Small (ha) Forest' or varStruct == ' Low Resilience (ha) PMG345':
                    plotLegend = (0.99, 0.25)

                if varList.index(varStruct) >= (len(varList) - 3):
                    labelXtick = True
                else:
                    labelXtick = False

                if varList.index(varStruct) == 0:
                    labelYtick = True
                else:
                    labelYtick = False

                xLabelText = yLabelText = ''
                reporterFunc.plotReporter4(
                    fig, ax, '', pdfFile, dataTable,
                    ['mean', 'lower', 'upper'], xLabelText, yLabelText,
                    scenario, labelXtick, labelYtick, plotLegend,
                    figTextList[varList.index(varStruct)])

    reporterFunc.plotFigureText(fig, 'Simulation Year', 'Area (%)')

    pl.savefig(outDir + 'report4_Resilience_landscape.png',
               bbox_inches='tight',
               dpi=300)
    pdfFile.savefig()
    pl.close()
    pdfFile.close()
    print "Done."
Example #6
0
def main(outDir, subArea, runList, chartTitle, ownership):
    varList = [' Early Successional (ha) Forest', ' Pole and Small (ha) Forest', ' Medium (ha) Forest', ' Large and Giant (ha) Forest',' Open Canopy (ha) Sm+ Forest',' Closed Canopy (ha) Sm+ Forest']
    yLabelText = 'Area (%)'
    figTextList = ['Early successional','Pole and small','Medium','Large and giant','Open canopy','Closed canopy']

    # list of ownerships to graphs
    ownersToGraph = ['Federal','State','Private Non-Industrial','Private Industrial','Homeowner']
    reporterName = r'ForestStructure2_by_OWNER_pivot.csv'
    reporterNameSYU = r'ForestStructure2_SYU_by_OWNER_pivot.csv'
    ownerLabelField = ' OWNER_label'

    if ownership == 'All':
        pdfFile = PdfPages(outDir + chartTitle + '_syu_ForestStructure2_landscape.pdf')
        forestedSYUArea = 222072
    elif ownership in ownersToGraph:
        ownersToGraph = [ownership]
        forestedSYUArea = 172556
        pdfFile = PdfPages(outDir + chartTitle + '_syu_ForestStructure2_' + ownersToGraph[0] + '.pdf')
    else:
        ownersToGraph = [ownership]
        pdfFile = PdfPages(outDir + chartTitle + '_syu_ForestStructure2_' + ownersToGraph[0] + '.pdf')
        ownerLabelField = ' OWNER_DETL_label'
        reporterName = r'ForestStructure2_by_OWNER_DETL_pivot.csv'

    # load area stats by owner
    areaStats = pd.io.parsers.read_csv(outDir + runList[0] + "\\AreaStats_by_OWNER_pivot.csv")
    areaStats = areaStats[areaStats[' Year'] == 1]

    # sum total areas over selected ownerships
    for ownerToGraph in ownersToGraph:
        ownerStats = areaStats[areaStats[ownerLabelField] == ownerToGraph]
        if ownerToGraph == ownersToGraph[0]:
            forestedArea = ownerStats[' Forested (ha)'].iloc[0]
        else:
            forestedArea += ownerStats[' Forested (ha)'].iloc[0]

    fig = pl.figure(1, figsize=(8,6.5))
    for varStruct in varList:
        # setup plot for all scenarios
        ax = fig.add_subplot(2,3,varList.index(varStruct) + 1)
        print ('Running ' + varStruct)

        for scenario in runList:
            inDir = outDir + scenario + "\\"

            if os.path.isdir(inDir):
                for reporter in [reporterName, reporterNameSYU]:
                    totalArea = pd.io.parsers.read_csv(inDir + reporter)
                    yearList = list(set(totalArea[' Year']))
                    repList = list(set(totalArea[' Run']))

                    # get stats from multiple reps
                    statsList = []
                    for year in range(1,max(yearList) + 1):
                        yearArea = totalArea[totalArea[' Year'] == year]

                        dataList = []
                        for rep in repList:
                            repArea = yearArea[yearArea[' Run'] == rep]

                            # sum output over selected ownerships
                            for ownerToGraph in ownersToGraph:
                                if ownerToGraph == ownersToGraph[0]:
                                    ownerArea = pd.DataFrame(repArea[repArea[ownerLabelField] == ownerToGraph])
                                else:
                                    ownerArea[varStruct].iloc[0] += repArea[repArea[ownerLabelField] == ownerToGraph][varStruct].iloc[0]

                            dataList.append(ownerArea[varStruct].iloc[0])

                        # convert to numpy array
                        numpyList = np.array(dataList)
                        lower95th = np.mean(numpyList, axis=0) - ((1.96 * np.std(numpyList, axis=0)) / np.sqrt(len(repList)))
                        upper95th = np.mean(numpyList, axis=0) + ((1.96 * np.std(numpyList, axis=0)) / np.sqrt(len(repList)))

                        if lower95th < 0:
                            lower95th = 0.0

                        # add year data to dictionary
                        dataDict = {'timeStep': year, 'mean': np.mean(numpyList, axis=0), 'std': np.std(numpyList, axis=0), 'lower': lower95th, 'upper': upper95th}

                        # convert to list for DataFrame
                        statsList.append(dataDict)

                    # convert to DataFrame
                    dataTable = pd.DataFrame(statsList)

                    if '_SYU_' in reporter:
                        scenario += '_SYU_'
                        dataTable['mean'] = dataTable['mean'] / forestedSYUArea * 100
                        dataTable['lower'] = dataTable['lower'] / forestedSYUArea * 100
                        dataTable['upper'] = dataTable['upper'] / forestedSYUArea * 100
                    else:
                        dataTable['mean'] = dataTable['mean'] / forestedArea * 100
                        dataTable['lower'] = dataTable['lower'] / forestedArea * 100
                        dataTable['upper'] = dataTable['upper'] / forestedArea * 100

                    plotLegend = (-99,-99)
                    if varStruct == ' Pole and Small (ha) Forest':
                        plotLegend = (0.8,0.45)

                    if varList.index(varStruct) >= (len(varList) - 3):
                        labelXtick = True
                    else:
                        labelXtick = False

    #                if varList.index(varStruct) == 0 or varList.index(varStruct) == 3:
                    labelYtick = True

                    xLabelText = yLabelText = ''
                    mnAxis, mxAxis = reporterFunc.plotReporter4(fig, ax, '', pdfFile, dataTable, ['mean'], xLabelText, yLabelText, scenario, labelXtick, labelYtick, plotLegend, figTextList[varList.index(varStruct)])

    reporterFunc.plotFigureText(fig, 'Simulation Year', 'Area (%)')

#    pl.savefig(outDir + 'report4_ForestStructure2_landscape.png', bbox_inches='tight', dpi=300)
    pdfFile.savefig()
    pl.close()
    pdfFile.close()
    print "Done with forest structure 2."
Example #7
0
def main(outDir, subArea, runName, chartTitlePre, ownership):
    varList = [' NumberDwellings1kmFromStandRep']
    chartTitle = chartTitlePre
    PMG345Ha = reporterFunc.getPMG345Ha(subArea)

    # list of ownerships to graphs
#    if ownership == 'All':
#        ownersToGraph = ['Federal','State','Private Non-Industrial','Private Industrial','Tribal','Homeowner']
    pdfFile = PdfPages(outDir + 'report4bw_Homes_Exposed_to_HS_Fire_All.pdf')
#    else:
#        ownersToGraph = [ownership]
#        pdfFile = PdfPages(outDir + 'report4bw_Homes_Exposed_to_HS_Fire_' + ownersToGraph[0] + '.pdf')

    # setup plot for all scenarios
    fig = pl.figure(1, figsize=(4,6.5))

    # Current Policy run required!
    for scenario in ['No_Treatment_Fed','Restoration','CurrentPolicy']:
        inDir = outDir + runName + "_" + scenario + "\\"

        if scenario == 'No_Treatment_Fed':
            yearList = list(set(pd.io.parsers.read_csv(inDir + r'FireExperience_pivot.csv')[' Year']))
            repList = list(set(pd.io.parsers.read_csv(inDir + r'FireExperience_pivot.csv')[' Run']))

        totalArea = pd.io.parsers.read_csv(inDir + r'FireExperience_pivot.csv')
        dataTable = pd.DataFrame(totalArea[totalArea[' Year'] > 0])
        dataTable['key'] = 'run' + dataTable[' Run'].astype(str) + '_' + dataTable[' Year'].astype(str)

        if scenario == 'No_Treatment_Fed':
            scenarioTable = dataTable
        else:
            scenarioTable = pd.merge(scenarioTable, dataTable, how='left', on='key')

    # sum over owners
    scenarioTable.index = scenarioTable['key']

    #Sort dataTable on number of homes exposed to fire
    scenarioTable = scenarioTable.rename(columns={' NumberDwellings1kmFromStandRep': 'CP_Dwellings1kmHSFire',' NumberDwellings1kmFromStandRep_x': 'NFT_Dwellings1kmHSFire',' NumberDwellings1kmFromStandRep_y': 'Res_Dwellings1kmHSFire'})
    dataTable = scenarioTable.sort('NFT_Dwellings1kmHSFire', ascending=False)

    for splot in [1, 2]:
        ax = fig.add_subplot(2,1,splot)

        # label plots and set percent of top values
        if splot == 1:
            yLabelText = 'Number of dwellings 1km from stand-replacing fire'
            labelXaxis = False
            figText = 'A'
            topPercent = 1.0
        elif splot == 2:
            yLabelText = 'Number of dwellings 1km from top 10% of stand-replacing fires'
            labelXaxis = True
            figText = 'B'
            topPercent = 0.1

        statsList1 = []
        statsList2 = []
        statsList3 = []

        valueSet = []
        maxValueSet = []

        for i in range(int(round(len(dataTable) * topPercent))):
            statsList1.append(dataTable['CP_Dwellings1kmHSFire'].iloc[i])
            statsList2.append(dataTable['NFT_Dwellings1kmHSFire'].iloc[i])
            statsList3.append(dataTable['Res_Dwellings1kmHSFire'].iloc[i])

        valueSet.append(statsList1)
        valueSet.append(statsList2)
        valueSet.append(statsList3)

        maxValueSet.append(max(statsList1))
        maxValueSet.append(max(statsList2))
        maxValueSet.append(max(statsList3))

        yLabelText = ''
        labelList = ['Current\nManagement','No Federal\nTreatment','Accelerated\nRestoration']
        reporterFunc.plotReporter4bw(fig, ax, ownership, pdfFile, valueSet, labelList, subArea, chartTitle, yLabelText, maxValueSet, labelXaxis, figText)


    yLabelText = 'Number of dwellings 1km from high-severity fire'
    reporterFunc.plotFigureText(fig, '', yLabelText)

    pl.savefig(outDir + 'report4bw_Homes_Exposed_to_HS_Fire_All.png', bbox_inches='tight', dpi=300)
    pdfFile.savefig()
    pl.close()
    pdfFile.close()
    print "Done."
def main(subArea, runName, chartTitlePre):
    outDir = "C:\\Users\\olsenk\\Dropbox\\FPF\\Envision Runs\\keith_production\\"
    varList = [
        ' Resilient (ha) PMG345', ' Early Successional (ha) Forest',
        ' Pole and Small (ha) Forest', ' Medium (ha) Forest',
        ' Large and Giant (ha) Forest', ' Open Canopy (ha) Forest',
        ' Moderate Canopy (ha) Forest', ' Closed Canopy (ha) Forest'
    ]
    chartTitle = chartTitlePre
    PMG345Ha = reporterFunc.getPMG345Ha(subArea)
    forestedHa = reporterFunc.getOwnerForestedHa(subArea)

    # list of ownerships to graphs
    reporterName = r'ForestStructure2_by_OWNER_DETL_pivot.csv'
    ownerLabelField = ' OWNER_DETL_label'

    pdfFile = PdfPages(outDir + 'report5bar_ForestStructre2_byOwner.pdf')

    # setup plot for all owners
    fig = pl.figure(1, figsize=(11, 8.5))

    inDir = outDir + runName + "_CurrentPolicy\\"
    ownersToGraph = [
        'USFS', 'State', 'Corporate Forest',
        'Chemult Ranger District (Fremont-Winema NF)',
        'Chiloquin Ranger District (Fremont-Winema NF)',
        'Klamath Ranger District (Fremont-Winema NF)', 'ODF Sun Pass',
        'ODF Gilchrist', 'JWTR Timber Holdings',
        'Cascade Timberlands (Mazama Forest)', 'Jeld-Wen Inc', 'J-Spear Ranch'
    ]

    if os.path.isdir(inDir):
        yearList = list(
            set(pd.io.parsers.read_csv(inDir + reporterName)[' Year']))
        repList = list(
            set(pd.io.parsers.read_csv(inDir + reporterName)[' Run']))
        totalArea = pd.io.parsers.read_csv(inDir + reporterName)

        # sum output over selected ownerships
        for ownership in ownersToGraph:
            ax = fig.add_subplot(2, 6, ownersToGraph.index(ownership) + 1)
            print ownership

            # get stats from multiple reps
            statsList = []
            for varStruct in varList:
                for year in [1, max(yearList)]:
                    yearArea = totalArea[totalArea[' Year'] == year]

                    dataList = []
                    for rep in repList:
                        repArea = yearArea[yearArea[' Run'] == rep]

                        if ownership == 'USFS':
                            ownerArea = pd.DataFrame(repArea[
                                repArea[ownerLabelField] ==
                                'Chemult Ranger District (Fremont-Winema NF)'])
                            fireProneArea345 = PMG345Ha[
                                'Chemult Ranger District (Fremont-Winema NF)']
                            fireProneArea = forestedHa[
                                'Chemult Ranger District (Fremont-Winema NF)']

                            for subOwner in [
                                    'Chiloquin Ranger District (Fremont-Winema NF)',
                                    'Klamath Ranger District (Fremont-Winema NF)'
                            ]:
                                tempArea = repArea[repArea[ownerLabelField] ==
                                                   subOwner]
                                fireProneArea345 += PMG345Ha[subOwner]
                                fireProneArea += forestedHa[subOwner]
                                for varName in varList:
                                    ownerArea[varName].iloc[0] += tempArea[
                                        varName].iloc[0]

                        elif ownership == 'State':
                            ownerArea = pd.DataFrame(repArea[
                                repArea[ownerLabelField] == 'ODF Sun Pass'])
                            fireProneArea345 = PMG345Ha['ODF Sun Pass']
                            fireProneArea = forestedHa['ODF Sun Pass']

                            for subOwner in [
                                    'ODF Gilchrist',
                                    'ODF Gilchrist (The Conservation Fund)'
                            ]:
                                tempArea = repArea[repArea[ownerLabelField] ==
                                                   subOwner]
                                fireProneArea345 += PMG345Ha[subOwner]
                                fireProneArea += forestedHa[subOwner]
                                for varName in varList:
                                    ownerArea[varName].iloc[0] += tempArea[
                                        varName].iloc[0]

                        elif ownership == 'ODF Gilchrist':
                            ownerArea = pd.DataFrame(repArea[
                                repArea[ownerLabelField] == 'ODF Gilchrist'])
                            fireProneArea345 = PMG345Ha['ODF Gilchrist']
                            fireProneArea = forestedHa['ODF Gilchrist']

                            for subOwner in [
                                    'ODF Gilchrist (The Conservation Fund)'
                            ]:
                                tempArea = repArea[repArea[ownerLabelField] ==
                                                   subOwner]
                                fireProneArea345 += PMG345Ha[subOwner]
                                fireProneArea += forestedHa[subOwner]
                                for varName in varList:
                                    ownerArea[varName].iloc[0] += tempArea[
                                        varName].iloc[0]

                        elif ownership == 'Corporate Forest':
                            ownerArea = pd.DataFrame(
                                repArea[repArea[ownerLabelField] ==
                                        'JWTR Timber Holdings'])
                            fireProneArea345 = PMG345Ha['JWTR Timber Holdings']
                            fireProneArea = forestedHa['JWTR Timber Holdings']

                            for subOwner in [
                                    'Cascade Timberlands (Mazama Forest)',
                                    'Jeld-Wen Inc', 'J-Spear Ranch'
                            ]:
                                tempArea = repArea[repArea[ownerLabelField] ==
                                                   subOwner]
                                fireProneArea345 += PMG345Ha[subOwner]
                                fireProneArea += forestedHa[subOwner]
                                for varName in varList:
                                    ownerArea[varName].iloc[0] += tempArea[
                                        varName].iloc[0]

                        else:
                            ownerArea = pd.DataFrame(
                                repArea[repArea[ownerLabelField] == ownership])
                            fireProneArea345 = PMG345Ha[ownership]
                            fireProneArea = forestedHa[ownership]

                        if varStruct in [
                                ' Resilient (ha) PMG345',
                                ' Semi-Resilient (ha) PMG345',
                                ' Low Resilience (ha) PMG345'
                        ]:
                            if fireProneArea345 > 0:
                                dataList.append((ownerArea[varStruct].iloc[0]))
                            else:
                                dataList.append(0.0)
                        else:
                            if fireProneArea > 0:
                                dataList.append((ownerArea[varStruct].iloc[0]))
                            else:
                                dataList.append(0.0)

                    # calculate percent change
                    numpyList = np.array(dataList)
                    if year == 1:
                        startYrMean = np.mean(numpyList, axis=0)
                    else:
                        endYrMean = np.mean(numpyList, axis=0)

                # convert to list for DataFrame
                statsList.append((endYrMean - startYrMean) / startYrMean * 100)

            if 'USFS' in ownership or 'Sun Pass' in ownership:
                labelYaxis = True
            else:
                labelYaxis = False

            yLabelText = 'Percent change'
            varList2 = []
            for varName in varList:
                if '(ha)' in varName:
                    varList2.append(varName[:-12])

            statsList.reverse()
            varList2.reverse()
            statsDF = pd.DataFrame(statsList)
            statsDF['positives'] = statsDF[0] > 0
            reporterFunc.plotReporter5bar(fig, ax, '', pdfFile, statsDF,
                                          varList2, yLabelText, ownership,
                                          labelYaxis)

    reporterFunc.plotFigureText(fig, 'Change in % of ownership', '')

    pl.savefig(outDir + 'report5bar_ForestStructre2_byOwner.png',
               bbox_inches='tight',
               dpi=300)
    pdfFile.savefig()
    pl.close()
    pdfFile.close()
    print "Done."
Example #9
0
def main(subArea, runName, chartTitlePre, ownership):
    outDir = "C:\\Users\\olsenk\\Dropbox\\FPF\\Envision Runs\\keith_production\\"
    varList = [
        ' Stand Replacing FirePMG3', ' Stand Replacing FirePMG4',
        ' Stand Replacing FirePMG5'
    ]
    chartTitle = chartTitlePre
    PMG345Ha = reporterFunc.getPMG345Ha(subArea)

    # list of ownerships to graphs
    if ownership == 'All':
        ownersToGraph = [
            'Federal', 'State', 'Private Non-Industrial', 'Private Industrial',
            'Tribal', 'Homeowner'
        ]
        pdfFile = PdfPages(outDir + 'report4bw_PMG345_in_HS_Fire_All.pdf')
    else:
        ownersToGraph = [ownership]
        pdfFile = PdfPages(outDir + 'report4bw_PMG345_in_HS_Fire_' +
                           ownersToGraph[0] + '.pdf')

    # setup plot for all scenarios
    fig = pl.figure(1, figsize=(4, 6.5))

    # Current Policy run required!
    for scenario in ['Restoration', 'CurrentPolicy']:
        inDir = outDir + runName + "_" + scenario + "\\"

        if scenario == 'Restoration':
            yearList = list(
                set(
                    pd.io.parsers.read_csv(
                        inDir + r'FireOccurance_by_OWNER_pivot.csv')[' Year']))
            repList = list(
                set(
                    pd.io.parsers.read_csv(
                        inDir + r'FireOccurance_by_OWNER_pivot.csv')[' Run']))

        totalArea = pd.io.parsers.read_csv(inDir +
                                           r'FireOccurance_by_OWNER_pivot.csv')
        dataTable = pd.DataFrame(totalArea[totalArea[' Year'] > 0])
        dataTable['key'] = dataTable[' OWNER_label'] + '_' + dataTable[
            ' Run'].astype(str) + '_' + dataTable[' Year'].astype(str)

        if scenario == 'Restoration':
            scenarioTable = dataTable
        else:
            scenarioTable = pd.merge(scenarioTable,
                                     dataTable,
                                     how='left',
                                     on='key')

    # sum over owners
    scenarioTable.index = scenarioTable['key']
    fireProneArea = PMG345Ha[ownersToGraph[0]]
    if ownership == 'All':
        for rep in range(len(repList)):
            for year in range(1, len(yearList)):
                for owner in ownersToGraph:
                    key = owner + '_' + str(rep) + '_' + str(year)
                    print(key)
                    if owner != ownersToGraph[0]:
                        for varName in varList:
                            scenarioTable.loc[
                                ownersToGraph[0] + '_' + str(rep) + '_' +
                                str(year), varName +
                                '_x'] += scenarioTable.loc[key, varName + '_x']
                            scenarioTable.loc[
                                ownersToGraph[0] + '_' + str(rep) + '_' +
                                str(year), varName +
                                '_y'] += scenarioTable.loc[key, varName + '_y']

        for owner in ownersToGraph:
            fireProneArea += PMG345Ha[owner]

    ownerArea = pd.DataFrame(
        scenarioTable[scenarioTable[' OWNER_label_y'] == ownersToGraph[0]])

    # calculate percent of PMG345 area for each row
    ownerArea['CP_HS_pct'] = (
        ownerArea[varList[0] + '_y'] + ownerArea[varList[1] + '_y'] +
        ownerArea[varList[2] + '_y']) / fireProneArea * 100
    ownerArea['Res_HS_pct'] = (
        ownerArea[varList[0] + '_x'] + ownerArea[varList[1] + '_x'] +
        ownerArea[varList[2] + '_x']) / fireProneArea * 100

    #Sort dataTable on percent PMG345 in HS fire
    dataTable = ownerArea.sort('CP_HS_pct', ascending=False)

    for splot in [1, 2]:
        ax = fig.add_subplot(2, 1, splot)

        # label plots and set percent of top values
        if splot == 1:
            yLabelText = 'Area of high severity fire in fire-frequent landscape (%)'
            labelXaxis = False
            figText = 'a'
            topPercent = 1.0
        elif splot == 2:
            yLabelText = 'Area of top 10% stand-replacing fires in fire-frequent landscape (%)'
            labelXaxis = True
            figText = 'b'
            topPercent = 0.1

        statsList1 = []
        statsList3 = []

        valueSet = []
        maxValueSet = []

        for i in range(int(round(len(dataTable) * topPercent))):
            statsList1.append(dataTable['CP_HS_pct'].iloc[i])
            statsList3.append(dataTable['Res_HS_pct'].iloc[i])

        valueSet.append(statsList1)
        valueSet.append(statsList3)

        maxValueSet.append(max(statsList1))
        maxValueSet.append(max(statsList3))

        labelList = ['Current\nManagement', 'Accelerated\nRestoration']
        print yLabelText
        print 'median for Current Management ' + str(np.median(valueSet[0]))
        print 'median for Restoration ' + str(np.median(valueSet[1]))
        print

        yLabelText = ''
        reporterFunc.plotReporter4bw(fig, ax, ownership, pdfFile, valueSet,
                                     labelList, subArea, chartTitle,
                                     yLabelText, maxValueSet, labelXaxis,
                                     figText)

    yLabelText = 'Area of high-severity fire (%)'
    reporterFunc.plotFigureText(fig, '', yLabelText)

    pl.savefig(outDir + 'report4bw_PMG345_in_HS_Fire_All.png',
               bbox_inches='tight',
               dpi=300)
    pdfFile.savefig()
    pl.close()
    pdfFile.close()
    print "Done."
def main(outDir, subArea, runList, chartTitle, ownership):
    varList = [
        ' Small Tree Saw Timber Total', ' Medium Tree Saw Timber Total',
        ' Large Tree Saw Timber Total', ' Giant Tree Saw Timber Total'
    ]
    yLabelText = ''
    figTextList = ['Small trees', 'Medium trees', 'Large trees', 'Giant trees']

    # list of ownerships to graphs
    ownersToGraph = [
        'Federal', 'State', 'Private Non-Industrial', 'Private Industrial',
        'Homeowner'
    ]
    reporterName = r'StandingVol_bySize_by_OWNER_pivot.csv'
    ownerLabelField = ' OWNER_label'

    if ownership == 'All':
        pdfFile = PdfPages(outDir + chartTitle +
                           '_syu_StandingVol_bySize_landscape.pdf')
    elif ownership in ownersToGraph:
        ownersToGraph = [ownership]
        pdfFile = PdfPages(outDir + chartTitle + '_syu_StandingVol_bySize_' +
                           ownersToGraph[0] + '.pdf')
    else:
        ownersToGraph = [ownership]
        pdfFile = PdfPages(outDir + chartTitle + '_syu_StandingVol_bySize_' +
                           ownersToGraph[0] + '.pdf')
        ownerLabelField = ' OWNER_DETL_label'
        reporterName = r'StandingVol_bySize_by_OWNER_DETL_pivot.csv'

    fig = pl.figure(1, figsize=(11, 8.5))
    for varStruct in varList:
        # setup plot for all scenarios
        ax = fig.add_subplot(2, 2, varList.index(varStruct) + 1)
        print('Running ' + varStruct)

        for scenario in runList:
            inDir = outDir + scenario + "\\"

            if os.path.isdir(inDir):
                totalArea = pd.io.parsers.read_csv(inDir + reporterName)
                yearList = list(set(totalArea[' Year']))
                repList = list(set(totalArea[' Run']))

                # get stats from multiple reps
                statsList = []
                statsList2 = []
                for year in range(1, max(yearList) + 1):
                    yearArea = totalArea[totalArea[' Year'] == year]

                    dataList = []
                    dataList2 = []
                    for rep in repList:
                        repArea = yearArea[yearArea[' Run'] == rep]

                        # sum output over selected ownerships
                        for ownerToGraph in ownersToGraph:
                            if ownerToGraph == ownersToGraph[0]:
                                ownerArea = pd.DataFrame(repArea[
                                    repArea[ownerLabelField] == ownerToGraph])
                            else:
                                tempArea = repArea[repArea[ownerLabelField] ==
                                                   ownerToGraph]
                                for varName in varList:
                                    #                            totalArea.loc[list(ownerArea.index)[0],varName] += tempArea[varName].iloc[0]
                                    ownerArea[varName].iloc[0] += tempArea[
                                        varName].iloc[0]

                                ownerToGraph = 'All'

                        dataList.append(ownerArea[varStruct + ' (m3)'].iloc[0])
                        dataList2.append(ownerArea[varStruct +
                                                   ' SYU (m3)'].iloc[0])

                    # convert to numpy array
                    numpyList = np.array(dataList)
                    numpyList2 = np.array(dataList2)

                    # add year data to dictionary
                    dataDict = {
                        'timeStep': year,
                        'mean': np.mean(numpyList, axis=0)
                    }
                    dataDict2 = {
                        'timeStep': year,
                        'mean': np.mean(numpyList2, axis=0)
                    }

                    # convert to list for DataFrame
                    statsList.append(dataDict)
                    statsList2.append(dataDict2)

                # convert to DataFrame
                dataTable = pd.DataFrame(statsList)
                dataTable2 = pd.DataFrame(statsList2)

                if (varList.index(varStruct)) < (len(varList) / 2):
                    labelXtick = False
                else:
                    labelXtick = True

                labelYtick = True
                yLabelText = ''

                labelYtick = True
                plotLegend = (0.99, 0.99)
                xLabelText = ''
                dataTable['mean'] = dataTable['mean'] / 1000000
                dataTable2['mean'] = dataTable2['mean'] / 1000000

                mnAxis, mxAxis = reporterFunc.plotReporter4(
                    fig, ax, '', pdfFile, dataTable, ['mean'], xLabelText,
                    yLabelText, scenario, labelXtick, labelYtick, plotLegend,
                    figTextList[varList.index(varStruct)])
                mnAxis, mxAxis = reporterFunc.plotReporter4(
                    fig, ax, '', pdfFile, dataTable2, ['mean'], xLabelText,
                    yLabelText, scenario + '_SYU_', labelXtick, labelYtick,
                    plotLegend, figTextList[varList.index(varStruct)])

    reporterFunc.plotFigureText(
        fig, 'Simulation Year',
        'Standing saw timber volume ( $\mathregular{1x10^6}$ $\mathregular{m^3}$)'
    )

    #    pl.savefig(outDir + 'report4_ForestStructure2_landscape.png', bbox_inches='tight', dpi=300)
    pdfFile.savefig()
    pl.close()
    pdfFile.close()
    print "Done with standing volume."
Example #11
0
def main(outDir, subArea, runName, chartTitlePre, ownership):
    varStruct = ' Total Merch Harvest (m3)'
    #    yLabelText = 'Percent of Landscape in'
    chartTitle = chartTitlePre
    forestedHa = reporterFunc.getOwnerForestedHa(subArea)
    ownerAllHa = reporterFunc.getOwnerHa(subArea)
    figTextList = ['A', 'B', 'C', 'D']

    # list of ownerships to graphs
    ownersToGraph = [
        'Federal', 'Tribal', 'Private Industrial', 'Private Non-Industrial'
    ]
    pdfFile = PdfPages(outDir + 'report4_Vol_Owners.pdf')

    fig = pl.figure(1, figsize=(6.5, 6.5))
    for owner in ownersToGraph:
        # setup plot for all scenarios
        ax = fig.add_subplot(2, 2, ownersToGraph.index(owner) + 1)

        #        for scenario in ['CurrentPolicy','No_Treatment_Fed','Restoration','noFireNoTreatFed','noFireCurrentPolicy']:
        for scenario in [
                'CurrentPolicy', 'No_Treatment_Fed', 'Restoration',
                'noFireNoTreatFed'
        ]:
            inDir = outDir + runName + "_" + scenario + "\\"

            if os.path.isdir(inDir):
                yearList = list(
                    set(
                        pd.io.parsers.read_csv(
                            inDir +
                            r'WoodProducts_by_OWNER_pivot.csv')[' Year']))
                repList = list(
                    set(
                        pd.io.parsers.read_csv(
                            inDir +
                            r'WoodProducts_by_OWNER_pivot.csv')[' Run']))
                totalArea = pd.io.parsers.read_csv(
                    inDir + r'WoodProducts_by_OWNER_pivot.csv')

                # get stats from multiple reps
                statsList = []
                for year in range(1, max(yearList) + 1):
                    yearArea = totalArea[totalArea[' Year'] == year]

                    dataList = []
                    for rep in repList:
                        repArea = yearArea[yearArea[' Run'] == rep]

                        ownerArea = pd.DataFrame(
                            repArea[repArea[' OWNER_label'] == owner])
                        dataList.append(ownerArea[varStruct].iloc[0])

                    # convert to numpy array
                    numpyList = np.array(dataList)
                    lower95th = np.mean(numpyList, axis=0) - (
                        (1.96 * np.std(numpyList, axis=0)) /
                        np.sqrt(len(repList)))
                    upper95th = np.mean(numpyList, axis=0) + (
                        (1.96 * np.std(numpyList, axis=0)) /
                        np.sqrt(len(repList)))

                    if lower95th < 0:
                        lower95th = 0.0

                    # add year data to dictionary
                    dataDict = {
                        'timeStep': year,
                        'mean': np.mean(numpyList, axis=0),
                        'std': np.std(numpyList, axis=0),
                        'lower': lower95th,
                        'upper': upper95th
                    }

                    # convert to list for DataFrame
                    statsList.append(dataDict)

                # convert to DataFrame
                dataTable = pd.DataFrame(statsList)

                labelXtick = True
                labelYtick = True
                plotLegend = (-99, -99)
                xLabelText = 'Simulation Year'
                dataTable['mean'] = dataTable['mean'] / 1000
                dataTable['lower'] = dataTable['lower'] / 1000
                dataTable['upper'] = dataTable['upper'] / 1000

                if ownersToGraph.index(owner) < 2:
                    labelXtick = False
                    xLabelText = ''

                if ownersToGraph.index(owner) % 2 == 1:
                    yLabelText = ''

                if owner == 'Tribal':
                    plotLegend = (0.84, 0.33)

                xLabelText = yLabelText = ''
                reporterFunc.plotReporter4(
                    fig, ax, '', pdfFile, dataTable,
                    ['mean', 'lower', 'upper'], xLabelText, yLabelText,
                    scenario, labelXtick, labelYtick, plotLegend,
                    figTextList[ownersToGraph.index(owner)])

    reporterFunc.plotFigureText(
        fig, 'Simulation Year',
        'Merchantable volume ( $\mathregular{1x10^3}$ $\mathregular{m^3}$)')

    pl.savefig(outDir + 'report4_Vol_Owners.png', bbox_inches='tight', dpi=300)
    pdfFile.savefig()
    pl.close()
    pdfFile.close()
    print "Done."