def ProcessSummaryPlots(result_dicts,
                        names,
                        options,
                        plotaverage=True,
                        speciallegend=False):
    # result_dicts: a list of dictionaries with results that we saved from CalculateSensorTemperature
    # names: a list of the corresponding names for result_dicts

    outputpath = PlotUtils.GetOutputPath('ExtendedModelSummaryPlots', options)

    if not os.path.exists(outputpath):
        os.makedirs(outputpath)

    scenariolabel = PlotUtils.GetCoolingScenarioLabel(
        CoolantTemperature.cooling)

    barrel_endcap = ''
    if hasattr(options, 'barrel'):
        structure_name = 'barrel side' if options.barrel else 'endcap'
        barrel_endcap = 'Barrel_' if options.barrel else 'Endcap_'

    full_system = hasattr(options, 'endcap') or hasattr(options, 'barrel')

    if not hasattr(options, 'endcap'):
        options.endcap = False

    if not hasattr(options, 'barrel'):
        options.barrel = False

    # Write plots
    c = ROOT.TCanvas('ExtendedModelSummaryPlotsCanvas', 'blah', 600, 500)

    xtitle = 'Time [years]'
    x = GlobalSettings.time_step_list[1:]

    styles = {
        'D0': 1,
        'D1': 10,
        'D2': 11,
        'D3': 12,
        'D4': 13,
        'D5': 14,
        'M0': 1,
        'M13': 14
    }

    # One-per-module items that nonetheless need to know about the other modules.
    # We put this here in order to print out the plot.
    for disk_layer in range(Layout.nlayers_or_disks):
        if not full_system:
            continue
        for ring_mod in range(Layout.nmodules_or_rings):
            deltavhvservices = []
            for i in range(GlobalSettings.nstep):
                index = PlotUtils.GetResultDictIndex(names, ring_mod,
                                                     disk_layer)

                # Get the multiplexed deltavhv
                # tape, type I+II cables, PP2
                deltavhv_type12pp2 = CableLosses.DeltaVHV_halfsubstructure_Type1Type2PP2(
                    names, ring_mod, disk_layer, result_dicts, i)
                # type III+IV cables
                deltavhv_type34 = CableLosses.DeltaVHV_halfsubstructure_Type3Type4(
                    names, ring_mod, disk_layer, result_dicts, i)

                # Add vhvr too
                deltavhvservices.append(deltavhv_type12pp2 + deltavhv_type34 +
                                        result_dicts[index]['vhvr'].GetY()[i])

            result_dicts[index]['deltavhvservices'] = MakeGraph(
                'HVDeltaVServices',
                'HV #Delta^{}V of HV filter, tape, cables, PP2 (one petal side)',
                xtitle, 'V', x, deltavhvservices)

    list_of_plots = list(result_dicts[0].keys())

    for plotname in list_of_plots:

        if not issubclass(type(result_dicts[0][plotname]), ROOT.TGraph):
            continue

        # collect all the graphs
        graphs = list(a[plotname] for a in result_dicts)

        # For the average plot
        average = [0] * result_dicts[0][plotname].GetN()

        for i, name in enumerate(names):
            for j in range(result_dicts[i][plotname].GetN()):
                average[j] += result_dicts[i][plotname].GetY()[j]

        average = list(average[i] / float(len(result_dicts))
                       for i in range(len(average)))
        gr_average = MakeGraph('Average_%s' % (plotname), 'average', xtitle,
                               'P [W]', x, average)
        gr_average.SetLineWidth(4)

        leg = ROOT.TLegend(0.57, 0.69, 0.91, 0.93)
        if options.barrel:
            leg = ROOT.TLegend(0.57, 0.69, 0.95, 0.93)

        PlotUtils.SetStyleLegend(leg)
        for i, g in enumerate(graphs):
            if i:
                g.SetName('%s_%d' % (g.GetName(), i))
            g.SetLineColor(
                colors.get(names[i][:2],
                           PlotUtils.ColorPalette()[i]))
            if options.endcap:
                g.SetLineStyle(styles.get(names[i][2:], 1))
            if options.barrel:
                g.SetLineStyle(styles.get(names[i][2:], 19))
            g.SetLineWidth(2)
            g.Draw('l' if i else 'al')
            leg.AddEntry(g, names[i], 'l')

        # special legend for endcap
        if speciallegend:
            if options.endcap:
                # save dummy graphs so they do not go out of scope
                dummy_graphs = SetEndcapLegendSpecial(
                    leg,
                    graphs,
                    multiplexedhv=(plotname == 'deltavhvservices'))
            elif options.barrel:
                dummy_graphs = SetBarrelLegendSpecial(leg, graphs)

        if plotaverage:
            gr_average.Draw('l')
            leg.AddEntry(gr_average, 'Average', 'l')

        # make sure there are at least 5 entries in legend (spacing)
        for i in range(5 - len(graphs) - plotaverage):
            leg.AddEntry(0, '', '')

        leg.Draw()

        #
        # Descriptive text
        #
        text = ROOT.TLegend(0.11, 0.70, 0.46, 0.92)
        PlotUtils.SetStyleLegend(text)
        PlotUtils.AddRunParameterLabels(text, [graphs[0].GetTitle()],
                                        wrap=True)
        text.Draw()

        minzero = PlotUtils.MakePlotMinimumZero(plotname)
        forcemin = PlotUtils.GetPlotForcedMinimum(plotname)

        if plotname in ['qsensor_headroom']:
            c.SetLogy(True)

        taxisfunc.FixXaxisRanges(c)
        taxisfunc.AutoFixYaxis(c, minzero=minzero, forcemin=forcemin)

        c.Print('%s/%s%s.eps' %
                (outputpath, barrel_endcap, graphs[0].GetName()))

        if plotname in ['qsensor_headroom']:
            c.SetLogy(False)

    x = GlobalSettings.time_step_list[1:]

    #
    # Process stave / petal totals. One dict per petal -- a list of 6 dicts.
    #
    if not full_system:
        return

    if True:
        result_dicts_petals = []  # endcap

        for disk_layer in range(Layout.nlayers_or_disks):
            result_dicts_petals.append(dict())
            ppetal,qsensorpetal,phvpetal,itapepetal,isensorpetal = [],[],[],[],[]
            petalhvservices = []
            petalvoutlvpp2, vdrop_roundtrip, pserviceslvfullpetal = [], [], []
            plosslvcablest1,plosslvcablest2,plosslvcablest34,plosslvpp2 = [],[],[],[]
            plosslvcablest3, plosslvcablest4 = [], []
            plosshvcablest1,plosshvcablest2,plosshvcablest34,plosshvpp2,ptapehv = [],[],[],[],[]
            petaltapedeltav, petaltapepower = [], []

            for i in range(GlobalSettings.nstep):
                ppetal.append(0)
                qsensorpetal.append(0)
                phvpetal.append(0)
                itapepetal.append(0)
                isensorpetal.append(0)
                petaltapepower.append(0)
                for ring_mod in range(Layout.nmodules_or_rings):
                    index = PlotUtils.GetResultDictIndex(
                        names, ring_mod, disk_layer)
                    ppetal[i] += result_dicts[index]['pmodule'].GetY()[i]
                    ppetal[i] += result_dicts[index]['peos'].GetY()[
                        i]  # peos should be 0 for R0-R4
                    qsensorpetal[i] += result_dicts[index]['qsensor'].GetY()[i]
                    phvpetal[i] += result_dicts[index]['phv_wleakage'].GetY(
                    )[i]
                    itapepetal[i] += result_dicts[index]['itape'].GetY()[i]
                    itapepetal[i] += result_dicts[index]['itape_eos'].GetY()[i]
                    isensorpetal[i] += result_dicts[index]['isensor'].GetY()[i]

                    # Module LV power (including module, tape)
                    # This one is quite important actually!
                    petaltapepower[i] += result_dicts[index][
                        'pmodule_noHV'].GetY()[i]

                # Five power components (0,1), (2,3), (4), (5), EOS
                petalhvservices.append(
                    CableLosses.PHVservicesFullPetal(names, disk_layer,
                                                     result_dicts, i))

                # Get the tape voltage drop, power in R5
                LastModule = (5 if options.endcap else 13)
                index_R5 = PlotUtils.GetResultDictIndex(
                    names, LastModule, disk_layer)
                tape_voltage_drop_r5 = result_dicts[index_R5][
                    'vdrop_tape'].GetY()[i]
                petaltapedeltav.append(tape_voltage_drop_r5 -
                                       PoweringEfficiency.VfeastMin)

                # Other services - LV
                petalvoutlvpp2.append(
                    CableLosses.Vout_LV_pp2(itapepetal[i],
                                            tape_voltage_drop_r5))
                vdrop_roundtrip.append(
                    CableLosses.VdropLV_RoundTrip_type1and2(itapepetal[i]))
                pserviceslvfullpetal.append(
                    CableLosses.PLVservicesFullSubstructure(
                        itapepetal[i], tape_voltage_drop_r5))
                plosslvcablest1.append(
                    CableLosses.PlossLVCablesType1(itapepetal[i]))
                plosslvcablest2.append(
                    CableLosses.PlossLVCablesType2(itapepetal[i]))
                plosslvcablest3.append(
                    CableLosses.PlossLVCablesType3(itapepetal[i],
                                                   tape_voltage_drop_r5))
                plosslvcablest4.append(
                    CableLosses.PlossLVCablesType4(itapepetal[i],
                                                   tape_voltage_drop_r5))
                plosslvcablest34.append(
                    CableLosses.PlossLVCablesType3and4(itapepetal[i],
                                                       tape_voltage_drop_r5))
                plosslvpp2.append(
                    CableLosses.Ppp2_LV(itapepetal[i], tape_voltage_drop_r5))

                # Other services - HV
                plosshvcablest1.append(
                    CableLosses.PlossHVCablesType1(names, disk_layer,
                                                   result_dicts, i))
                plosshvcablest2.append(
                    CableLosses.PlossHVCablesType2(names, disk_layer,
                                                   result_dicts, i))
                plosshvcablest34.append(
                    CableLosses.PlossHVCablesType3and4(names, disk_layer,
                                                       result_dicts, i))
                plosshvpp2.append(
                    CableLosses.Ppp2_HV(names, disk_layer, result_dicts, i))
                ptapehv.append(
                    CableLosses.PtapeHV(names, disk_layer, result_dicts, i))

            str_pet_stv = 'petal' if Layout.isEndcap else 'stave'
            aa, bb, cc = [
                'Petal', 'Disk', disk_layer
            ] if Layout.isEndcap else ['Stave', 'Layer', disk_layer]
            result_dicts_petals[disk_layer]['pmodulepetal'] = MakeGraph(
                '%sPower%s%d' % (aa, bb, cc),
                'Total power in %s (with EOS) (one side)' % (str_pet_stv),
                xtitle, 'P_{%s} [W]' % (str_pet_stv), x, ppetal)
            result_dicts_petals[disk_layer]['qsensorpetal'] = MakeGraph(
                '%sSensorQ%s%d' % (aa, bb, cc),
                'Total sensor Q in %s (one side)' % (str_pet_stv), xtitle,
                'P [W]', x, qsensorpetal)
            result_dicts_petals[disk_layer]['phv_wleakagepetal'] = MakeGraph(
                '%sHVPower%s%d' % (aa, bb, cc),
                'HV power in %s (one side)' % (str_pet_stv), xtitle, 'P [W]',
                x, phvpetal)
            result_dicts_petals[disk_layer]['itapepetal'] = MakeGraph(
                '%sTapeCurrentLV%s%d' % (aa, bb, cc),
                'LV tape current in %s (with EOS) (one side)' % (str_pet_stv),
                xtitle, 'I [A]', x, itapepetal)
            result_dicts_petals[disk_layer]['isensorpetal'] = MakeGraph(
                '%sSensorCurrent%s%d' % (aa, bb, cc),
                'Total sensor (leakage) current in %s (one side)' %
                (str_pet_stv), xtitle, 'I [mA]', x, isensorpetal)

            result_dicts_petals[disk_layer]['petalhvservices'] = MakeGraph(
                '%sHVServicesPowerLossFullPetal%s%d' % (aa, bb, cc),
                'HV Services power loss, %s (both sides)' % (str_pet_stv),
                xtitle, 'P [W]', x, petalhvservices)
            result_dicts_petals[disk_layer]['petalvoutlvpp2'] = MakeGraph(
                '%sVoutLVPP2%s%d' % (aa, bb, cc),
                'Vout at PP2 (servicing one %s side)' % (str_pet_stv), xtitle,
                'V', x, petalvoutlvpp2)
            result_dicts_petals[disk_layer]['vdrop_roundtrip'] = MakeGraph(
                '%sVdropLVRoundTripType1and2%s%d' % (aa, bb, cc),
                'Round-trip Vdrop of Type 1 and 2 cables (servicing one %s side)'
                % (str_pet_stv), xtitle, 'V', x, vdrop_roundtrip)
            result_dicts_petals[disk_layer]['pserviceslvfullpetal'] = MakeGraph(
                '%sLVServicesPowerLossFullPetal%s%d' % (aa, bb, cc),
                'LV Services (cables + PP2) power loss for a full %s (both sides)'
                % (str_pet_stv), xtitle, 'P [W]', x, pserviceslvfullpetal)
            result_dicts_petals[disk_layer]['plosslvcablest1'] = MakeGraph(
                '%sLVPowerLossCablesType1%s%d' % (aa, bb, cc),
                'LV cables power loss, type I (one %s side)' % (str_pet_stv),
                xtitle, 'P [W]', x, plosslvcablest1)
            result_dicts_petals[disk_layer]['plosslvcablest2'] = MakeGraph(
                '%sLVPowerLossCablesType2%s%d' % (aa, bb, cc),
                'LV cables power loss, type II (one %s side)' % (str_pet_stv),
                xtitle, 'P [W]', x, plosslvcablest2)
            result_dicts_petals[disk_layer]['plosslvcablest3'] = MakeGraph(
                '%sLVPowerLossCablesType3%s%d' % (aa, bb, cc),
                'LV cables power loss, type III (one %s side)' % (str_pet_stv),
                xtitle, 'P [W]', x, plosslvcablest3)
            result_dicts_petals[disk_layer]['plosslvcablest4'] = MakeGraph(
                '%sLVPowerLossCablesType4%s%d' % (aa, bb, cc),
                'LV cables power loss, type IV (one %s side)' % (str_pet_stv),
                xtitle, 'P [W]', x, plosslvcablest4)
            result_dicts_petals[disk_layer]['plosslvcablest34'] = MakeGraph(
                '%sLVPowerLossCablesType34%s%d' % (aa, bb, cc),
                'LV cables power loss, type III/IV (one %s side)' %
                (str_pet_stv), xtitle, 'P [W]', x, plosslvcablest34)
            result_dicts_petals[disk_layer]['plosslvpp2'] = MakeGraph(
                '%sLVPowerLossPP2%s%d' % (aa, bb, cc),
                'LV PP2 power loss, (one %s side)' % (str_pet_stv), xtitle,
                'P [W]', x, plosslvpp2)
            result_dicts_petals[disk_layer]['petaltapedeltav'] = MakeGraph(
                '%sLVTapeVoltageDrop%s%d' % (aa, bb, cc),
                'LV tape voltage drop (one %s side)' % (str_pet_stv), xtitle,
                '#Delta^{}V [V]', x, petaltapedeltav)
            result_dicts_petals[disk_layer]['petaltapepower'] = MakeGraph(
                '%sLVTapePower%s%d' % (aa, bb, cc),
                'LV tape power (one side), %s' % (str_pet_stv), xtitle,
                'P [W]', x, petaltapepower)

            result_dicts_petals[disk_layer]['plosshvcablest1'] = MakeGraph(
                '%sHVPowerLossCablesType1%s%d' % (aa, bb, cc),
                'HV cables power loss, type I (one %s side)' % (str_pet_stv),
                xtitle, 'P [W]', x, plosshvcablest1)
            result_dicts_petals[disk_layer]['plosshvcablest2'] = MakeGraph(
                '%sHVPowerLossCablesType2%s%d' % (aa, bb, cc),
                'HV cables power loss, type II (one %s side)' % (str_pet_stv),
                xtitle, 'P [W]', x, plosshvcablest2)
            result_dicts_petals[disk_layer]['plosshvcablest34'] = MakeGraph(
                '%sHVPowerLossCablesType34%s%d' % (aa, bb, cc),
                'HV cables power loss, type III/IV (one %s side)' %
                (str_pet_stv), xtitle, 'P [W]', x, plosshvcablest34)
            result_dicts_petals[disk_layer]['plosshvpp2'] = MakeGraph(
                '%sHVPowerLossPP2%s%d' % (aa, bb, cc),
                'HV PP2 power loss, (one %s side)' % (str_pet_stv), xtitle,
                'P [W]', x, plosshvpp2)
            result_dicts_petals[disk_layer]['ptapehv'] = MakeGraph(
                '%sHVPowerLossTape%s%d' % (aa, bb, cc),
                'HV tape power loss, (one %s side)' % (str_pet_stv), xtitle,
                'P [W]', x, ptapehv)

            thermal_runaway_yearpetal = 999
            for ring_mod in range(Layout.nmodules_or_rings):
                index = PlotUtils.GetResultDictIndex(names, ring_mod,
                                                     disk_layer)
                if result_dicts[index]['thermal_runaway_year']:
                    thermal_runaway_yearpetal = min(
                        thermal_runaway_yearpetal,
                        result_dicts[index]['thermal_runaway_year'])
            if thermal_runaway_yearpetal == 999:
                thermal_runaway_yearpetal = 0

            # Append to result_dicts for further use in ProcessSummaryTables
            index = PlotUtils.GetResultDictIndex(names, 0, disk_layer)
            for i in [
                    'pmodulepetal', 'qsensorpetal', 'phv_wleakagepetal',
                    'itapepetal', 'isensorpetal', 'petalhvservices',
                    'petalvoutlvpp2', 'vdrop_roundtrip',
                    'pserviceslvfullpetal', 'plosslvcablest1',
                    'plosslvcablest2', 'plosslvcablest3', 'plosslvcablest4',
                    'plosslvcablest34', 'plosslvpp2', 'petaltapedeltav',
                    'petaltapepower', 'plosshvcablest1', 'plosshvcablest2',
                    'plosshvcablest34', 'plosshvpp2', 'ptapehv'
            ]:
                result_dicts[index][i] = result_dicts_petals[disk_layer][i]
            result_dicts[index][
                'thermal_runaway_yearpetal'] = thermal_runaway_yearpetal

        for plotname in result_dicts_petals[0].keys():
            c.Clear()

            leg = ROOT.TLegend(0.74, 0.69, 0.91, 0.93)
            PlotUtils.SetStyleLegend(leg)
            if options.endcap:
                dummy_graphs = SetEndcapLegendSpecial(leg,
                                                      graphs,
                                                      doRings=False)
            else:
                dummy_graphs = SetBarrelLegendSpecial(leg,
                                                      graphs,
                                                      doModules=False)

            for disk_layer in range(Layout.nlayers_or_disks):
                if options.endcap:
                    result_dicts_petals[disk_layer][plotname].SetLineStyle(
                        styles.get('D%d' % disk_layer, 1))
                else:
                    result_dicts_petals[disk_layer][plotname].SetLineColor(
                        colors.get('L%d' % disk_layer, 1))
                result_dicts_petals[disk_layer][plotname].Draw(
                    'l' if disk_layer else 'al')
            text.Clear()
            PlotUtils.AddRunParameterLabels(
                text,
                additionalinfo=[result_dicts_petals[0][plotname].GetTitle()])
            text.Draw()
            leg.Draw()
            minzero = PlotUtils.MakePlotMinimumZero(plotname)
            forcemin = PlotUtils.GetPlotForcedMinimum(plotname)
            taxisfunc.AutoFixYaxis(c, minzero=minzero, forcemin=forcemin)
            c.Print('%s/%s%s.eps' %
                    (outputpath, barrel_endcap,
                     result_dicts_petals[0][plotname].GetName().replace(
                         'Disk0', '').replace('Layer0', '')))

        # Endcap totals, if necessary.
        for ring_mod in range(Layout.nmodules_or_rings):
            thermal_runaway_yearmodule = 999
            for disk_layer in range(Layout.nlayers_or_disks):
                index = PlotUtils.GetResultDictIndex(names, ring_mod,
                                                     disk_layer)
                if result_dicts[index]['thermal_runaway_year']:
                    thermal_runaway_yearmodule = min(
                        thermal_runaway_yearmodule,
                        result_dicts[index]['thermal_runaway_year'])
            if thermal_runaway_yearmodule == 999:
                thermal_runaway_yearmodule = 0

            index = PlotUtils.GetResultDictIndex(names, ring_mod, 0)
            result_dicts[index][
                'thermal_runaway_yearmodule'] = thermal_runaway_yearmodule

    #
    # Process Totals
    #
    avgitapepetal = []  # Average tape current (LV)
    rmsitapepetal = []  # RMS tape current (LV)
    pnoservicestotal = [
    ]  # Power in both endcaps (LV+HV), excluding services (e.g. excluding cables, patch-panels)
    pcoolingsystotal = [
    ]  # Power in both endcaps, adding type-1 cables and PP1 losses
    pwallpowertotal = []  # Including everything else
    phvtotal = [
    ]  # Total HV Power (sensor+resistors) in full endcap or barrel (both sides)
    pservice = []  # Service power only (opposite of noservices)
    plosslvcablest1total,plosslvcablest2total,plosslvcablest3total,plosslvcablest4total = [],[],[],[]
    plosslvpp2total = []
    plosslvPStotal = []
    nModuleSides = 2.
    nDetectors = 2.  # 2 barrel sides; 2 endcaps
    for i in range(GlobalSettings.nstep):
        avgitapepetal.append(0)
        rmsitapepetal.append(0)
        pnoservicestotal.append(0)
        pcoolingsystotal.append(0)
        pwallpowertotal.append(0)
        phvtotal.append(0)
        pservice.append(0)
        plosslvcablest1total.append(0)
        plosslvcablest2total.append(0)
        plosslvcablest3total.append(0)
        plosslvcablest4total.append(0)
        plosslvpp2total.append(0)
        plosslvPStotal.append(0)

        for disk_layer in range(Layout.nlayers_or_disks):
            index = PlotUtils.GetResultDictIndex(names, 0, disk_layer)

            # HV only
            phvtotal[i] += result_dicts[index]['phv_wleakagepetal'].GetY()[i]

            # Nominal module power (Module LV + HV + HV resistors + leakage + EOS + LV tape)
            list_noservices = ['pmodulepetal']
            list_cooling = ['plosslvcablest1', 'plosshvcablest1', 'ptapehv']
            list_pp2andlater = [
                'plosslvcablest2', 'plosshvcablest2', 'plosslvcablest34',
                'plosshvcablest34', 'plosslvpp2', 'plosshvpp2'
            ]

            avgitapepetal[i] += (result_dicts[index]['itapepetal'].GetY()[i]
                                 ) / float(Layout.nlayers_or_disks)
            rmsitapepetal[i] += (result_dicts[index]['itapepetal'].GetY()[i]
                                 )**2 / float(Layout.nlayers_or_disks)

            plosslvcablest1total[i] += result_dicts[index][
                'plosslvcablest1'].GetY()[i]
            plosslvcablest2total[i] += result_dicts[index][
                'plosslvcablest2'].GetY()[i]
            plosslvcablest3total[i] += result_dicts[index][
                'plosslvcablest3'].GetY()[i]
            plosslvcablest4total[i] += result_dicts[index][
                'plosslvcablest4'].GetY()[i]
            plosslvpp2total[i] += result_dicts[index]['plosslvpp2'].GetY()[i]

            for value in list_noservices:
                pnoservicestotal[i] += result_dicts[index][value].GetY()[i]

            for value in list_noservices + list_cooling:
                pcoolingsystotal[i] += result_dicts[index][value].GetY()[i]

            # Wall power needs the power supply losses - see later!
            for value in list_noservices + list_cooling + list_pp2andlater:
                pwallpowertotal[i] += result_dicts[index][value].GetY()[i]

            # "services" needs the power supply losses - see later!
            for value in list_cooling + list_pp2andlater:
                pservice[i] += result_dicts[index][value].GetY()[i]

        # Calculate power supply losses, and propagate to other quantities too
        plosslvPStotal[i] = pwallpowertotal[i] * (
            -1 + 1 / float(CableLosses.PowerSuppliesEfficency))
        pwallpowertotal[i] = pwallpowertotal[i] / float(
            CableLosses.PowerSuppliesEfficency)
        pservice[i] += plosslvPStotal[i]

        rmsitapepetal[i] = math.sqrt(rmsitapepetal[i])

        # endcap                2              npetals/ring            nEndcaps (2)
        # barrel                2              nstaves/side            nSides (2)
        pnoservicestotal[i] *= (nModuleSides * Layout.nstaves_petals *
                                nDetectors)
        pcoolingsystotal[i] *= (nModuleSides * Layout.nstaves_petals *
                                nDetectors)
        pwallpowertotal[i] *= (nModuleSides * Layout.nstaves_petals *
                               nDetectors)
        phvtotal[i] *= (nModuleSides * Layout.nstaves_petals * nDetectors)
        pservice[i] *= (nModuleSides * Layout.nstaves_petals * nDetectors)
        plosslvcablest1total[i] *= (nModuleSides * Layout.nstaves_petals *
                                    nDetectors)
        plosslvcablest2total[i] *= (nModuleSides * Layout.nstaves_petals *
                                    nDetectors)
        plosslvcablest3total[i] *= (nModuleSides * Layout.nstaves_petals *
                                    nDetectors)
        plosslvcablest4total[i] *= (nModuleSides * Layout.nstaves_petals *
                                    nDetectors)
        plosslvpp2total[i] *= (nModuleSides * Layout.nstaves_petals *
                               nDetectors)
        plosslvPStotal[i] *= (nModuleSides * Layout.nstaves_petals *
                              nDetectors)

    gr = dict()
    gr['avgitapepetal'] = MakeGraph(
        'AverageTapeCurrentLV',
        'Average tape LV %s current (one side)' % (structure_name), xtitle,
        'A_{%s} [A]' % ('Avg'), x, avgitapepetal)
    gr['rmsitapepetal'] = MakeGraph(
        'RMSTapeCurrentLV',
        'RMS tape LV %s current (one side)' % (structure_name), xtitle,
        'A_{%s} [A]' % ('RMS'), x, rmsitapepetal)
    gr['pnoservicestotal'] = MakeGraph(
        'TotalPowerNoServices',
        'Total power in both %ss (no services)' % (structure_name), xtitle,
        'P_{%s} [W]' % ('Total'), x, pnoservicestotal)
    gr['pcoolingsystotal'] = MakeGraph(
        'TotalPowerCoolingSys',
        'Total power in both %ss (cooling system power)' % (structure_name),
        xtitle, 'P_{%s} [W]' % ('Total'), x, pcoolingsystotal)
    gr['pwallpowertotal'] = MakeGraph(
        'TotalWallPower',
        'Total power in both %ss (wall power)' % (structure_name), xtitle,
        'P_{%s} [W]' % ('Total'), x, pwallpowertotal)
    gr['phv_wleakagetotal'] = MakeGraph(
        'TotalHVPower',
        'Total HV power (sensor + resistors) in both %ss' % (structure_name),
        xtitle, 'P_{%s} [W]' % ('HV'), x, phvtotal)
    gr['pservicetotal'] = MakeGraph(
        'TotalServicePower',
        'Total service power in both %ss' % (structure_name), xtitle,
        'P_{%s} [W]' % ('Total'), x, pservice)
    gr['plosslvcablest1total'] = MakeGraph('Total_plosslvcablest1',
                                           'plosslvcablest1', xtitle,
                                           'P_{%s} [W]' % ('Total'), x,
                                           plosslvcablest1total)
    gr['plosslvcablest2total'] = MakeGraph('Total_plosslvcablest2',
                                           'plosslvcablest2', xtitle,
                                           'P_{%s} [W]' % ('Total'), x,
                                           plosslvcablest2total)
    gr['plosslvcablest3total'] = MakeGraph('Total_plosslvcablest3',
                                           'plosslvcablest3', xtitle,
                                           'P_{%s} [W]' % ('Total'), x,
                                           plosslvcablest3total)
    gr['plosslvcablest4total'] = MakeGraph('Total_plosslvcablest4',
                                           'plosslvcablest4', xtitle,
                                           'P_{%s} [W]' % ('Total'), x,
                                           plosslvcablest4total)
    gr['plosslvpp2total'] = MakeGraph('Total_plosslvpp2', 'plosslvpp2', xtitle,
                                      'P_{%s} [W]' % ('Total'), x,
                                      plosslvpp2total)
    gr['plosslvPStotal'] = MakeGraph('Total_plosslvPS', 'plosslvPS', xtitle,
                                     'P_{%s} [W]' % ('Total'), x,
                                     plosslvPStotal)

    thermal_runaway_yeartotal = 999
    for disk_layer in range(Layout.nlayers_or_disks):
        for ring_mod in range(Layout.nmodules_or_rings):
            index = PlotUtils.GetResultDictIndex(names, ring_mod, disk_layer)
            if result_dicts[index]['thermal_runaway_year']:
                thermal_runaway_yeartotal = min(
                    thermal_runaway_yeartotal,
                    result_dicts[index]['thermal_runaway_year'])
    if thermal_runaway_yeartotal == 999:
        thermal_runaway_yeartotal = 0

    for i in [
            'pnoservicestotal', 'pcoolingsystotal', 'pwallpowertotal',
            'phv_wleakagetotal', 'pservicetotal', 'avgitapepetal',
            'rmsitapepetal', 'plosslvcablest1total', 'plosslvcablest2total',
            'plosslvcablest3total', 'plosslvcablest4total', 'plosslvPStotal',
            'plosslvpp2total'
    ]:
        result_dicts[0][i] = gr[i]

    # For summary tables in ProcessSummaryTables
    result_dicts[0]['pmoduletotal'] = result_dicts[0]['pnoservicestotal']

    result_dicts[0]['thermal_runaway_yeartotal'] = thermal_runaway_yeartotal

    for g in gr.keys():
        c.Clear()
        gr[g].Draw('al')
        text.Clear()
        PlotUtils.AddRunParameterLabels(text,
                                        additionalinfo=[gr[g].GetTitle()])
        text.Draw()
        taxisfunc.AutoFixYaxis(c, minzero=True, forcemin=False)
        c.Print('%s/%s%s.eps' % (outputpath, barrel_endcap, gr[g].GetName()))

    return
def CalculateSensorTemperature(options,itape_previous_list=[],vdrop_previous_list=[]) :
    # itape_previous must be a list with the same length as GlobalSettings.nstep
    # Same with vdrop_previous_list

    # "Initialize lists"
    # Lists of quantities vs time
    tsensor    = [] # Sensor temperature
    tabc       = [] # ABC temperature
    thcc       = [] # HCC temperature
    tfeast     = [] # FEAST temperature
    teos       = [] # EOS temperature
    pabc       = [] # ABC power
    phcc       = [] # HCC power
    pamac      = list(NominalPower.Pamac for i in range(GlobalSettings.nstep))
    peos       = [] # EOS power
    pfeast     = [] # FEAST power (due to ABC and HCC - linPOL12V specified elsewhere)
    plinpol12v = [] # linPOL12V power dissipated (powers the amac)
    pmodule    = [] # Power per module (front-end + HV)
    ptape_cumulative = [] # Power loss in tape due to items on the module, plus previous modules
    phv_wleakage = [] # HV power per module (leakage + resistors)
    isensor    = [] # Sensor current (Leakage current per module)
    phvr       = [] # HV power per module due to serial resistors
    vhvr       = [] # Voltage drop of serial resistors
    phvmux     = [] # HV Power per module parallel resistor
    itape      = [] # Tape current (load) per module
    itape_cumulative = [] # Cumulative tape current (load) per module - adding the previous modules
    itape_eos  = [] # Tape current per module (load) due to EOS
    idig       = [] # Digital current per module (ABCs+HCCs)
    ihcc_dig   = [] # Digital HCC current (all HCCs)
    ihcc_a     = list(NominalPower.nhcc*FrontEndComponents.hccIa for i in range(GlobalSettings.nstep)) # Analog HCC current
    iabc_dig   = [] # Digital ABC current (all ABCs)
    iabc_a     = list(NominalPower.nabc*FrontEndComponents.abcIa for i in range(GlobalSettings.nstep)) # Analog ABC current
    ihybrid0   = []
    ihybrid1   = []
    ihybrid2   = []
    ihybrid3   = []
    iamac_3v   = list(FrontEndComponents.amac3I for i in range(GlobalSettings.nstep)) # AMAC 3V
    iamac_1p5v = list(FrontEndComponents.amac15I for i in range(GlobalSettings.nstep)) # AMAC 1.5V
    ifeast     = [] # FEAST current (load)
    ifeast_in  = [] # FEAST current (input)
    efffeast   = [] # FEAST efficiency
    vdrop_tape = [] # Voltage drop in the module (including FEAST/linPOL12V and tape) (== vfeast of next module)
    vfeast     = [] # FEAST/linPOL12V voltage used in this module
    qsensor    = [] # sensor Q
    qsensor_headroom = [] # Sensor Qleakage headroom factor
    tc_crit = [] # Critical coolant temperature
    tid_sf_abc = [] # scale factor vs time (ABC)
    tid_sf_hcc = [] # scale factor vs time (HCC)
    tid_bump_abc = [] # TID bump vs time (ABC)
    tid_bump_hcc = [] # TID bump vs time (HCC)
    tid_shape = [] # TID shape vs time (ABC)
    # if you add a list here, then be sure to add it to the "if thermal_runaway" list

    # "Initialize temperatures"

    nomT = GlobalSettings.nomsensorT

    # These are initial values. Saved slightly differently for simplicity.
    # defTeos
    teos.append(Temperatures.Teos( NominalPower.eosP(nomT),
                                   NominalPower.Pmod(nomT, nomT, nomT, 10., 1, 0, 0, 0),
                                   0, CoolantTemperature.GetTimeStepTc()[0] ))
    # defTabc
    tabc.append(Temperatures.Tabc( NominalPower.Pabc(nomT, 1, 0),
                                   NominalPower.eosP(nomT),
                                   NominalPower.Pmod(nomT, nomT, nomT, 10., 1, 0, 0, 0),
                                   0, CoolantTemperature.GetTimeStepTc()[0] ))
    # defThcc
    thcc.append(Temperatures.Thcc( NominalPower.Phcc(nomT, 1, 0), NominalPower.eosP(nomT),
                                   NominalPower.Pmod(nomT, nomT, nomT, 10., 1, 0, 0, 0),
                                   0, CoolantTemperature.GetTimeStepTc()[0] ))
    # defTfeast
    tfeast.append(Temperatures.Tfeast( NominalPower.Pfeast(nomT, nomT, nomT, 1, 0),
                                       NominalPower.eosP(nomT),
                                       NominalPower.Pmod(nomT, nomT, nomT, 10., 1, 0, 0, 0),
                                       0, CoolantTemperature.GetTimeStepTc()[0] ))

    thermal_runaway = False
    thermal_runaway_index = 0
    thermal_runaway_year = 0
    thermal_runaway_month = 0

    ts_sweep_list = []          # Ts sweep lists as a companion to the lists below
    ts_vs_qref = []             # Qref vs sensor temperature in microW/mm^2
    static_qref = []            # corresponds to "lhs"
    ts_vs_q = []                # Q(Ts) vs sensor temperature
    ts_vs_q_at_crit = []        # Propaganda plot
    ts_vs_q_thermalbalance = [] # Thermal balance Q vs sensor temperature
    q_minus_qthermalbalance = [] # Needed for Tcoolant headroom

    x = GlobalSettings.time_step_list[1:] # for time that you want to stop at runaway.
    x_qsensor_headroom = GlobalSettings.time_step_list[1:]
    x_noRunaway = GlobalSettings.time_step_list[1:] # (for operational variables)

    # Not sure whether nstep+1 is required...
    for i in range(GlobalSettings.nstep) :

        year = int((i+1)*GlobalSettings.step)
        month = ((i+1)*GlobalSettings.step % 1.)*12.

        # sensor temperature vs sensor leakage power stuff
        ts_sweep_list.append([])
        ts_vs_qref.append([])
        ts_vs_q.append([])
        ts_vs_q_at_crit.append([])
        ts_vs_q_thermalbalance.append([])
        q_minus_qthermalbalance.append([])

        # Solve for Tsensor (ts)
        tmp_ts_list = []
        qref_rootsolve_list = []

        y_gets_over_zero = False

        itape_previous_i = 0 if not itape_previous_list else itape_previous_list[i]

        # vfeast_i otherwise known as vdrop (for FEAST, linPOL12V)
        vfeast_i = PoweringEfficiency.VfeastMin if not vdrop_previous_list else vdrop_previous_list[i]

        doserate_i = OperationalProfiles.doserate[i]
        tid_dose_i = OperationalProfiles.tid_dose[i]
        Tcoolant_i = CoolantTemperature.GetTimeStepTc()[i]

        lhs = SensorLeakage.qref[i]
        static_qref.append(lhs*1000./SensorProperties.area) # sensor leakage modeling

        for ts_i,ts in enumerate(range(GlobalSettings.ts_step*(-35),GlobalSettings.ts_step*60)) :
            ts = ts/float(GlobalSettings.ts_step)

            # sensor current at this temperature ts
            isensor_i = Temperatures.unref(SensorLeakage.qref[i],ts)/float(SensorProperties.vbias)

            # T0 temperature, which depends (via HV resistors) on ts at a given step.
            t0_noLeakage_ts_i = Temperatures.T0(NominalPower.eosP(teos[-1]),
                                                NominalPower.Pmod(tabc[-1],thcc[-1],tfeast[-1],
                                                                  vfeast_i,
                                                                  doserate_i,tid_dose_i,
                                                                  isensor_i, # You need the current here to get the heat from the HV resistors
                                                                  itape_previous_i),
                                                Tcoolant_i
                                                )

            # Module temperature, excluding the sensor power
            RcQh = t0_noLeakage_ts_i - Tcoolant_i

            rhs = Temperatures.Qref(ts,t0_noLeakage_ts_i)

            # sensor temperature vs sensor leakage power stuff
            ts_sweep_list[-1].append(ts)
            ts_vs_qref[-1].append(rhs*1000./SensorProperties.area) # Qref vs sensor temperature in microW/mm^2
            ts_vs_q[-1].append(Temperatures.unref(SensorLeakage.qref[i],ts)) # Q(Ts) vs sensor temperature
            ts_vs_q_thermalbalance[-1].append(max(0,(ts-t0_noLeakage_ts_i)/float(ThermalImpedances.Rt))) # Thermal balance Q vs sensor temperature
            if (len(ts_vs_q_thermalbalance[-1]) > 2) and ts_vs_q_thermalbalance[-1][-1] < ts_vs_q_thermalbalance[-1][-2] :
                ts_vs_q_thermalbalance[-1].pop(-1)

            y = rhs - lhs

            if y > 0 :
                y_gets_over_zero = True

            # thermal runaway
            if len(qref_rootsolve_list) and y < qref_rootsolve_list[-1] and (not y_gets_over_zero) :
                if thermal_runaway == False :
                    thermal_runaway_index = i
                    thermal_runaway_year = year
                    thermal_runaway_month = month
                thermal_runaway = True
                if n_runaway_errors[0] <= 5 :
                    print 'WARNING! Probably hit thermal runaway! Year %d Month %2.0f'%(year,month)
                if n_runaway_errors[0] == 5 :
                    print '(Suppressing additional thermal runaway efficiency errors)'
                n_runaway_errors[0] += 1
                continue

            # bad starting point
            if (ts_i == 0) and y > 0 :
                print 'Error! In year %2.1f, y starts greater than 0 (%2.2f). Exiting.'%(i*GlobalSettings.step,y)
                import sys; sys.exit()

            # unimportant region
            if y < -5 :
                continue

            # only fill solving lists if y is increasing
            if (not len(qref_rootsolve_list)) or (y > qref_rootsolve_list[-1]) :
                tmp_ts_list.append(ts)
                qref_rootsolve_list.append(y)

        if thermal_runaway :
            for i_list in [tsensor,tabc,thcc,tfeast,teos,pabc,phcc,peos,pfeast,pmodule,ptape_cumulative,phv_wleakage,isensor,phvr,vhvr,
                           phvmux,itape,itape_cumulative,itape_eos,idig,ihcc_dig,iabc_dig,ihybrid0,ihybrid1,ihybrid2,ihybrid3,ifeast,ifeast_in,efffeast,vfeast,qsensor,
                           vdrop_tape,plinpol12v,
                           tid_sf_abc,tid_sf_hcc,tid_bump_abc,tid_bump_hcc,tid_shape] :
                i_list.append(i_list[-1])
            qsensor_headroom.append(1)
            tc_crit.append(Tcoolant_i)

            # Advance one increment before shutting down
            if (thermal_runaway_index+1 < i) :
                x[i] = x[i-1]

            # Qsensor headroom has its own version:
            if (thermal_runaway_index < i) :
                x_qsensor_headroom[i] = x_qsensor_headroom[i-1]
                qsensor_headroom[-1] = 0.7

            continue

        # interpolate using TGraph "Eval" function
        graph = ROOT.TGraph(len(tmp_ts_list),array('d',qref_rootsolve_list),array('d',tmp_ts_list))
        resultts = graph.Eval(0)
        resultqsensor = Temperatures.unref(SensorLeakage.qref[i],resultts)

        # (solving step is done.)

        qsensor.append(resultqsensor)

        # Leakage current per module
        isensor.append( resultqsensor /float(SensorProperties.vbias) )

        # Calculate temperatures in the system based on sensor temperature

        #  Sensor temperature
        tsensor.append(resultts)

        # Critical Temperature Coolant calculation
        tmp_graph = ROOT.TGraph(len(ts_vs_q_thermalbalance[-1]),array('d',ts_vs_q_thermalbalance[-1]),array('d',ts_sweep_list[-1][:len(ts_vs_q_thermalbalance[-1])]))
        tmp_headroom_list = [-1]
        for xx in range(len(ts_vs_q[-1])) :
            if ts_vs_q[-1][xx] > ts_vs_q_thermalbalance[-1][-1] :
                continue
            if ts_vs_q[-1][xx] == 0 :
                continue
            tmp_headroom_list.append( ts_sweep_list[-1][xx] - tmp_graph.Eval(ts_vs_q[-1][xx]) )

        tc_crit.append( Tcoolant_i + max(tmp_headroom_list) )
        if len(tc_crit) == 2 :
            tc_crit[0] = tc_crit[1]

        # Sensor Qleakage headroom factor
        qref_crit = max(ts_vs_qref[-1]) # Critical qref -- maximum of qref list
        qsensor_headroom.append( 1 if (not static_qref[-1]) else qref_crit/float(static_qref[-1]))
        if len(qsensor_headroom) == 2 :
            qsensor_headroom[0] = qsensor_headroom[1]

        # propaganda: Ts vs Q at critical point (multiplied by headroom factor)
        for ts_i,ts in enumerate(range(GlobalSettings.ts_step*(-35),GlobalSettings.ts_step*60)) :
            ts = ts/float(GlobalSettings.ts_step)
            ts_vs_q_at_crit[-1].append(Temperatures.unref(SensorLeakage.qref[i]*qsensor_headroom[-1],ts))

        # Stuff that is useful for later on

        # module power: no leakage power, but power from hvmux and rhv is included here.
        pmodule_noLeakagePow_lastStep = NominalPower.Pmod(tabc[i-1],thcc[i-1],tfeast[i-1],
                                                          vfeast_i,
                                                          doserate_i,tid_dose_i,isensor[i],
                                                          itape_previous_i)

        # Temperature of ABC
        tabc.append(Temperatures.Tabc(NominalPower.Pabc(tabc[i-1],doserate_i,tid_dose_i),
                                      NominalPower.eosP(teos[i-1]),
                                      pmodule_noLeakagePow_lastStep,resultqsensor,Tcoolant_i)
                    )
        if (i == 0) :
            tabc.pop(0) # remove the initial value

        # Temperature of HCC
        thcc.append(Temperatures.Thcc(NominalPower.Phcc(thcc[i-1],doserate_i,tid_dose_i),
                                      NominalPower.eosP(teos[i-1]),
                                      pmodule_noLeakagePow_lastStep,resultqsensor,Tcoolant_i)
                      )
        if (i == 0) :
            thcc.pop(0) # remove the initial value

        # Temperature of FEAST
        tfeast.append(Temperatures.Tfeast(NominalPower.Pfeast(tabc[i],thcc[i],tfeast[i-1],
                                                              doserate_i,tid_dose_i),
                                          NominalPower.eosP(teos[i-1]),
                                          pmodule_noLeakagePow_lastStep,resultqsensor,Tcoolant_i)
                      )
        if (i == 0) :
            tfeast.pop(0) # remove the initial value

        # Temperature of EOS
        teos.append(Temperatures.Teos(NominalPower.eosP(teos[i-1]),
                                      pmodule_noLeakagePow_lastStep,resultqsensor,Tcoolant_i)
                    )
        if (i == 0) :
            teos.pop(0) # remove the initial value

        #
        # From here we can use actual temperatures
        #

        pmodule_noLeakagePow_thisStep = NominalPower.Pmod(tabc[i],thcc[i],tfeast[i],
                                                          vfeast_i,
                                                          doserate_i,tid_dose_i,isensor[i],
                                                          itape_previous_i)

        # ABC Power (all n ABCs)
        pabc.append(NominalPower.Pabc(tabc[i],doserate_i,tid_dose_i))
        tid_sf_abc.append(AbcTidBump.tid_scalefactor(tabc[i],doserate_i,tid_dose_i))
        tid_bump_abc.append(AbcTidBump.tid_scalePlusShape(tabc[i],doserate_i,tid_dose_i))
        tid_shape.append(1+AbcTidBump.tid_shape(tabc[i],doserate_i,tid_dose_i)*0.45)

        # HCC power (all n HCCs)
        phcc.append(NominalPower.Phcc(thcc[i],doserate_i,tid_dose_i))
        tid_sf_hcc.append(AbcTidBump.tid_scalefactor(thcc[i],doserate_i,tid_dose_i))
        tid_bump_hcc.append(AbcTidBump.tid_scalePlusShape(thcc[i],doserate_i,tid_dose_i))

        # EOS Power
        peos.append(NominalPower.eosP(teos[i]))

        # FEAST power (dissipated only by FEAST), including power dissipated due to ABC/HCCs. Both FEASTs.
        # (There is no more pfeast_abchcc)
        pfeast.append(NominalPower.Pfeast(tabc[i],thcc[i],tfeast[i],doserate_i,tid_dose_i))

        # linPOL12V power dissipated (powers the amac)
        plinpol12v.append(NominalPower.PlinPOL12V(vfeast_i))

        # Power per module (front-end + HV)
        pmodule.append(pmodule_noLeakagePow_thisStep + resultqsensor)

        # Power loss in tape due to items on the module
        # ptape.append(NominalPower.Ptape(tabc[i],thcc[i],tfeast[i],vfeast_i,doserate_i,tid_dose_i))

        # Power loss in tape due to items on the module, plus previous modules
        ptape_cumulative.append(NominalPower.Ptape_Cumulative(tabc[i],thcc[i],tfeast[i],vfeast_i,doserate_i,tid_dose_i,itape_previous_i))

        # HV power per module (leakage + Phv_R + Phv_Mux)
        phv_wleakage.append(resultqsensor + NominalPower.Phv_R( isensor[i] ) + NominalPower.Phv_Mux )

        # HV power per module due to serial resistors
        phvr.append( NominalPower.Phv_R( isensor[i] ) )

        # HV power per module due to serial resistors
        # With two filters, the current is halved and thus the DeltaV is halved.
        vhvr.append( isensor[i] * SensorProperties.Rhv / float(NominalPower.nfilter_nhvmux) )

        # HV per module due to parallel resistor
        phvmux.append(NominalPower.Phv_Mux)

        # Tape current (load) per module
        itape.append(NominalPower.Itape(tabc[i],thcc[i],tfeast[i],vfeast_i,doserate_i,tid_dose_i))

        # Cumulative tape current (load) per module - adding the previous modules
        itape_cumulative.append(NominalPower.Itape_Cumulative(tabc[i],thcc[i],tfeast[i],vfeast_i,doserate_i,tid_dose_i,itape_previous_i))

        # Voltage drop in the module (including FEAST/linPOL12V and tape) (== vfeast of next module)
        vdrop_tape.append(vfeast_i + itape_cumulative[i]*NominalPower.Rtape)

        # FEAST/linPOL12V voltage used in this module
        vfeast.append(vfeast_i)

        # Tape current (load) per module due to EOS
        itape_eos.append(NominalPower.Itape_eos(teos[i]))

        # Digital current per module (ABCs + HCCs)
        idig.append(NominalPower.Idig(tabc[i],thcc[i],doserate_i,tid_dose_i))

        # Digital current of (all) HCCs
        ihcc_dig.append(NominalPower.Ihcc_digital(thcc[i],doserate_i,tid_dose_i))

        # Digital current of (all) HCCs
        iabc_dig.append(NominalPower.Iabc_digital(tabc[i],doserate_i,tid_dose_i))

        # Hybrid currents
        ihybrid0.append( (iabc_dig[i] + iabc_a[i])*NominalPower.hybrid0_nabc/float(NominalPower.nabc) + (ihcc_dig[i] + ihcc_a[i])*NominalPower.hybrid0_nhcc/float(NominalPower.nhcc) )
        ihybrid1.append( (iabc_dig[i] + iabc_a[i])*NominalPower.hybrid1_nabc/float(NominalPower.nabc) + (ihcc_dig[i] + ihcc_a[i])*NominalPower.hybrid1_nhcc/float(NominalPower.nhcc) )
        ihybrid2.append( (iabc_dig[i] + iabc_a[i])*NominalPower.hybrid2_nabc/float(NominalPower.nabc) + (ihcc_dig[i] + ihcc_a[i])*NominalPower.hybrid2_nhcc/float(NominalPower.nhcc) )
        ihybrid3.append( (iabc_dig[i] + iabc_a[i])*NominalPower.hybrid3_nabc/float(NominalPower.nabc) + (ihcc_dig[i] + ihcc_a[i])*NominalPower.hybrid3_nhcc/float(NominalPower.nhcc) )

        # FEAST current PER FEAST (in case there is more than one feast)
        ifeast.append(NominalPower.Ifeast(tabc[i],thcc[i],doserate_i,tid_dose_i) / float(NominalPower.nfeast))

        # FEAST efficiency
        efffeast.append(PoweringEfficiency.feasteff(tfeast[i],ifeast[i]))

        # FEAST input current (both FEASTs, in case there is more than one feast.)
        # In any case there is no nfeast in the equation below.
        ifeast_in.append( (pfeast[i] + pabc[i] + phcc[i]) / float(vfeast_i) )

        # if i and math.fabs(((i+1)*GlobalSettings.step) % 1.) < 0.000001 :
        #     print 'Calculated year %.0f'%( int((i+1)*GlobalSettings.step) )

        continue # end of loop

    xtitle = 'Time [years]'
    tid_max_index = idig.index(max(idig))

    # dictionary of graphs
    gr = dict()

    gr['tsensor']    = MakeGraph('SensorTemperature'      ,'Sensor temperature'                        ,xtitle,'T_{%s} [#circ^{}C]'%('sensor'),x,tsensor   )
    gr['tabc']       = MakeGraph('AbcTemperature'         ,'ABC temperature'                           ,xtitle,'T_{%s} [#circ^{}C]'%('ABC'   ),x,tabc      )
    gr['thcc']       = MakeGraph('HCCTemperature'         ,'HCC temperature'                           ,xtitle,'T_{%s} [#circ^{}C]'%('HCC'   ),x,thcc      )
    gr['tfeast']     = MakeGraph('FEASTTemperature'       ,'FEAST temperature'                         ,xtitle,'T_{%s} [#circ^{}C]'%('Feast' ),x,tfeast    )
    gr['teos']       = MakeGraph('EOSTemperature'         ,'EOS temperature'                           ,xtitle,'T_{%s} [#circ^{}C]'%('EOS'   ),x,teos      )
    gr['peos']       = MakeGraph('EOSPower'               ,'EOS power (one side)'                      ,xtitle,'P_{%s} [W]'%('EOS'   )        ,x,peos      )
    gr['pmodule']    = MakeGraph('ModulePower'            ,'Module power (one side) (no EOS)'          ,xtitle,'P_{%s} [W]'%('module')        ,x,pmodule   )
    gr['ptape_cumulative'] = MakeGraph('TapePowerCumulative','Cumulative LV tape power loss (one module, one side)',xtitle,'P_{%s} [W]'%('tape'),x,ptape_cumulative)
    gr['phv_wleakage'] = MakeGraph('HVPower'              ,'Total HV power (with leakage and resistors) (one side)',xtitle,'P_{%s} [W]'%('HV'    )        ,x,phv_wleakage)
    gr['isensor']    = MakeGraph('SensorCurrent'          ,'Sensor (leakage) current (one module side)',xtitle,'I_{%s} [mA]'%('sensor')       ,x,list(isensor[a]*1000. for a in range(len(isensor))))
    gr['qsensor']    = MakeGraph('HVSensorQ'              ,'Sensor Q (one side)'                       ,xtitle,'P [W]'                        ,x,qsensor   )
    gr['phvr']       = MakeGraph('HVPowerSerialResistors' ,'HV power serial resistors (one side)'      ,xtitle,'P_{%s} [W]'%('HV,Rseries')    ,x,phvr      )
    gr['vhvr']       = MakeGraph('HVVdropSerialResistors' ,'HV #Delta^{}V serial resistors'            ,xtitle,'#Delta^{}V_{%s} [V]'%('HV,Rseries'),x,vhvr   )
    gr['phvmux']     = MakeGraph('HVPowerParallelResistor','HV power parallel resistor (one side)'     ,xtitle,'P_{%s} [W]'%('HV,Rparallel')  ,x,phvmux    )
    gr['itape']      = MakeGraph('TapeCurrentLV'          ,'LV tape current (one side) due to items on module',xtitle,'I_{%s} [A]'%('tape')   ,x,itape     )
    gr['itape_cumulative'] = MakeGraph('TapeCurrentLVCumulative','Cumulative LV tape current (one side)',xtitle,'I_{%s} [A]'%('tape')         ,x,itape_cumulative)
    gr['itape_eos']  = MakeGraph('TapeCurrentEOS'         ,'Tape current load for EOS (one side)'      ,xtitle,'I_{%s} [A]'%('tape')          ,x,itape_eos )
    gr['idig']       = MakeGraph('DigitalCurrent'         ,'ABC and HCC digital current'               ,xtitle,'I_{%s} [A]'%('digital')       ,x,idig      )
    gr['ihybrid0']   = MakeGraph('Hybrid0Current'         ,'Hybrid 0 current'                          ,xtitle,'I [A]'                        ,x,ihybrid0  )
    gr['ihybrid1']   = MakeGraph('Hybrid1Current'         ,'Hybrid 1 current'                          ,xtitle,'I [A]'                        ,x,ihybrid1  )
    gr['ihybrid2']   = MakeGraph('Hybrid2Current'         ,'Hybrid 2 current'                          ,xtitle,'I [A]'                        ,x,ihybrid2  )
    gr['ihybrid3']   = MakeGraph('Hybrid3Current'         ,'Hybrid 3 current'                          ,xtitle,'I [A]'                        ,x,ihybrid3  )
    gr['ifeast']     = MakeGraph('FeastCurrent'           ,'FEAST current (load, per FEAST)'           ,xtitle,'I_{%s} [A]'%('FEAST,load')    ,x,ifeast    )
    gr['ifeast_in']  = MakeGraph('FeastCurrentInput'      ,'FEAST current (input)'                     ,xtitle,'I_{%s} [A]'%('FEAST,in')      ,x,ifeast_in )
    gr['efffeast']   = MakeGraph('FeastEfficiency'        ,'Feast efficiency'                          ,xtitle,'Efficiency [%]'               ,x,efffeast  )
    gr['vfeast']     = MakeGraph('FeastVoltage'           ,'Vdrop over FEAST and linPOL12V'            ,xtitle,'#Delta^{}V [V]'               ,x,vfeast    )
    gr['vdrop_tape'] = MakeGraph('TapeVoltageDrop'        ,'Vdrop over FEAST, linPOL12V and tape'      ,xtitle,'#Delta^{}V [V]'               ,x,vdrop_tape)
    gr['qsensor_headroom'] = MakeGraph('SensorQHeadroom'  ,'Sensor Q headroom factor'                  ,xtitle,'Power headroom factor [_{}Q_{S,crit}/Q_{S}]',x_qsensor_headroom,qsensor_headroom)
    gr['tcoolant']   = MakeGraph('CoolantTemperature'     ,'Coolant temperature'                       ,xtitle,'T_{%s} [#circ^{}C]'%('coolant'),x_noRunaway,CoolantTemperature.GetTimeStepTc())
    gr['tid_sf_abc'] = MakeGraph('ABCTidBumpScaleFactor'  ,'ABC TID bump scale factor'                 ,xtitle,'scale factor'                 ,x_noRunaway,tid_sf_abc)
    gr['tid_sf_hcc'] = MakeGraph('HCCTidBumpScaleFactor'  ,'HCC TID bump scale factor'                 ,xtitle,'scale factor'                 ,x_noRunaway,tid_sf_hcc)
    gr['tid_bump_abc'] = MakeGraph('ABCTidBump'           ,'ABC TID bump'                              ,xtitle,'scale factor #times shape'    ,x_noRunaway,tid_bump_abc)
    gr['tid_bump_hcc'] = MakeGraph('HCCTidBump'           ,'HCC TID bump'                              ,xtitle,'scale factor #times shape'    ,x_noRunaway,tid_bump_hcc)
    gr['doserate']   = MakeGraph('DoseRate'               ,'Dose rate'                                 ,xtitle,'dose rate [kRad/hr]'          ,x_noRunaway,OperationalProfiles.doserate)

    # pmodule_noHV is (Power per module including leakage) minus (HV power including leakage)
    pmodule_noHV  = list(pmodule[i] - phv_wleakage[i] for i in range(len(pmodule)))
    gr['pmodule_noHV'] = MakeGraph('ModulePower_noHV','Power without HV (no EOS)',xtitle,'P [W]',x,pmodule_noHV)

    dosave = (not hasattr(options,'save') or options.save)

    # Write out to file
    if dosave :
        outputpath = PlotUtils.GetOutputPath('SensorTemperatureCalc',options)
        outfilename = '%s/%s.root'%(outputpath,'SensorTemperatureCalc')
        out = ROOT.TFile(outfilename,'recreate')
        for g in gr.keys() :
            gr[g].Write()
        out.Close()
        print 'Wrote file %s'%(outfilename)

    # Write plots
    c = ROOT.gROOT.FindObject('SensorTemperatureCalcCanvas')
    if not c :
        c = ROOT.TCanvas('SensorTemperatureCalcCanvas','blah',600,500)
    c.Clear()

    text = ROOT.TLegend(0.11,0.70,0.46,0.92) # a more flexible way to draw text.
    PlotUtils.SetStyleLegend(text)
    for g in gr.keys() :
        c.Clear()
        gr[g].Draw('al')
        text.Clear()
        PlotUtils.AddRunParameterLabels(text,additionalinfo=[gr[g].GetTitle()])
        text.Draw()
        minzero = PlotUtils.MakePlotMinimumZero(g)
        forcemin = PlotUtils.GetPlotForcedMinimum(g)
        if g == 'qsensor_headroom' :
            c.SetLogy(True)
        taxisfunc.AutoFixYaxis(c,minzero=minzero,forcemin=forcemin)
        if dosave :
            c.Print('%s/%s.eps'%(outputpath,gr[g].GetName()))
        if g == 'qsensor_headroom' :
            c.SetLogy(False)

    text.Clear()
    additionalinfo = []
    if hasattr(options,'ring_lay') and options.ring_lay != None :
        additionalinfo = ['Endcap Disk 5, R%s'%(options.ring_lay)]
    PlotUtils.AddRunParameterLabels(text,additionalinfo=additionalinfo)

    # Extra graphs that you may not want to save individually
    extr = dict()
    extr['pamac']         = MakeGraph('AMACPower'              ,'AMAC power'                                ,xtitle,'P_{%s} [W]'%('AMAC'  )        ,x,pamac     )
    extr['pabc']          = MakeGraph('ABCPower'               ,'ABC power'                                 ,xtitle,'P_{%s} [W]'%('ABC'   )        ,x,pabc      )
    extr['phcc']          = MakeGraph('HCCPower'               ,'HCC power'                                 ,xtitle,'P_{%s} [W]'%('HCC'   )        ,x,phcc      )
    extr['pfeast']        = MakeGraph('FeastPower'             ,'FEAST power'                               ,xtitle,'P_{%s} [W]'%('FEAST' )        ,x,pfeast    )
    extr['plinpol12v']    = MakeGraph('LinPOL12VPower'         ,'LinPOL12V power (for AMAC)'                ,xtitle,'P_{%s} [W]'%('linPOL12V' )    ,x,plinpol12v)
    extr['tid_shape']     = MakeGraph('TID_Shape'              ,'TID shape #times 1.45'                     ,xtitle,'shape'                        ,x,tid_shape )
    extr['ihcc_dig']      = MakeGraph('HCCDigitalCurrent'      ,'HCC digital current'                       ,xtitle,'I_{%s} [A]'%('HCC')           ,x,ihcc_dig  )
    extr['ihcc_a']        = MakeGraph('HCCAnalogCurrent'       ,'HCC analog current'                        ,xtitle,'I_{%s} [A]'%('HCC')           ,x,ihcc_a    )
    extr['iabc_dig']      = MakeGraph('HCCDigitalCurrent'      ,'ABC digital current'                       ,xtitle,'I_{%s} [A]'%('ABC')           ,x,iabc_dig  )
    extr['iabc_a']        = MakeGraph('HCCAnalogCurrent'       ,'ABC analog current'                        ,xtitle,'I_{%s} [A]'%('ABC')           ,x,iabc_a    )
    extr['iamac_3v']      = MakeGraph('AMACCurrent3V'          ,'AMAC current (3V)'                         ,xtitle,'I_{%s} [A]'%('AMAC')          ,x,iamac_3v  )
    extr['iamac_1p5v']    = MakeGraph('AMACCurrent1p5V'        ,'AMAC current (1.5V)'                       ,xtitle,'I_{%s} [A]'%('IMAC')          ,x,iamac_1p5v)

    # Kurt, put any extra plots here

    #
    # Module power
    #
    c.Clear()
    pmodule_noHV_noTapeLoss = list(pmodule[i] - phv_wleakage[i] - ptape_cumulative[i] for i in range(len(pmodule)))
    gr_pmodule_noHV_noTapeLoss = MakeGraph('ModulePower_noHV_NoTapeLoss','Power w/o HV and w/o tape loss',xtitle,'P [W]',x,pmodule_noHV_noTapeLoss)
    gr_pmodule_noHV_noTapeLoss.SetLineStyle(7)
    colors = {'pmodule'                :ROOT.kGreen+1,
              'pmodule_noHV'           :ROOT.kBlue+1,
              'pmodule_noHV_noTapeLoss':ROOT.kRed+1
              }
    leg = ROOT.TLegend(0.50,0.81,0.78,0.94)
    PlotUtils.SetStyleLegend(leg)
    for i,key in enumerate(['pmodule','pmodule_noHV']) :
        gr[key].SetLineColor(colors.get(key))
        gr[key].Draw('l' if i else 'al')
        leg.AddEntry(gr[key],gr[key].GetTitle(),'l')
    gr_pmodule_noHV_noTapeLoss.SetLineColor(colors.get('pmodule_noHV_noTapeLoss'))
    gr_pmodule_noHV_noTapeLoss.Draw('l')
    leg.AddEntry(gr_pmodule_noHV_noTapeLoss,gr_pmodule_noHV_noTapeLoss.GetTitle(),'l')
    leg.Draw()
    text.Draw()
    taxisfunc.AutoFixYaxis(c,minzero=True)
    if dosave :
        c.Print('%s/%s.eps'%(outputpath,'SummaryPowerPerModule'))

    #
    # Temperatures
    #
    c.Clear()
    colors = {'tabc'    :ROOT.kBlue+1,
              'thcc'    :ROOT.kRed+1,
              'tfeast'  :ROOT.kOrange+1,
              'teos'    :ROOT.kCyan+1,
              'tsensor' :ROOT.kGreen+1,
              'tcoolant':ROOT.kMagenta+1,
              }
    leg = ROOT.TLegend(0.52,0.69,0.80,0.93)
    PlotUtils.SetStyleLegend(leg)
    tabc_clone = gr['tabc'].Clone()
    tabc_clone.GetYaxis().SetTitle('T [#circ^{}C]')
    tabc_clone.Draw('al')
    leg.AddEntry(tabc_clone,tabc_clone.GetTitle(),'l')
    for i,key in enumerate(['thcc','tfeast','teos','tsensor','tcoolant']) :
        gr[key].SetLineColor(colors.get(key))
        gr[key].Draw('l')
        leg.AddEntry(gr[key],gr[key].GetTitle(),'l')
    leg.Draw()
    text.Draw()
    taxisfunc.AutoFixYaxis(c)
    if dosave :
        c.Print('%s/%s.eps'%(outputpath,'SummaryTemperature'))

    #
    # Temperature headroom
    #
    c.Clear()
    leg = ROOT.TLegend(0.57,0.86,0.80,0.93)
    PlotUtils.SetStyleLegend(leg)
    gr_tc_crit = MakeGraph('TcCrit','Critical Tc',xtitle,'T_{coolant} [C]',x,tc_crit)
    tc_headroom = list(tc_crit[a] - CoolantTemperature.GetTimeStepTc()[a] for a in range(len(tc_crit)))
    gr['tc_headroom'] = MakeGraph('CoolantTemperatureHeadroom','Coolant Headroom',xtitle,'Headroom T_{C} [C]',x,tc_headroom)
    gr['tcoolant'].Draw('al')
    gr_tc_crit.Draw('l')
    leg.AddEntry(gr['tcoolant'],gr['tcoolant'].GetTitle(),'l')
    leg.AddEntry(gr_tc_crit,gr_tc_crit.GetTitle(),'l')
    leg.Draw()
    text.Draw()
    taxisfunc.AutoFixYaxis(c,ignorelegend=False)
    if dosave :
        c.Print('%s/%s.eps'%(outputpath,'TemperatureHeadroom'))

    #
    # HV power summary
    #
    c.Clear()
    hv_power_resistors = list(phvr[i] + phvmux[i] for i in range(len(phvr)))
    gr['hv_power_resistors'] = MakeGraph('HVPowerResistors','Contribution from all resistors',xtitle,'P [W]',x,hv_power_resistors)
    phvmux_title_old = gr['phvmux'].GetTitle()
    gr['phvmux'].SetTitle('Contribution from parallel resistor')
    gr['phvmux'].SetLineStyle(7)
    colors = {'phv_wleakage'      :ROOT.kBlue+1,
              'hv_power_resistors':ROOT.kGreen+1,
              'phvmux'            :ROOT.kRed+1,
              }
    leg = ROOT.TLegend(0.50,0.81,0.78,0.94)
    PlotUtils.SetStyleLegend(leg)
    for i,key in enumerate(['phv_wleakage','hv_power_resistors','phvmux']) :
        gr[key].SetLineColor(colors.get(key))
        gr[key].Draw('l' if i else 'al')
        leg.AddEntry(gr[key],gr[key].GetTitle(),'l')
    leg.Draw()
    text.Draw()
    taxisfunc.AutoFixYaxis(c,minzero=True)
    if dosave :
        c.Print('%s/%s.eps'%(outputpath,'SummaryHVPower'))
    gr['phvmux'].SetTitle(phvmux_title_old)

    #
    # Total power plot
    #
    c.Clear()
    hists = dict()
    stack = ROOT.THStack('stack','stack')
    # pmod = pabc + phcc + pamac + pfeast + ptape_cumulative + phv_wleakage
    leg = ROOT.TLegend(0.61,0.63,0.86,0.93)
    leg.SetName('legend')
    PlotUtils.SetStyleLegend(leg)
    hists = []
    hists.insert(0,PlotUtils.AddToStack(stack,leg,GraphToHist(extr['pamac'])))
    hists.insert(0,PlotUtils.AddToStack(stack,leg,GraphToHist(extr['pabc'])))
    hists.insert(0,PlotUtils.AddToStack(stack,leg,GraphToHist(extr['phcc'])))
    hists.insert(0,PlotUtils.AddToStack(stack,leg,GraphToHist(extr['pfeast'])))
    hists.insert(0,PlotUtils.AddToStack(stack,leg,GraphToHist(extr['plinpol12v'])))
    hists.insert(0,PlotUtils.AddToStack(stack,leg,GraphToHist(gr['ptape_cumulative'])))
    phvresistors  = list(phvmux[i] + phvr[i] for i in range(len(phvmux)))
    gr_phvresistors = MakeGraph('ModulePower_HVResistors','Power of HV resistors',xtitle,'P [W]',x,phvresistors)
    hists.insert(0,PlotUtils.AddToStack(stack,leg,GraphToHist(gr_phvresistors))) # HV resistors
    hists.insert(0,PlotUtils.AddToStack(stack,leg,GraphToHist(gr['qsensor']))) # qsensor
    if max(peos) > 0 :
        hists.insert(0,PlotUtils.AddToStack(stack,leg,GraphToHist(gr['peos'])))

    for h in hists :
        leg.AddEntry(h,h.GetTitle().replace('power ','').replace('power','').replace(' (one module, one side)',''),'f')
    if max(peos) == 0 :
        leg.AddEntry(0,'','')

    stack.Draw('l')
    leg.Draw()
    text.Draw()
    stack.GetHistogram().GetXaxis().SetTitle(xtitle)
    stack.GetHistogram().GetYaxis().SetTitle('P [W]')
    taxisfunc.AutoFixYaxis(c,ignorelegend=False,minzero=True)
    #taxisfunc.SetYaxisRanges(c,0,20)
    if dosave :
        c.Print('%s/%s.eps'%(outputpath,'PowerStackPlot'))
    elif hasattr(options,'ring_lay') and options.ring_lay != None :
        tmp_outputpath = PlotUtils.GetOutputPath('ExtendedModelSummaryPlots',options)
        c.Print('%s/%s_EndcapR%s.eps'%(tmp_outputpath,'SummaryPowerPerModule',options.ring_lay))

    #
    # Total LV plot
    #
    c.Clear()
    hists = dict()
    stack = ROOT.THStack('stack_lv','stack_lv')
    leg = ROOT.TLegend(0.61,0.73,0.86,0.93)
    leg.SetName('legend')
    PlotUtils.SetStyleLegend(leg)
    hists = []
    hists.insert(0,PlotUtils.AddToStack(stack,leg,GraphToHist(extr['ihcc_a']  )))
    hists.insert(0,PlotUtils.AddToStack(stack,leg,GraphToHist(extr['iabc_a']  )))
    hists.insert(0,PlotUtils.AddToStack(stack,leg,GraphToHist(extr['ihcc_dig'])))
    hists.insert(0,PlotUtils.AddToStack(stack,leg,GraphToHist(extr['iabc_dig'])))

    for h in hists :
        leg.AddEntry(h,h.GetTitle().replace('current ','').replace('current',''),'f')

    stack.Draw('l')
    leg.Draw()
    text.Draw()
    stack.GetHistogram().GetXaxis().SetTitle(xtitle)
    stack.GetHistogram().GetYaxis().SetTitle('I [A]')
    taxisfunc.AutoFixYaxis(c,ignorelegend=False,minzero=True)
    if dosave :
        c.Print('%s/%s.eps'%(outputpath,'LVCurrentHCCABCStackPlot'))
    elif hasattr(options,'ring_lay') and options.ring_lay != None :
        tmp_outputpath = PlotUtils.GetOutputPath('ExtendedModelSummaryPlots',options)
        c.Print('%s/%s_EndcapR%s.eps'%(tmp_outputpath,'LVCurrentHCCABCStackPlot',options.ring_lay))

    #
    # Thermal balance curve
    #
    def PlotQGraph(can,legend,index,color,leg_label) :
        xlist = ts_sweep_list[index]
        ylist = ts_vs_q_thermalbalance[index]

        max_coolantT = max(CoolantTemperature.GetTimeStepTc())
        xlist = xlist[:xlist.index(max_coolantT + 45.)]
        ylist = ylist[:len(xlist)]

        xlist_2 = xlist[:len(ylist)]
        tmp_gr = MakeGraph('blah','blah','T_{S} [#circ^{}C]','Q [W]',xlist_2,ylist)

        # Now do the ts vs q plot
        ylist_1 = ts_vs_q[index]
        ylist_1 = ylist_1[:len(xlist)]

        index_stop = len(ylist_1)
        #too_high = list(ylist_1[i] > ylist[-1] for i in range(len(ylist_1)))
        too_high = list(ylist_1[i] > 40 for i in range(len(ylist_1)))
        if True in too_high :
            index_stop = too_high.index(True)
        tmp_gr_1 = MakeGraph('Q(thermal balance)','Q(thermal balance)','T_{S} [#circ^{}C]','Q [W]',xlist[:index_stop],ylist_1[:index_stop])

        tmp_gr  .SetLineColor(color)
        tmp_gr_1.SetLineColor(color)
        tmp_gr_1.SetLineStyle(7)

        can.cd()
        drawopt = 'l' if (True in list(issubclass(type(a),ROOT.TGraph) for a in can.GetListOfPrimitives())) else 'al'
        tmp_gr.Draw(drawopt)
        tmp_gr_1.Draw('l')

#         ylist_2 = ts_vs_q_at_crit[index]
#         index_stop = len(ylist_2)
#         too_high = list(ylist_2[i] > 40 for i in range(len(ylist_2)))
#         if True in too_high :
#             index_stop = too_high.index(True)
#         tmp_gr_2 = MakeGraph('q_crit','q crit','T_{S} [#circ^{}C]','Q [W]',xlist[:index_stop],ylist_2[:index_stop])
#         tmp_gr_2.SetLineColor(color)
#         tmp_gr_2.Draw('l')

        legend.AddEntry(tmp_gr,leg_label,'l')

        return tmp_gr,tmp_gr_1#,tmp_gr_2

    c.Clear()
    leg = ROOT.TLegend(0.61,0.80,0.93,0.93)
    PlotUtils.SetStyleLegend(leg)
    year1_index = int(1./float(GlobalSettings.step))

    collection = []
    collection.append(PlotQGraph(c,leg,year1_index,PlotUtils.ColorPalette()[0],'t = 1 year'  ))
    collection.append(PlotQGraph(c,leg,tid_max_index,PlotUtils.ColorPalette()[1],'t = tid bump'))
    if thermal_runaway_index :
        collection.append(PlotQGraph(c,leg,thermal_runaway_index,PlotUtils.ColorPalette()[3],'t = thermal runaway'))
    else :
        collection.append(PlotQGraph(c,leg,-1,PlotUtils.ColorPalette()[2],'t = %d years'%(GlobalSettings.nyears)))
    leg.Draw()

    taxisfunc.AutoFixYaxis(c)

    if dosave :
        c.Print('%s/%s.eps'%(outputpath,'QVersusTs'))

    #
    # Sensor temperature vs sensor leakage power
    #
    def PlotQRefGraph(can,legend,index,color,leg_label) :
        xlist = ts_vs_qref[index]
        ylist = ts_sweep_list[index]

        max_coolantT = max(CoolantTemperature.GetTimeStepTc())
        ylist = ylist[:ylist.index(max_coolantT + 45.)]
        xlist = xlist[:len(ylist)]

        x_max_i = xlist.index(max(xlist))

        # Trim top
        tmp_y = ylist
        while xlist[-1] < 0 :
            xlist.pop(-1)
            tmp_y.pop(-1)

        tmp_gr   = MakeGraph('blah','blah','q^{}_{ref} at  #minus15#circ^{}C [#mu^{}W/mm^{2}]','T_{S} [#circ^{}C]',xlist[:x_max_i+1],tmp_y[:x_max_i+1])
        tmp_gr_1 = MakeGraph('blah','blah','q^{}_{ref} at  #minus15#circ^{}C [#mu^{}W/mm^{2}]','T_{S} [#circ^{}C]',xlist[x_max_i:],tmp_y[x_max_i:])

        tmp_gr  .SetLineColor(color)
        tmp_gr_1.SetLineColor(color)
        tmp_gr_1.SetLineStyle(7)

         # Set 0 point
        tmp_gr.SetPoint(0,0,tmp_gr.Eval(0))
        while tmp_gr.GetX()[1] < 0 :
            tmp_gr.RemovePoint(1)

        can.cd()
        drawopt = 'l' if (True in list(issubclass(type(a),ROOT.TGraph) for a in can.GetListOfPrimitives())) else 'al'
        tmp_gr.Draw(drawopt)
        tmp_gr_1.Draw('l')

        static_qref_ts = ylist[xlist.index(max(xlist))]
        if static_qref[index] < max(xlist) :
            static_qref_ts = tmp_gr.Eval(static_qref[index])
        tmp_gr_2 = MakeGraph('blah','blah','','',[static_qref[index]],[static_qref_ts])
        tmp_gr_2.SetMarkerColor(color)
        tmp_gr_2.Draw('p')

        legend.AddEntry(tmp_gr,leg_label,'l')
        tmp_gr.GetXaxis().SetTitle('q^{}_{ref} at  #minus15#circ^{}C [#mu^{}W/mm^{2}]')
        tmp_gr.GetYaxis().SetTitle('T_{S} [#circ^{}C]')
        return tmp_gr,tmp_gr_1,tmp_gr_2

    c.Clear()
    leg = ROOT.TLegend(0.61,0.80,0.93,0.93)
    PlotUtils.SetStyleLegend(leg)
    collection = []
    collection.append(PlotQRefGraph(c,leg,year1_index  ,PlotUtils.ColorPalette()[0],'t = 1 year'))
    collection.append(PlotQRefGraph(c,leg,tid_max_index,PlotUtils.ColorPalette()[1],'t = tid bump'))
    if thermal_runaway_index :
        collection.append(PlotQRefGraph(c,leg,thermal_runaway_index,PlotUtils.ColorPalette()[3],'t = thermal runaway'))
    else :
        collection.append(PlotQRefGraph(c,leg,-1           ,PlotUtils.ColorPalette()[2],'t = %d years'%(GlobalSettings.nyears)))
    leg.Draw()

    taxisfunc.AutoFixYaxis(c)
    taxisfunc.FixXaxisRanges(c)

    if dosave :
        c.Print('%s/%s.eps'%(outputpath,'QrefVersusTs'))

    #
    # TID Characterization vs time
    #
    c.Clear()
    leg = ROOT.TLegend(0.52,0.76,0.84,0.93)
    PlotUtils.SetStyleLegend(leg)
    extr['tid_shape'].Draw('al')
    leg.AddEntry(extr['tid_shape'],extr['tid_shape'].GetTitle(),'l')
    for i,g in enumerate(['tid_bump_abc','tid_bump_hcc','tid_sf_abc','tid_sf_hcc']) :
        gr[g].SetLineColor(PlotUtils.ColorPalette()[i%2+1])
        if i > 1 :
            gr[g].SetLineStyle(7)
        gr[g].Draw('l')
        leg.AddEntry(gr[g],gr[g].GetTitle(),'l')
    leg.Draw()
    text.Draw()
    taxisfunc.AutoFixYaxis(c)
    if dosave :
        c.Print('%s/%s.eps'%(outputpath,'TIDBumpCharacterization'))
    elif hasattr(options,'ring_lay') and options.ring_lay != None :
        tmp_outputpath = PlotUtils.GetOutputPath('ExtendedModelSummaryPlots',options)
        c.Print('%s/%s_EndcapR%s.eps'%(tmp_outputpath,'TIDBumpCharacterization',options.ring_lay))

    #
    # TID Characterization vs dose
    #
    c.Clear()
    leg = ROOT.TLegend(0.52,0.76,0.84,0.93)
    PlotUtils.SetStyleLegend(leg)
    gr_vdose = dict()
    xtitle_dose = 'Integrated dose [MRad]'
    x_dose = list(a/1000. for a in OperationalProfiles.tid_dose[1:])
    gr_vdose['tid_shape']    = MakeGraph('TID_ShapeVsDose'            ,'TID shape #times 1.45'    ,xtitle_dose,'shape',x_dose,tid_shape)
    gr_vdose['tid_sf_abc']   = MakeGraph('ABCTidBumpScaleFactorVsDose','ABC TID bump scale factor',xtitle_dose,'shape',x_dose,tid_sf_abc)
    gr_vdose['tid_sf_hcc']   = MakeGraph('HCCTidBumpScaleFactorVsDose','HCC TID bump scale factor',xtitle_dose,'shape',x_dose,tid_sf_hcc)
    gr_vdose['tid_bump_abc'] = MakeGraph('ABCTidBumpVsDose'           ,'ABC TID bump'             ,xtitle_dose,'shape',x_dose,tid_bump_abc)
    gr_vdose['tid_bump_hcc'] = MakeGraph('HCCTidBumpVsDose'           ,'HCC TID bump'             ,xtitle_dose,'shape',x_dose,tid_bump_hcc)
    gr_vdose['tid_shape'].Draw('al')
    leg.AddEntry(extr['tid_shape'],extr['tid_shape'].GetTitle(),'l')
    for i,g in enumerate(['tid_bump_abc','tid_bump_hcc','tid_sf_abc','tid_sf_hcc']) :
        gr_vdose[g].SetLineColor(PlotUtils.ColorPalette()[i%2+1])
        if i > 1 :
            gr_vdose[g].SetLineStyle(7)
        gr_vdose[g].Draw('l')
        leg.AddEntry(gr_vdose[g],gr_vdose[g].GetTitle(),'l')
    leg.Draw()
    text.Draw()
    taxisfunc.AutoFixYaxis(c)
    if dosave :
        c.Print('%s/%s.eps'%(outputpath,'TIDBumpCharacterizationVsDose'))
    elif hasattr(options,'ring_lay') and options.ring_lay != None :
        tmp_outputpath = PlotUtils.GetOutputPath('ExtendedModelSummaryPlots',options)
        c.Print('%s/%s_EndcapR%s.eps'%(tmp_outputpath,'TIDBumpCharacterizationVsDose',options.ring_lay))

    # Kurt, put any extra plots here -- End.

    # Claire, put any extra plots here

    # Claire, put any extra plots here -- End.

    # return all the graphs
    return_items = gr
    return_items['thermal_runaway_year'] = thermal_runaway_year
    return_items['thermal_runaway_month'] = thermal_runaway_month

    return return_items