public void DoOneRun(int RunId, WeightingCombination[] i_weightingCombinations, ParameterValues parameters) { double i_aggregatedDamage; ModelOutput i_output1; // Create Output object for run 1, set addmp to 0 so that // the extra greenhouse gases are not emitted and then run // the model i_output1 = new ModelOutput(); var fundWorkflow = new Esmf.Model.ModelTyped <FundWorkflow>(); var result1 = fundWorkflow.Run(parameters); i_output1.Load(result1); for (int i = 0; i < i_weightingCombinations.Length; i++) { i_weightingCombinations[i].CalculateWeights(i_output1); i_aggregatedDamage = i_weightingCombinations[i].AddDamagesUp(i_output1.Damages, _run.YearsToAggregate, _emissionYear); WriteAggregateDamage(RunId, i, i_aggregatedDamage, i_weightingCombinations); } //for (int l = 0; l < i_output1.Damages.Count; l++) //{ // i_Damage = i_output1.Damages[l]; // if ((i_Damage.Year >= _emissionYear.Value) && (i_Damage.Year < _emissionYear.Value + _run.YearsToAggregate)) // { // for (int k = 0; k < i_weightingCombinations.Length; k++) // WriteDamage(RunId, i_Damage, k, i_weightingCombinations[k][i_Damage.Year, i_Damage.Region], i_weightingCombinations); // } //} }
public void Run() { // Load parameters var parameters = new Parameters(); parameters.ReadExcelFile(@"Data\Parameter - base.xlsm"); // Get best guess parameter values var parameterValues = parameters.GetBestGuess(); // Create a new model that inits itself from the parameters just loaded var model = new Esmf.Model.ModelTyped<FundWorkflow>(); // Run the model var rs = model.Run(parameterValues); // Display all variables in interactive window OutputHelper.ShowModel(rs); }
public static void Run() { int monteCarloRuns = 10000; // Load parameters var parameters = new Parameters(); parameters.ReadExcelFile(@"Data\Parameter - base.xlsm"); // Do one best guess run { var model = new Esmf.Model.ModelTyped <FundWorkflow>(); //var model = new FundWorkflow(parameters.GetBestGuess()); model.Run(parameters.GetBestGuess()); } int currentRun = 0; var stopwatch = new Stopwatch(); stopwatch.Start(); ParallelMonteCarlo.DoParallelRun( parameters, monteCarloRuns, p => { var m = new Esmf.Model.ModelTyped <FundWorkflow>(); m.Run(p); int tempCurrentCount = Interlocked.Increment(ref currentRun); Console.Write("\rRun {0} ", tempCurrentCount); return(0.0); }, d => 0.0); stopwatch.Stop(); Console.WriteLine(); Console.WriteLine(stopwatch.Elapsed); }
public static void Run() { int monteCarloRuns = 10000; // Load parameters var parameters = new Parameters(); parameters.ReadExcelFile(@"Data\Parameter - base.xlsm"); // Do one best guess run { var model = new Esmf.Model.ModelTyped<FundWorkflow>(); //var model = new FundWorkflow(parameters.GetBestGuess()); model.Run(parameters.GetBestGuess()); } int currentRun = 0; var stopwatch = new Stopwatch(); stopwatch.Start(); ParallelMonteCarlo.DoParallelRun( parameters, monteCarloRuns, p => { var m = new Esmf.Model.ModelTyped<FundWorkflow>(); m.Run(p); int tempCurrentCount = Interlocked.Increment(ref currentRun); Console.Write("\rRun {0} ", tempCurrentCount); return 0.0; }, d => 0.0); stopwatch.Stop(); Console.WriteLine(); Console.WriteLine(stopwatch.Elapsed); }
public void TestMigrationDeterministic() { var parameterDefinition = new Parameters(); parameterDefinition.ReadExcelFile("Parameter - Base.xlsm"); var p = parameterDefinition.GetBestGuess(); var m = new Esmf.Model.ModelTyped<FundWorkflow>(); var res = m.Run(p); var c = new Clock(Timestep.FromYear(1951), Timestep.FromYear(2999)); while (!c.IsLastTimestep) { var regions = res.Dimensions.GetValues<Region>(); double totalLeave = (from r in regions select res.RootComponent.ImpactSeaLevelRise.leave[c.Current, r]).Sum(); double totalEnter = (from r in regions select res.RootComponent.ImpactSeaLevelRise.enter[c.Current, r]).Sum(); Assert.IsTrue(Math.Abs(totalLeave - totalEnter) < 1.0, "Migration doesn't even out"); c.Advance(); } }
public void TestMigrationProbabalistic() { var parameterDefinition = new Parameters(); parameterDefinition.ReadExcelFile("Parameter - Base.xlsm"); var p = parameterDefinition.GetBestGuess(); var m = new Esmf.Model.ModelTyped <FundWorkflow>(); var res = m.Run(p); var c = new Clock(Timestep.FromYear(1951), Timestep.FromYear(2999)); while (!c.IsLastTimestep) { var regions = res.Dimensions.GetValues <Region>(); double totalLeave = (from r in regions select res.RootComponent.ImpactSeaLevelRise.leave[c.Current, r]).Sum(); double totalEnter = (from r in regions select res.RootComponent.ImpactSeaLevelRise.enter[c.Current, r]).Sum(); Assert.IsTrue(Math.Abs(totalLeave - totalEnter) < 1.0, "Migration doesn't even out"); c.Advance(); } }
public static void Run(string configurationFileName) { TextWriter gDisaggregatedCsvFile = null; TextWriter lAggregateMarginalDamage = null; TextWriter lGlobalInputCsv = null; TextWriter lRegionInputCsv = null; TextWriter lYearInputCsv = null; TextWriter lRegionYearInputCsv = null; SimulationManager lSimulationManager; var lDefaultConfigurationFile = Path.Combine(Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "Data"), "DefaultSimulation.xml"); lSimulationManager = new SimulationManager(configurationFileName == null ? lDefaultConfigurationFile : configurationFileName); lSimulationManager.Load(); if (!Directory.Exists(ConsoleApp.OutputPath)) Directory.CreateDirectory(ConsoleApp.OutputPath); var lRandom = GetNewRandom(lSimulationManager); lAggregateMarginalDamage = TextWriter.Synchronized(new StreamWriter(Path.Combine(ConsoleApp.OutputPath, "Output - Aggregate marginal damage.csv"))); var TempOutputFile = new StreamWriter(Path.Combine(ConsoleApp.OutputPath, "Output - Temp.csv")); if (lSimulationManager.OutputVerbal) { lAggregateMarginalDamage.Write("Scenario"); lAggregateMarginalDamage.Write(";"); lAggregateMarginalDamage.Write("Gas"); lAggregateMarginalDamage.Write(";"); lAggregateMarginalDamage.Write("Emissionyear"); lAggregateMarginalDamage.Write(";"); lAggregateMarginalDamage.Write("Run"); lAggregateMarginalDamage.Write(";"); lAggregateMarginalDamage.Write("Weightingscheme"); lAggregateMarginalDamage.Write(";"); lAggregateMarginalDamage.Write("Marginal damage"); lAggregateMarginalDamage.WriteLine(); } TextWriter lSummaryDamage = TextWriter.Synchronized(new StreamWriter(Path.Combine(ConsoleApp.OutputPath, "Output - Summary damage.csv"))); if (lSimulationManager.OutputVerbal) { lSummaryDamage.WriteLine("Scenario;Gas;Emissionyear;Weightingscheme;Bestguess;Mean;TrimMean0.1%;TrimMean1%;TrimMean5%;Median;Std;Var;Skew;Kurt;Min;Max;SE"); } if (lSimulationManager.Runs.Exists((Run r) => r.OutputDisaggregatedData)) { gDisaggregatedCsvFile = TextWriter.Synchronized(new StreamWriter(Path.Combine(ConsoleApp.OutputPath, "Output - Fact YearRegionSectorWeightingscheme.csv"))); if (lSimulationManager.OutputVerbal) { gDisaggregatedCsvFile.Write("Scenario"); gDisaggregatedCsvFile.Write(";"); gDisaggregatedCsvFile.Write("Run"); gDisaggregatedCsvFile.Write(";"); gDisaggregatedCsvFile.Write("Marginal Gas"); gDisaggregatedCsvFile.Write(";"); gDisaggregatedCsvFile.Write("Marginal Emission Year"); gDisaggregatedCsvFile.Write(";"); gDisaggregatedCsvFile.Write("Year"); gDisaggregatedCsvFile.Write(";"); gDisaggregatedCsvFile.Write("Region"); gDisaggregatedCsvFile.Write(";"); gDisaggregatedCsvFile.Write("Sector"); gDisaggregatedCsvFile.Write(";"); gDisaggregatedCsvFile.Write("Weightingscheme"); gDisaggregatedCsvFile.Write(";"); gDisaggregatedCsvFile.Write("Damage"); gDisaggregatedCsvFile.WriteLine(); } } using (var lDimGasCsv = new StreamWriter(Path.Combine(ConsoleApp.OutputPath, "Output - Dim Gas.csv"))) { lDimGasCsv.WriteLine("0;C"); lDimGasCsv.WriteLine("1;CH4"); lDimGasCsv.WriteLine("2;N2O"); lDimGasCsv.WriteLine("3;SF6"); } using (var lDimSectorCsv = new StreamWriter(Path.Combine(ConsoleApp.OutputPath, "Output - Dim Sector.csv"))) { lDimSectorCsv.WriteLine("0;eloss;Water"); lDimSectorCsv.WriteLine("1;eloss;Forests"); lDimSectorCsv.WriteLine("2;eloss;Heating"); lDimSectorCsv.WriteLine("3;eloss;Cooling"); lDimSectorCsv.WriteLine("4;eloss;Agriculture"); lDimSectorCsv.WriteLine("5;eloss;Dryland"); lDimSectorCsv.WriteLine("6;eloss;SeaProtection"); lDimSectorCsv.WriteLine("7;eloss;Imigration"); lDimSectorCsv.WriteLine("8;sloss;Species"); lDimSectorCsv.WriteLine("9;sloss;Death"); lDimSectorCsv.WriteLine("10;sloss;Morbidity"); lDimSectorCsv.WriteLine("11;sloss;Wetland"); lDimSectorCsv.WriteLine("12;sloss;Emigration"); lDimSectorCsv.WriteLine("13;eloss;Hurricane"); lDimSectorCsv.WriteLine("14;eloss;ExtratropicalStorms"); } using (var lDimScenarioCsv = new StreamWriter(Path.Combine(ConsoleApp.OutputPath, "Output - Dim Scenario.csv"))) { foreach (Scenario lScenario in lSimulationManager.Scenarios) { // Write Scenario dimension file lDimScenarioCsv.Write(lScenario.Id); lDimScenarioCsv.Write(";"); lDimScenarioCsv.Write(lScenario.Name); lDimScenarioCsv.WriteLine(); } } using (var lDimYearCsv = new StreamWriter(Path.Combine(ConsoleApp.OutputPath, "Output - Dim Year.csv"))) { for (int i = 1950; i <= 2300; i++) { string lYearStr = i.ToString(); lDimYearCsv.Write(lYearStr); lDimYearCsv.Write(";"); lDimYearCsv.Write(lYearStr.Substring(0, 2)); lDimYearCsv.Write("xx;"); lDimYearCsv.Write(lYearStr.Substring(0, 3)); lDimYearCsv.Write("x;"); lDimYearCsv.Write(lYearStr.Substring(0, 4)); lDimYearCsv.WriteLine(); } } var lDimEmissionYear = new ConcurrentBag<Timestep>(); if (lSimulationManager.OutputInputParameters) { lGlobalInputCsv = TextWriter.Synchronized(new StreamWriter(Path.Combine(ConsoleApp.OutputPath, "Output - Fact Parameter.csv"))); lRegionInputCsv = TextWriter.Synchronized(new StreamWriter(Path.Combine(ConsoleApp.OutputPath, "Output - Fact ParameterRegion.csv"))); lYearInputCsv = TextWriter.Synchronized(new StreamWriter(Path.Combine(ConsoleApp.OutputPath, "Output - Fact ParameterYear.csv"))); lRegionYearInputCsv = TextWriter.Synchronized(new StreamWriter(Path.Combine(ConsoleApp.OutputPath, "Output - Fact ParameterYearRegion.csv"))); } if (lSimulationManager.RunParallel && !lSimulationManager.SameRandomStreamPerRun) { throw new ArgumentException("Cannot run in parallel but without random stream per run"); } var parallelOptions = new System.Threading.Tasks.ParallelOptions() { MaxDegreeOfParallelism = lSimulationManager.RunParallel ? -1 : 1 }; if (lSimulationManager.RunParallel) { var parameterDefinition = new Parameters(); parameterDefinition.ReadExcelFile(@"Data\Parameter - base.xlsm"); // Create a new model that inits itself from the parameters just loaded var model = new Esmf.Model.ModelTyped<FundWorkflow>(); model.Run(parameterDefinition.GetBestGuess()); } System.Threading.Tasks.Parallel.ForEach<Run, object>( lSimulationManager.Runs, parallelOptions, () => { Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; Thread.CurrentThread.Priority = ThreadPriority.BelowNormal; return null; }, (lRun, loopState, dummy) => { var tlRandom = lSimulationManager.SameRandomStreamPerRun ? GetNewRandom(lSimulationManager) : lRandom; var lParam = new Parameters(); foreach (string filename in lRun.Scenario.ExcelFiles) lParam.ReadExcelFile(filename); Console.WriteLine(lRun.Scenario.Name); if (lRun.Mode == RunMode.MarginalRun) { var lMarginalRun = new TMarginalRun(lRun, lRun.MarginalGas, lRun.EmissionYear, ConsoleApp.OutputPath, lParam, lRandom); lDimEmissionYear.Add(lRun.EmissionYear); lMarginalRun.AggregateDamageCsv = lAggregateMarginalDamage; lMarginalRun.SummaryCsv = lSummaryDamage; if (lRun.OutputDisaggregatedData) { lMarginalRun.YearRegionSectorWeightingSchemeCsv = gDisaggregatedCsvFile; } if (lSimulationManager.OutputInputParameters) { lMarginalRun.GlobalInputCsv = lGlobalInputCsv; lMarginalRun.RegionInputCsv = lRegionInputCsv; lMarginalRun.YearInputCsv = lYearInputCsv; lMarginalRun.RegionYearInputCsv = lRegionYearInputCsv; } var watch = new System.Diagnostics.Stopwatch(); watch.Start(); lMarginalRun.Run(); watch.Stop(); //Console.WriteLine("Elapsed time: {0}", watch.Elapsed); } else if (lRun.Mode == RunMode.FullMarginalRun) { MarginalGas[] gases = { MarginalGas.C }; foreach (MarginalGas gas in gases) { for (int emissionyear = 2010; emissionyear <= 2100; emissionyear += 5) { lDimEmissionYear.Add(Timestep.FromYear(emissionyear)); Console.WriteLine("Now doing year {0} and gas {1}", emissionyear, gas); // DA: Use MargMain for marginal cost, use Main for total cost and optimisation // modes var lMarginalRun = new TMarginalRun(lRun, gas, Timestep.FromYear(emissionyear), ConsoleApp.OutputPath, lParam, lRandom); lMarginalRun.AggregateDamageCsv = lAggregateMarginalDamage; if (lRun.OutputDisaggregatedData) { lMarginalRun.YearRegionSectorWeightingSchemeCsv = gDisaggregatedCsvFile; } if (lSimulationManager.OutputInputParameters) { lMarginalRun.GlobalInputCsv = lGlobalInputCsv; lMarginalRun.RegionInputCsv = lRegionInputCsv; lMarginalRun.YearInputCsv = lYearInputCsv; lMarginalRun.RegionYearInputCsv = lRegionYearInputCsv; } var watch = new System.Diagnostics.Stopwatch(); watch.Start(); lMarginalRun.Run(); watch.Stop(); //Console.WriteLine("Elapsed time: {0}", watch.Elapsed); } } } else if (lRun.Mode == RunMode.TotalRun) { // DA: Use MargMain for marginal cost, use Main for total cost and optimisation // modes var lTotalDamageRun = new TotalDamage(lRun, ConsoleApp.OutputPath, lParam, lRun.EmissionYear); lTotalDamageRun.AggregateDamageCsv = lAggregateMarginalDamage; if (lRun.OutputDisaggregatedData) { lTotalDamageRun.YearRegionSectorWeightingSchemeCsv = gDisaggregatedCsvFile; } if (lSimulationManager.OutputInputParameters) { lTotalDamageRun.GlobalInputCsv = lGlobalInputCsv; lTotalDamageRun.RegionInputCsv = lRegionInputCsv; lTotalDamageRun.YearInputCsv = lYearInputCsv; lTotalDamageRun.RegionYearInputCsv = lRegionYearInputCsv; } lTotalDamageRun.Run(); } return null; }, (dummy) => { return; }); lSummaryDamage.Close(); lAggregateMarginalDamage.Close(); TempOutputFile.Close(); using (var lDimEmissionYearCsv = new StreamWriter(Path.Combine(ConsoleApp.OutputPath, "Output - Dim Emissionyear.csv"))) { foreach (Timestep emissionyear in lDimEmissionYear.Distinct().OrderBy(i => i.Value)) lDimEmissionYearCsv.WriteLine("{0};{1}", emissionyear, emissionyear); } if (lSimulationManager.Runs.Exists((Run run) => run.OutputDisaggregatedData)) { gDisaggregatedCsvFile.Close(); } if (lSimulationManager.OutputInputParameters) { lGlobalInputCsv.Close(); lRegionInputCsv.Close(); lYearInputCsv.Close(); lRegionYearInputCsv.Close(); } }
public void Start() { var run1 = new Esmf.Model.ModelTyped <FundWorkflow>(); var run2 = new Esmf.Model.ModelTyped <FundWorkflow>(); if (!ExpectedUtilityMode) { run1["impactaggregation"].Variables["loss"].StoreOutput = true; run1["socioeconomic"].Variables["income"].StoreOutput = true; run1["socioeconomic"].Variables["populationin1"].StoreOutput = true; run2["impactaggregation"].Variables["loss"].StoreOutput = true; run2["socioeconomic"].Variables["income"].StoreOutput = true; run2["socioeconomic"].Variables["populationin1"].StoreOutput = true; run1["ImpactWaterResources"].Variables["water"].StoreOutput = true; run1["ImpactForests"].Variables["forests"].StoreOutput = true; run1["ImpactHeating"].Variables["heating"].StoreOutput = true; run1["ImpactCooling"].Variables["cooling"].StoreOutput = true; run1["ImpactAgriculture"].Variables["agcost"].StoreOutput = true; run1["ImpactSeaLevelRise"].Variables["drycost"].StoreOutput = true; run1["ImpactSeaLevelRise"].Variables["protcost"].StoreOutput = true; run1["ImpactSeaLevelRise"].Variables["entercost"].StoreOutput = true; run1["ImpactTropicalStorms"].Variables["hurrdam"].StoreOutput = true; run1["ImpactExtratropicalStorms"].Variables["extratropicalstormsdam"].StoreOutput = true; run1["ImpactBioDiversity"].Variables["species"].StoreOutput = true; run1["ImpactDeathMorbidity"].Variables["deadcost"].StoreOutput = true; run1["ImpactDeathMorbidity"].Variables["morbcost"].StoreOutput = true; run1["ImpactSeaLevelRise"].Variables["wetcost"].StoreOutput = true; run1["ImpactSeaLevelRise"].Variables["leavecost"].StoreOutput = true; run2["ImpactWaterResources"].Variables["water"].StoreOutput = true; run2["ImpactForests"].Variables["forests"].StoreOutput = true; run2["ImpactHeating"].Variables["heating"].StoreOutput = true; run2["ImpactCooling"].Variables["cooling"].StoreOutput = true; run2["ImpactAgriculture"].Variables["agcost"].StoreOutput = true; run2["ImpactSeaLevelRise"].Variables["drycost"].StoreOutput = true; run2["ImpactSeaLevelRise"].Variables["protcost"].StoreOutput = true; run2["ImpactSeaLevelRise"].Variables["entercost"].StoreOutput = true; run2["ImpactTropicalStorms"].Variables["hurrdam"].StoreOutput = true; run2["ImpactExtratropicalStorms"].Variables["extratropicalstormsdam"].StoreOutput = true; run2["ImpactBioDiversity"].Variables["species"].StoreOutput = true; run2["ImpactDeathMorbidity"].Variables["deadcost"].StoreOutput = true; run2["ImpactDeathMorbidity"].Variables["morbcost"].StoreOutput = true; run2["ImpactSeaLevelRise"].Variables["wetcost"].StoreOutput = true; run2["ImpactSeaLevelRise"].Variables["leavecost"].StoreOutput = true; run1["socioeconomic"].Parameters["runwithoutpopulationperturbation"].SetValue(true); run2["socioeconomic"].Parameters["runwithoutpopulationperturbation"].SetValue(true); } if (ExpectedUtilityMode) { for (int i = 0; i < SWFs.Count; i++) { string compName = string.Format("welfare{0}", i); AddWelfareComponents(compName, run1, SWFs[i]); AddWelfareComponents(compName, run2, SWFs[i]); } } run2.AddComponent("marginalemission", typeof(Fund.Components.MarginalEmission.MarginalEmissionComponent), typeof(Fund.Components.MarginalEmission.IMarginalEmissionState), "emissions"); run2["marginalemission"].Parameters["emissionperiod"].SetValue(EmissionYear); switch (Gas) { case MarginalGas.C: run2["marginalemission"].Parameters["emission"].Bind("emissions", "mco2"); run2["climateco2cycle"].Parameters["mco2"].Bind("marginalemission", "modemission"); break; case MarginalGas.CH4: run2["marginalemission"].Parameters["emission"].Bind("emissions", "globch4"); run2["climatech4cycle"].Parameters["globch4"].Bind("marginalemission", "modemission"); break; case MarginalGas.N2O: run2["marginalemission"].Parameters["emission"].Bind("emissions", "globn2o"); run2["climaten2ocycle"].Parameters["globn2o"].Bind("marginalemission", "modemission"); break; case MarginalGas.SF6: run2["marginalemission"].Parameters["emission"].Bind("emissions", "globsf6"); run2["climatesf6cycle"].Parameters["globsf6"].Bind("marginalemission", "modemission"); break; default: throw new NotImplementedException(); } if (AdditionalInitMethod != null) { AdditionalInitMethod(run1); AdditionalInitMethod(run2); } Result1 = run1.Run(Parameters); Result2 = run2.Run(Parameters); SCCs = new List <IDictionary <Region, double> >(SWFs.Count); if (ExpectedUtilityMode) { for (int i = 0; i < SWFs.Count; i++) { var swf = SWFs[i]; string compName = string.Format("welfare{0}", i); var CurrSccs = new Dictionary <Region, double>(); SCCs.Add(CurrSccs); foreach (var r in Result1.Dimensions.GetValues <Region>()) { var sccInUtils = (swf.SWF == WelfareType.Regional || swf.SWF == WelfareType.Tol) ? (Result1[compName, "totalwelfare"][r] - Result2[compName, "totalwelfare"][r]) / 10000000.0 : (Result1[compName, "totalwelfare"] - Result2[compName, "totalwelfare"]) / 10000000.0; double computedScc = (swf.SWF == WelfareType.Global || swf.SWF == WelfareType.Pearce) ? sccInUtils / (1.0 / Math.Pow(GlobalCpCAtBase, swf.Eta)) : sccInUtils / (1.0 / Math.Pow(RegionalCpCAtBase[r.Index], swf.Eta)); CurrSccs.Add(r, computedScc); } if (swf.SWF == WelfareType.Tol) { double computedScc = Result1.Dimensions.GetValues <Region>().Select(r => CurrSccs[r]).Sum(); foreach (var r in Result1.Dimensions.GetValues <Region>()) { CurrSccs[r] = computedScc; } } } } else { using (var mdamage = new DoubleArray(YearsToAggregate, 16)) using (var ypc = new DoubleArray(YearsToAggregate, 16)) using (var gmdamage = new DoubleArray(YearsToAggregate)) using (var gypc = new DoubleArray(YearsToAggregate)) { // Extract results from model for (int t = 0; t < YearsToAggregate; t++) { gmdamage[t] = 0; double gincome = 0; double gpop = 0; foreach (var r in Result1.Dimensions.GetValues <Region>()) { double damage1 = (0.0 - Result1["ImpactWaterResources", "water"][EmissionYear + t, r] - Result1["ImpactForests", "forests"][EmissionYear + t, r] - Result1["ImpactHeating", "heating"][EmissionYear + t, r] - Result1["ImpactCooling", "cooling"][EmissionYear + t, r] - Result1["ImpactAgriculture", "agcost"][EmissionYear + t, r] + Result1["ImpactSeaLevelRise", "drycost"][EmissionYear + t, r] + Result1["ImpactSeaLevelRise", "protcost"][EmissionYear + t, r] + Result1["ImpactSeaLevelRise", "entercost"][EmissionYear + t, r] + Result1["ImpactTropicalStorms", "hurrdam"][EmissionYear + t, r] + Result1["ImpactExtratropicalStorms", "extratropicalstormsdam"][EmissionYear + t, r] + Result1["ImpactBioDiversity", "species"][EmissionYear + t, r] + Result1["ImpactDeathMorbidity", "deadcost"][EmissionYear + t, r] + Result1["ImpactDeathMorbidity", "morbcost"][EmissionYear + t, r] + Result1["ImpactSeaLevelRise", "wetcost"][EmissionYear + t, r] + Result1["ImpactSeaLevelRise", "leavecost"][EmissionYear + t, r]) * 1000000000.0; double damage2 = (0.0 - Result2["ImpactWaterResources", "water"][EmissionYear + t, r] - Result2["ImpactForests", "forests"][EmissionYear + t, r] - Result2["ImpactHeating", "heating"][EmissionYear + t, r] - Result2["ImpactCooling", "cooling"][EmissionYear + t, r] - Result2["ImpactAgriculture", "agcost"][EmissionYear + t, r] + Result2["ImpactSeaLevelRise", "drycost"][EmissionYear + t, r] + Result2["ImpactSeaLevelRise", "protcost"][EmissionYear + t, r] + Result2["ImpactSeaLevelRise", "entercost"][EmissionYear + t, r] + Result2["ImpactTropicalStorms", "hurrdam"][EmissionYear + t, r] + Result2["ImpactExtratropicalStorms", "extratropicalstormsdam"][EmissionYear + t, r] + Result2["ImpactBioDiversity", "species"][EmissionYear + t, r] + Result2["ImpactDeathMorbidity", "deadcost"][EmissionYear + t, r] + Result2["ImpactDeathMorbidity", "morbcost"][EmissionYear + t, r] + Result2["ImpactSeaLevelRise", "wetcost"][EmissionYear + t, r] + Result2["ImpactSeaLevelRise", "leavecost"][EmissionYear + t, r]) * 1000000000.0; double pop = Result1["socioeconomic", "populationin1"][EmissionYear + t, r] * 1000000.0; double income1 = Result1["socioeconomic", "income"][EmissionYear + t, r] * 1000000000.0; double income2 = Result2["socioeconomic", "income"][EmissionYear + t, r] * 1000000000.0; ypc[t, r.Index] = income1 / pop; // Normalize impacts damage2 = income1 * damage2 / income2; // Compute marginal damage mdamage[t, r.Index] = (damage2 - damage1) / 10000000.0; gmdamage[t] = gmdamage[t] + mdamage[t, r.Index]; gincome += income1; gpop += pop; } gypc[t] = gincome / gpop; } for (int i = 0; i < SWFs.Count; i++) { var swf = SWFs[i]; var CurrSccs = new Dictionary <Region, double>(); SCCs.Add(CurrSccs); switch (swf.SWF) { case WelfareType.Global: { double computedScc = 0; for (int t = 0; t < YearsToAggregate; t++) { computedScc += gmdamage[t] * Math.Pow(gypc[0] / gypc[t], swf.Eta) / Math.Pow(1.0 + swf.Prtp, t); } foreach (var r in Result1.Dimensions.GetValues <Region>()) { CurrSccs.Add(r, computedScc); } } break; case WelfareType.Negishi: throw new NotImplementedException(); break; case WelfareType.Pearce: { double baseYpc = gypc[0]; double computedScc = 0; for (int t = 0; t < YearsToAggregate; t++) { foreach (var r in Result1.Dimensions.GetValues <Region>()) { computedScc += mdamage[t, r.Index] * Math.Pow(baseYpc / ypc[t, r.Index], swf.Eta) / Math.Pow(1.0 + swf.Prtp, t); } } foreach (var r in Result1.Dimensions.GetValues <Region>()) { CurrSccs.Add(r, computedScc); } } break; case WelfareType.Regional: { foreach (var r in Result1.Dimensions.GetValues <Region>()) { double computedScc = 0; for (int t = 0; t < YearsToAggregate; t++) { computedScc += mdamage[t, r.Index] * Math.Pow(ypc[0, r.Index] / ypc[t, r.Index], swf.Eta) / Math.Pow(1.0 + swf.Prtp, t); } CurrSccs.Add(r, computedScc); } } break; case WelfareType.Tol: { double computedScc = 0; foreach (var r in Result1.Dimensions.GetValues <Region>()) { for (int t = 0; t < YearsToAggregate; t++) { computedScc += mdamage[t, r.Index] * Math.Pow(ypc[0, r.Index] / ypc[t, r.Index], swf.Eta) / Math.Pow(1.0 + swf.Prtp, t); } } foreach (var r in Result1.Dimensions.GetValues <Region>()) { CurrSccs.Add(r, computedScc); } } break; case WelfareType.Utilitarian: { double computedScc = 0; for (int t = 0; t < YearsToAggregate; t++) { foreach (var r in Result1.Dimensions.GetValues <Region>()) { computedScc += mdamage[t, r.Index] * Math.Pow(1.0 / ypc[t, r.Index], swf.Eta) / Math.Pow(1.0 + swf.Prtp, t); } } foreach (var r in Result1.Dimensions.GetValues <Region>()) { CurrSccs.Add(r, computedScc * Math.Pow(ypc[0, r.Index], swf.Eta)); } } break; default: throw new NotImplementedException(); break; } } } } }
public static Tuple <double, double[]> Compute2010CpC() { var parameterDefinition = new Parameters(); parameterDefinition.ReadExcelFile(@"Data\Parameter - base.xlsm"); var globalCpC = new DoubleArray(monteCarloRuns); var regionalCpC = new DoubleArray(monteCarloRuns, 16); // Run model once to prep for multi tasking var m = new Esmf.Model.ModelTyped <FundWorkflow>(); m["socioeconomic"].Variables["globalconsumption"].StoreOutput = true; m["socioeconomic"].Variables["globalpopulation"].StoreOutput = true; m["socioeconomic"].Variables["consumption"].StoreOutput = true; m["socioeconomic"].Variables["populationin1"].StoreOutput = true; m["socioeconomic"].Parameters["runwithoutpopulationperturbation"].SetValue(true); m["scenariouncertainty"].Parameters["timeofuncertaintystart"].SetValue(Timestep.FromYear(2010)); var tr = m.Run(parameterDefinition.GetBestGuess()); var rdim = tr.Dimensions.GetDimension <Region>(); int currentRun = 0; var t2010 = Timestep.FromYear(2010); var rand = new jp.takel.PseudoRandom.MersenneTwister(); Parallel.ForEach( parameterDefinition.GetRandom(rand, monteCarloRuns), () => { Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; Thread.CurrentThread.Priority = ThreadPriority.BelowNormal; return(0); }, (pv, pls, dummy) => { int tempCurrentCount = Interlocked.Increment(ref currentRun); Console.Write("\rRun {0} ", tempCurrentCount); var res = m.Run(pv); globalCpC[pv.RunId.Value - 1] = res.RootComponent.SocioEconomic.globalconsumption[t2010] / res.RootComponent.SocioEconomic.globalpopulation[t2010]; foreach (var r in rdim.Values) { regionalCpC[pv.RunId.Value - 1, r.Index] = res.RootComponent.SocioEconomic.consumption[t2010, r] / res.RootComponent.SocioEconomic.populationin1[t2010, r]; } return(0); }, (dummy) => { }); Console.WriteLine(); Console.WriteLine(); double gCpCMean = globalCpC.Mean(); double gCpCSD = globalCpC.Std(); var rCpCMean = new DoubleArray(16); var rCpCSD = new DoubleArray(16); for (int i = 0; i < 16; i++) { var rCpC = regionalCpC.GetCol(i); rCpCMean[i] = rCpC.Mean(); rCpCSD[i] = rCpC.Std(); } if (!Directory.Exists("Output")) { Directory.CreateDirectory("Output"); } using (var f = File.CreateText(@"Output\cpc.csv")) { f.WriteLine("Region;E CpC; SD CpC"); f.WriteLine("Global;{0:f2};{1:f2}", gCpCMean, gCpCSD); for (int i = 0; i < 16; i++) { f.WriteLine("{0};{1:f2};{2:f2}", rdim.Names[i], rCpCMean[i], rCpCSD[i]); } } var finalResult = Tuple.Create(gCpCMean, new double[16]); for (int i = 0; i < 16; i++) { finalResult.Item2[i] = rCpCMean[i]; } return(finalResult); }
public static void Run() { int yearsToAggregate = 300; bool expectedUtility = false; double[] prtps = { 0.001, 0.01, 0.03 }; double[] etas = { 1.0, 1.5, 2.0 }; WelfareType[] swfs = { WelfareType.Global, WelfareType.Utilitarian, WelfareType.Regional, WelfareType.Tol, WelfareType.Pearce }; var stopwatch = new Stopwatch(); stopwatch.Start(); Console.WriteLine("Computing base CpC"); var baseCpC = Compute2010CpC(); Console.WriteLine("Doing a run with monteCarloRuns={0}, yearsToAggregate={1}", monteCarloRuns, yearsToAggregate); var runConfigs = (from prtp in prtps from eta in etas from swf in swfs select new RunConfig() { Prtp = prtp, Eta = eta, SWF = swf }).ToArray(); string[] regions = new string[16]; var parameterDefinition = new Parameters(); parameterDefinition.ReadExcelFile(@"Data\Parameter - base.xlsm"); // Run model once to prep for multi tasking { var m = new Esmf.Model.ModelTyped <FundWorkflow>(); m.Run(parameterDefinition.GetBestGuess()); } var relevantKeys = new List <ParameterElementKey>(); foreach (var p in parameterDefinition.GetElements()) { if (p is ParameterElement <double> ) { if (!(p is ParameterElementConstant <double>)) { relevantKeys.Add(p.Key); } } } var yValues = new DoubleArray[runConfigs.Length, 16]; var correlations = new Dictionary <ParameterElementKey, double> [runConfigs.Length, 16]; var regressions = new Dictionary <ParameterElementKey, double> [runConfigs.Length, 16]; var regressionsConfIntervLow = new Dictionary <ParameterElementKey, double> [runConfigs.Length, 16]; var regressionsConfIntervHigh = new Dictionary <ParameterElementKey, double> [runConfigs.Length, 16]; var regressionsFStat = new DoubleArray(runConfigs.Length, 16); var regressionsPVal = new DoubleArray(runConfigs.Length, 16); var regressionsRsq = new DoubleArray(runConfigs.Length, 16); var xValues = new DoubleArray(monteCarloRuns, relevantKeys.Count); var standardizedXValues = new DoubleArray(monteCarloRuns, relevantKeys.Count); var standardizedYValues = new DoubleArray[runConfigs.Length, 16]; for (int i = 0; i < runConfigs.Length; i++) { for (int l = 0; l < 16; l++) { yValues[i, l] = new DoubleArray(monteCarloRuns, 1); standardizedYValues[i, l] = new DoubleArray(monteCarloRuns); correlations[i, l] = new Dictionary <ParameterElementKey, double>(); regressions[i, l] = new Dictionary <ParameterElementKey, double>(); regressionsConfIntervHigh[i, l] = new Dictionary <ParameterElementKey, double>(); regressionsConfIntervLow[i, l] = new Dictionary <ParameterElementKey, double>(); } } var xMeans = new DoubleArray(relevantKeys.Count); var xStd = new DoubleArray(relevantKeys.Count); var rand = new MersenneTwister(); int currentRun = 0; { var m = new MarginalDamage2() { EmissionYear = Timestep.FromYear(2010), Gas = MarginalGas.C, Parameters = parameterDefinition.GetBestGuess(), YearsToAggregate = yearsToAggregate, GlobalCpCAtBase = baseCpC.Item1, ExpectedUtilityMode = expectedUtility, AdditionalInitMethod = (Esmf.Model.Model fw) => { fw["scenariouncertainty"].Parameters["timeofuncertaintystart"].SetValue(Timestep.FromYear(2010)); } }; for (int i = 0; i < 16; i++) { m.RegionalCpCAtBase[i] = baseCpC.Item2[i]; } for (int i = 0; i < runConfigs.Length; i++) { m.SWFs.Add(new WelfareSpec(runConfigs[i].SWF, runConfigs[i].Prtp, runConfigs[i].Eta)); } m.Start(); } Parallel.ForEach( parameterDefinition.GetRandom(rand, monteCarloRuns), () => { Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; Thread.CurrentThread.Priority = ThreadPriority.BelowNormal; return(0); }, (pv, pls, dummy) => { int tempCurrentCount = Interlocked.Increment(ref currentRun); Console.Write("\rRun {0} ", tempCurrentCount); var m = new MarginalDamage2() { EmissionYear = Timestep.FromYear(2010), Gas = MarginalGas.C, Parameters = pv, YearsToAggregate = yearsToAggregate, GlobalCpCAtBase = baseCpC.Item1, ExpectedUtilityMode = false, AdditionalInitMethod = (Esmf.Model.Model fw) => { fw["scenariouncertainty"].Parameters["timeofuncertaintystart"].SetValue(Timestep.FromYear(2010)); } }; for (int i = 0; i < 16; i++) { m.RegionalCpCAtBase[i] = baseCpC.Item2[i]; } for (int i = 0; i < runConfigs.Length; i++) { m.SWFs.Add(new WelfareSpec(runConfigs[i].SWF, runConfigs[i].Prtp, runConfigs[i].Eta)); } m.Start(); var dimensions = m.Result1.Dimensions; for (int i = 0; i < runConfigs.Length; i++) { foreach (var r in dimensions.GetValues <Region>()) { regions[r.Index] = r.ToString(); yValues[i, r.Index][(int)pv.RunId - 1] = m.SCCs[i][r]; } } for (int l = 0; l < relevantKeys.Count; l++) { var p = relevantKeys[l]; double val = ((ParameterValueElement <double>)pv.GetElementByKey(p)).Value; xValues[pv.RunId.Value - 1, l] = val; } return(0); }, (dummy) => { }); Console.WriteLine(); Console.WriteLine(); if (!Directory.Exists("Output")) { Directory.CreateDirectory("Output"); } Console.WriteLine("Write summary"); // Output summary using (var f = File.CreateText(@"Output\summary.csv")) { f.WriteLine("Prtp;Eta;Swf;SccRegion;Mean;Variance;StdDev;StandardError"); for (int i = 0; i < runConfigs.Length; i++) { for (int l = 0; l < 16; l++) { double standardError = yValues[i, l].Std() / Math.Sqrt(monteCarloRuns); f.WriteLine("{0};{1};{2:f3};{3:f3};{4:f3};{5:f3}", runConfigs[i], regions[l], yValues[i, l].Mean(), yValues[i, l].Var(), yValues[i, l].Std(), standardError); } } } Console.WriteLine("Compute correlations"); // Compute correlations for (int k = 0; k < relevantKeys.Count; k++) { var xSlice = xValues.GetCol(k); for (int i = 0; i < runConfigs.Length; i++) { for (int l = 0; l < 16; l++) { // Compute correlation between parameter i and SCC var pearson = new Pearson(yValues[i, l], xSlice); double corr = (double)pearson.Rho; correlations[i, l].Add(relevantKeys[k], corr); } } } Console.WriteLine("Compute regressions"); // Standardize everything for (int k = 0; k < relevantKeys.Count; k++) { var xSlice = xValues.GetCol(k); xMeans[k] = xSlice.Mean(); xStd[k] = xSlice.Std(); } for (int k = 0; k < monteCarloRuns; k++) { for (int i = 0; i < runConfigs.Length; i++) { for (int l = 0; l < 16; l++) { standardizedYValues[i, l][k] = (yValues[i, l][k] - yValues[i, l].Mean()) / yValues[i, l].Std(); } } for (int l = 0; l < relevantKeys.Count; l++) { standardizedXValues[k, l] = (xValues[k, l] - xMeans[l]) / xStd[l]; } } // Compute regression for (int i = 0; i < runConfigs.Length; i++) { for (int l = 0; l < 16; l++) { var regress = new Regress(standardizedYValues[i, l], standardizedXValues, 0.1); regressionsFStat[i, l] = regress.FStat; regressionsPVal[i, l] = regress.PVal; regressionsRsq[i, l] = regress.Rsq; for (int k = 0; k < relevantKeys.Count; k++) { regressions[i, l].Add(relevantKeys[k], regress.Beta[k + 1]); regressionsConfIntervLow[i, l].Add(relevantKeys[k], regress.BetaInt[k + 1, 0]); regressionsConfIntervHigh[i, l].Add(relevantKeys[k], regress.BetaInt[k + 1, 1]); } } } Console.WriteLine("Write regression summary"); // Write regression summaries using (var f = File.CreateText(@"Output\regression summary.csv")) { f.WriteLine("Prtp;Eta;Swf;SccRegion;FStat;PVal;Rsq"); for (int i = 0; i < runConfigs.Length; i++) { for (int l = 0; l < 16; l++) { f.WriteLine("{0};{1};{2:f15};{3:f15};{4:f15}", runConfigs[i], regions[l], regressionsFStat[i, l], regressionsPVal[i, l], regressionsRsq[i, l]); } } } Console.WriteLine("Write correlation"); // Write correlation using (var f = File.CreateText(@"Output\correlation.csv")) { f.WriteLine("Prtp;Eta;Swf;SccRegion;Name;Correlation;RegressCoefficient;RegressConfIntLower;RegressConfIntUpper"); for (int i = 0; i < runConfigs.Length; i++) { for (int l = 0; l < 16; l++) { foreach (var key in relevantKeys) { string s = key.Name; if (key is ParameterElementKey1Dimensional) { s += "-" + regions[((ParameterElementKey1Dimensional)key).D1]; } else if (key is ParameterElementKey2Dimensional) { s += "-" + regions[((ParameterElementKey2Dimensional)key).D1] + "-" + regions[((ParameterElementKey2Dimensional)key).D2]; } f.WriteLine("{0};{1};\"{2}\";{3:f10};{4:f10};{5:f10};{6:f10}", runConfigs[i], regions[l], s, correlations[i, l][key], regressions[i, l][key], regressionsConfIntervLow[i, l][key], regressionsConfIntervHigh[i, l][key]); } } } } Console.WriteLine("Write SCC values"); using (var f = File.CreateText(@"Output\scc values.csv")) { f.WriteLine("Prtp;Eta;Swf;SccRegion;RundId;Scc"); for (int i = 0; i < runConfigs.Length; i++) { for (int l = 0; l < 16; l++) { for (int k = 0; k < monteCarloRuns; k++) { double standardError = yValues[i, l].Std() / Math.Sqrt(monteCarloRuns); f.WriteLine("{0};{1};{2};{3:f14}", runConfigs[i], regions[l], k, yValues[i, l][k]); } } } } stopwatch.Stop(); Console.WriteLine(stopwatch.Elapsed); }
public static void Run(string configurationFileName) { TextWriter gDisaggregatedCsvFile = null; TextWriter lAggregateMarginalDamage = null; TextWriter lGlobalInputCsv = null; TextWriter lRegionInputCsv = null; TextWriter lYearInputCsv = null; TextWriter lRegionYearInputCsv = null; SimulationManager lSimulationManager; var lDefaultConfigurationFile = Path.Combine(Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "Data"), "DefaultSimulation.xml"); lSimulationManager = new SimulationManager(configurationFileName == null ? lDefaultConfigurationFile : configurationFileName); lSimulationManager.Load(); if (!Directory.Exists(ConsoleApp.OutputPath)) { Directory.CreateDirectory(ConsoleApp.OutputPath); } var lRandom = GetNewRandom(lSimulationManager); lAggregateMarginalDamage = TextWriter.Synchronized(new StreamWriter(Path.Combine(ConsoleApp.OutputPath, "Output - Aggregate marginal damage.csv"))); var TempOutputFile = new StreamWriter(Path.Combine(ConsoleApp.OutputPath, "Output - Temp.csv")); if (lSimulationManager.OutputVerbal) { lAggregateMarginalDamage.Write("Scenario"); lAggregateMarginalDamage.Write(";"); lAggregateMarginalDamage.Write("Gas"); lAggregateMarginalDamage.Write(";"); lAggregateMarginalDamage.Write("Emissionyear"); lAggregateMarginalDamage.Write(";"); lAggregateMarginalDamage.Write("Run"); lAggregateMarginalDamage.Write(";"); lAggregateMarginalDamage.Write("Weightingscheme"); lAggregateMarginalDamage.Write(";"); lAggregateMarginalDamage.Write("Marginal damage"); lAggregateMarginalDamage.WriteLine(); } TextWriter lSummaryDamage = TextWriter.Synchronized(new StreamWriter(Path.Combine(ConsoleApp.OutputPath, "Output - Summary damage.csv"))); if (lSimulationManager.OutputVerbal) { lSummaryDamage.WriteLine("Scenario;Gas;Emissionyear;Weightingscheme;Bestguess;Mean;TrimMean0.1%;TrimMean1%;TrimMean5%;Median;Std;Var;Skew;Kurt;Min;Max;SE"); } if (lSimulationManager.Runs.Exists((Run r) => r.OutputDisaggregatedData)) { gDisaggregatedCsvFile = TextWriter.Synchronized(new StreamWriter(Path.Combine(ConsoleApp.OutputPath, "Output - Fact YearRegionSectorWeightingscheme.csv"))); if (lSimulationManager.OutputVerbal) { gDisaggregatedCsvFile.Write("Scenario"); gDisaggregatedCsvFile.Write(";"); gDisaggregatedCsvFile.Write("Run"); gDisaggregatedCsvFile.Write(";"); gDisaggregatedCsvFile.Write("Marginal Gas"); gDisaggregatedCsvFile.Write(";"); gDisaggregatedCsvFile.Write("Marginal Emission Year"); gDisaggregatedCsvFile.Write(";"); gDisaggregatedCsvFile.Write("Year"); gDisaggregatedCsvFile.Write(";"); gDisaggregatedCsvFile.Write("Region"); gDisaggregatedCsvFile.Write(";"); gDisaggregatedCsvFile.Write("Sector"); gDisaggregatedCsvFile.Write(";"); gDisaggregatedCsvFile.Write("Weightingscheme"); gDisaggregatedCsvFile.Write(";"); gDisaggregatedCsvFile.Write("Damage"); gDisaggregatedCsvFile.WriteLine(); } } using (var lDimGasCsv = new StreamWriter(Path.Combine(ConsoleApp.OutputPath, "Output - Dim Gas.csv"))) { lDimGasCsv.WriteLine("0;C"); lDimGasCsv.WriteLine("1;CH4"); lDimGasCsv.WriteLine("2;N2O"); lDimGasCsv.WriteLine("3;SF6"); } using (var lDimSectorCsv = new StreamWriter(Path.Combine(ConsoleApp.OutputPath, "Output - Dim Sector.csv"))) { lDimSectorCsv.WriteLine("0;eloss;Water"); lDimSectorCsv.WriteLine("1;eloss;Forests"); lDimSectorCsv.WriteLine("2;eloss;Heating"); lDimSectorCsv.WriteLine("3;eloss;Cooling"); lDimSectorCsv.WriteLine("4;eloss;Agriculture"); lDimSectorCsv.WriteLine("5;eloss;Dryland"); lDimSectorCsv.WriteLine("6;eloss;SeaProtection"); lDimSectorCsv.WriteLine("7;eloss;Imigration"); lDimSectorCsv.WriteLine("8;sloss;Species"); lDimSectorCsv.WriteLine("9;sloss;Death"); lDimSectorCsv.WriteLine("10;sloss;Morbidity"); lDimSectorCsv.WriteLine("11;sloss;Wetland"); lDimSectorCsv.WriteLine("12;sloss;Emigration"); lDimSectorCsv.WriteLine("13;eloss;Hurricane"); lDimSectorCsv.WriteLine("14;eloss;ExtratropicalStorms"); } using (var lDimScenarioCsv = new StreamWriter(Path.Combine(ConsoleApp.OutputPath, "Output - Dim Scenario.csv"))) { foreach (Scenario lScenario in lSimulationManager.Scenarios) { // Write Scenario dimension file lDimScenarioCsv.Write(lScenario.Id); lDimScenarioCsv.Write(";"); lDimScenarioCsv.Write(lScenario.Name); lDimScenarioCsv.WriteLine(); } } using (var lDimYearCsv = new StreamWriter(Path.Combine(ConsoleApp.OutputPath, "Output - Dim Year.csv"))) { for (int i = 1950; i <= 2300; i++) { string lYearStr = i.ToString(); lDimYearCsv.Write(lYearStr); lDimYearCsv.Write(";"); lDimYearCsv.Write(lYearStr.Substring(0, 2)); lDimYearCsv.Write("xx;"); lDimYearCsv.Write(lYearStr.Substring(0, 3)); lDimYearCsv.Write("x;"); lDimYearCsv.Write(lYearStr.Substring(0, 4)); lDimYearCsv.WriteLine(); } } var lDimEmissionYear = new ConcurrentBag <Timestep>(); if (lSimulationManager.OutputInputParameters) { lGlobalInputCsv = TextWriter.Synchronized(new StreamWriter(Path.Combine(ConsoleApp.OutputPath, "Output - Fact Parameter.csv"))); lRegionInputCsv = TextWriter.Synchronized(new StreamWriter(Path.Combine(ConsoleApp.OutputPath, "Output - Fact ParameterRegion.csv"))); lYearInputCsv = TextWriter.Synchronized(new StreamWriter(Path.Combine(ConsoleApp.OutputPath, "Output - Fact ParameterYear.csv"))); lRegionYearInputCsv = TextWriter.Synchronized(new StreamWriter(Path.Combine(ConsoleApp.OutputPath, "Output - Fact ParameterYearRegion.csv"))); } if (lSimulationManager.RunParallel && !lSimulationManager.SameRandomStreamPerRun) { throw new ArgumentException("Cannot run in parallel but without random stream per run"); } var parallelOptions = new System.Threading.Tasks.ParallelOptions() { MaxDegreeOfParallelism = lSimulationManager.RunParallel ? -1 : 1 }; if (lSimulationManager.RunParallel) { var parameterDefinition = new Parameters(); parameterDefinition.ReadExcelFile(@"Data\Parameter - base.xlsm"); // Create a new model that inits itself from the parameters just loaded var model = new Esmf.Model.ModelTyped <FundWorkflow>(); model.Run(parameterDefinition.GetBestGuess()); } System.Threading.Tasks.Parallel.ForEach <Run, object>( lSimulationManager.Runs, parallelOptions, () => { Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; Thread.CurrentThread.Priority = ThreadPriority.BelowNormal; return(null); }, (lRun, loopState, dummy) => { var tlRandom = lSimulationManager.SameRandomStreamPerRun ? GetNewRandom(lSimulationManager) : lRandom; var lParam = new Parameters(); foreach (string filename in lRun.Scenario.ExcelFiles) { lParam.ReadExcelFile(filename); } Console.WriteLine(lRun.Scenario.Name); if (lRun.Mode == RunMode.MarginalRun) { var lMarginalRun = new TMarginalRun(lRun, lRun.MarginalGas, lRun.EmissionYear, ConsoleApp.OutputPath, lParam, lRandom); lDimEmissionYear.Add(lRun.EmissionYear); lMarginalRun.AggregateDamageCsv = lAggregateMarginalDamage; lMarginalRun.SummaryCsv = lSummaryDamage; if (lRun.OutputDisaggregatedData) { lMarginalRun.YearRegionSectorWeightingSchemeCsv = gDisaggregatedCsvFile; } if (lSimulationManager.OutputInputParameters) { lMarginalRun.GlobalInputCsv = lGlobalInputCsv; lMarginalRun.RegionInputCsv = lRegionInputCsv; lMarginalRun.YearInputCsv = lYearInputCsv; lMarginalRun.RegionYearInputCsv = lRegionYearInputCsv; } var watch = new System.Diagnostics.Stopwatch(); watch.Start(); lMarginalRun.Run(); watch.Stop(); //Console.WriteLine("Elapsed time: {0}", watch.Elapsed); } else if (lRun.Mode == RunMode.FullMarginalRun) { MarginalGas[] gases = { MarginalGas.C }; foreach (MarginalGas gas in gases) { for (int emissionyear = 2010; emissionyear <= 2100; emissionyear += 5) { lDimEmissionYear.Add(Timestep.FromYear(emissionyear)); Console.WriteLine("Now doing year {0} and gas {1}", emissionyear, gas); // DA: Use MargMain for marginal cost, use Main for total cost and optimisation // modes var lMarginalRun = new TMarginalRun(lRun, gas, Timestep.FromYear(emissionyear), ConsoleApp.OutputPath, lParam, lRandom); lMarginalRun.AggregateDamageCsv = lAggregateMarginalDamage; if (lRun.OutputDisaggregatedData) { lMarginalRun.YearRegionSectorWeightingSchemeCsv = gDisaggregatedCsvFile; } if (lSimulationManager.OutputInputParameters) { lMarginalRun.GlobalInputCsv = lGlobalInputCsv; lMarginalRun.RegionInputCsv = lRegionInputCsv; lMarginalRun.YearInputCsv = lYearInputCsv; lMarginalRun.RegionYearInputCsv = lRegionYearInputCsv; } var watch = new System.Diagnostics.Stopwatch(); watch.Start(); lMarginalRun.Run(); watch.Stop(); //Console.WriteLine("Elapsed time: {0}", watch.Elapsed); } } } else if (lRun.Mode == RunMode.TotalRun) { // DA: Use MargMain for marginal cost, use Main for total cost and optimisation // modes var lTotalDamageRun = new TotalDamage(lRun, ConsoleApp.OutputPath, lParam, lRun.EmissionYear); lTotalDamageRun.AggregateDamageCsv = lAggregateMarginalDamage; if (lRun.OutputDisaggregatedData) { lTotalDamageRun.YearRegionSectorWeightingSchemeCsv = gDisaggregatedCsvFile; } if (lSimulationManager.OutputInputParameters) { lTotalDamageRun.GlobalInputCsv = lGlobalInputCsv; lTotalDamageRun.RegionInputCsv = lRegionInputCsv; lTotalDamageRun.YearInputCsv = lYearInputCsv; lTotalDamageRun.RegionYearInputCsv = lRegionYearInputCsv; } lTotalDamageRun.Run(); } return(null); }, (dummy) => { return; }); lSummaryDamage.Close(); lAggregateMarginalDamage.Close(); TempOutputFile.Close(); using (var lDimEmissionYearCsv = new StreamWriter(Path.Combine(ConsoleApp.OutputPath, "Output - Dim Emissionyear.csv"))) { foreach (Timestep emissionyear in lDimEmissionYear.Distinct().OrderBy(i => i.Value)) { lDimEmissionYearCsv.WriteLine("{0};{1}", emissionyear, emissionyear); } } if (lSimulationManager.Runs.Exists((Run run) => run.OutputDisaggregatedData)) { gDisaggregatedCsvFile.Close(); } if (lSimulationManager.OutputInputParameters) { lGlobalInputCsv.Close(); lRegionInputCsv.Close(); lYearInputCsv.Close(); lRegionYearInputCsv.Close(); } }
public double[] DoOneRun(int RunId, WeightingCombination[] i_weightingCombinations, ParameterValues parameters) { ModelOutput i_output2; Damages i_marginalDamages; double i_aggregatedDamage; ModelOutput i_output1; // Create Output object for run 1, set addmp to 0 so that // the extra greenhouse gases are not emitted and then run // the model i_output1 = new ModelOutput(); var f1 = new Esmf.Model.ModelTyped<FundWorkflow>(); f1["ImpactWaterResources"].Variables["water"].StoreOutput = true; f1["ImpactForests"].Variables["forests"].StoreOutput = true; f1["ImpactHeating"].Variables["heating"].StoreOutput = true; f1["ImpactCooling"].Variables["cooling"].StoreOutput = true; f1["ImpactAgriculture"].Variables["agcost"].StoreOutput = true; f1["ImpactSeaLevelRise"].Variables["drycost"].StoreOutput = true; f1["ImpactSeaLevelRise"].Variables["protcost"].StoreOutput = true; f1["ImpactSeaLevelRise"].Variables["entercost"].StoreOutput = true; f1["ImpactTropicalStorms"].Variables["hurrdam"].StoreOutput = true; f1["ImpactExtratropicalStorms"].Variables["extratropicalstormsdam"].StoreOutput = true; f1["ImpactBioDiversity"].Variables["species"].StoreOutput = true; f1["ImpactDeathMorbidity"].Variables["deadcost"].StoreOutput = true; f1["ImpactDeathMorbidity"].Variables["morbcost"].StoreOutput = true; f1["ImpactSeaLevelRise"].Variables["wetcost"].StoreOutput = true; f1["ImpactSeaLevelRise"].Variables["leavecost"].StoreOutput = true; f1["SocioEconomic"].Variables["income"].StoreOutput = true; f1["SocioEconomic"].Variables["population"].StoreOutput = true; if (AdditionalInitCode != null) AdditionalInitCode(f1); var result1 = f1.Run(parameters); i_output1.Load(result1); // Create Output object for run 2, set addmp to 1 so that // the extra greenhouse gases for the marginal run are // emitted and then run the model i_output2 = new ModelOutput(); var f2 = new Esmf.Model.ModelTyped<FundWorkflow>(); f2["ImpactWaterResources"].Variables["water"].StoreOutput = true; f2["ImpactForests"].Variables["forests"].StoreOutput = true; f2["ImpactHeating"].Variables["heating"].StoreOutput = true; f2["ImpactCooling"].Variables["cooling"].StoreOutput = true; f2["ImpactAgriculture"].Variables["agcost"].StoreOutput = true; f2["ImpactSeaLevelRise"].Variables["drycost"].StoreOutput = true; f2["ImpactSeaLevelRise"].Variables["protcost"].StoreOutput = true; f2["ImpactSeaLevelRise"].Variables["entercost"].StoreOutput = true; f2["ImpactTropicalStorms"].Variables["hurrdam"].StoreOutput = true; f2["ImpactExtratropicalStorms"].Variables["extratropicalstormsdam"].StoreOutput = true; f2["ImpactBioDiversity"].Variables["species"].StoreOutput = true; f2["ImpactDeathMorbidity"].Variables["deadcost"].StoreOutput = true; f2["ImpactDeathMorbidity"].Variables["morbcost"].StoreOutput = true; f2["ImpactSeaLevelRise"].Variables["wetcost"].StoreOutput = true; f2["ImpactSeaLevelRise"].Variables["leavecost"].StoreOutput = true; f2["SocioEconomic"].Variables["income"].StoreOutput = true; f2["SocioEconomic"].Variables["population"].StoreOutput = true; if (AdditionalInitCode != null) AdditionalInitCode(f2); f2.AddComponent("marginalemission", typeof(Fund.Components.MarginalEmission.MarginalEmissionComponent), typeof(Fund.Components.MarginalEmission.IMarginalEmissionState), "emissions"); f2["marginalemission"].Parameters["emissionperiod"].SetValue(_emissionyear); switch (_gas) { case MarginalGas.C: f2["marginalemission"].Parameters["emission"].Bind("emissions", "mco2"); f2["climateco2cycle"].Parameters["mco2"].Bind("marginalemission", "modemission"); break; case MarginalGas.CH4: f2["marginalemission"].Parameters["emission"].Bind("emissions", "globch4"); f2["climatech4cycle"].Parameters["globch4"].Bind("marginalemission", "modemission"); break; case MarginalGas.N2O: f2["marginalemission"].Parameters["emission"].Bind("emissions", "globn2o"); f2["climaten2ocycle"].Parameters["globn2o"].Bind("marginalemission", "modemission"); break; case MarginalGas.SF6: f2["marginalemission"].Parameters["emission"].Bind("emissions", "globsf6"); f2["climatesf6cycle"].Parameters["globsf6"].Bind("marginalemission", "modemission"); break; default: throw new NotImplementedException(); } var result2 = f2.Run(parameters); i_output2.Load(result2); Fund28LegacyWeightingCombinations.GetWeightingCombinationsFromName(_run.WeightingCombination, out i_weightingCombinations, _emissionyear); // Take out growth effect effect of run 2 by transforming // the damage from run 2 into % of GDP of run 2, and then // multiplying that with GDP of run 1 for (int year = 1; year < LegacyConstants.NYear; year++) { for (int region = 0; region < LegacyConstants.NoReg; region++) { for (int sector = 0; sector < LegacyConstants.NoSector; sector++) { i_output2.Damages[year, region, (Sector)sector] = (i_output2.Damages[year, region, (Sector)sector] / i_output2.Incomes[year, region]) * i_output1.Incomes[year, region]; } } } // Calculate the marginal damage between run 1 and 2 for each // year/region/sector i_marginalDamages = Damages.CalculateMarginalDamage(i_output1.Damages, i_output2.Damages); double[] i_weightedAggregatedDamages = new double[i_weightingCombinations.Length]; for (int i = 0; i < i_weightingCombinations.Length; i++) { i_weightingCombinations[i].CalculateWeights(i_output1); i_aggregatedDamage = i_weightingCombinations[i].AddDamagesUp(i_marginalDamages, _run.YearsToAggregate, _emissionyear); i_weightedAggregatedDamages[i] = i_aggregatedDamage; WriteAggregateDamage(RunId, i, i_aggregatedDamage, i_weightingCombinations); // Console.Write(i_weightingCombinations[i].Name + ": "); // Console.WriteLine(Convert.ToString(i_aggregatedDamage)); } if (m_YearRegionSectorWeightingSchemeCsv != null) { foreach (var i_Damage in i_marginalDamages) { if ((i_Damage.Year >= _emissionyear.Value) && (i_Damage.Year < _emissionyear.Value + _run.YearsToAggregate)) { for (int k = 0; k < i_weightingCombinations.Length; k++) WriteMarginalDamage(RunId, i_Damage, k, i_weightingCombinations[k][i_Damage.Year, i_Damage.Region], i_weightingCombinations); } } } return i_weightedAggregatedDamages; }
public void DoOneRun(int RunId, WeightingCombination[] i_weightingCombinations, ParameterValues parameters) { double i_aggregatedDamage; ModelOutput i_output1; // Create Output object for run 1, set addmp to 0 so that // the extra greenhouse gases are not emitted and then run // the model i_output1 = new ModelOutput(); var fundWorkflow = new Esmf.Model.ModelTyped<FundWorkflow>(); var result1 = fundWorkflow.Run(parameters); i_output1.Load(result1); for (int i = 0; i < i_weightingCombinations.Length; i++) { i_weightingCombinations[i].CalculateWeights(i_output1); i_aggregatedDamage = i_weightingCombinations[i].AddDamagesUp(i_output1.Damages, _run.YearsToAggregate, _emissionYear); WriteAggregateDamage(RunId, i, i_aggregatedDamage, i_weightingCombinations); } //for (int l = 0; l < i_output1.Damages.Count; l++) //{ // i_Damage = i_output1.Damages[l]; // if ((i_Damage.Year >= _emissionYear.Value) && (i_Damage.Year < _emissionYear.Value + _run.YearsToAggregate)) // { // for (int k = 0; k < i_weightingCombinations.Length; k++) // WriteDamage(RunId, i_Damage, k, i_weightingCombinations[k][i_Damage.Year, i_Damage.Region], i_weightingCombinations); // } //} }
public double[] DoOneRun(int RunId, WeightingCombination[] i_weightingCombinations, ParameterValues parameters) { ModelOutput i_output2; Damages i_marginalDamages; double i_aggregatedDamage; ModelOutput i_output1; // Create Output object for run 1, set addmp to 0 so that // the extra greenhouse gases are not emitted and then run // the model i_output1 = new ModelOutput(); var f1 = new Esmf.Model.ModelTyped <FundWorkflow>(); f1["ImpactWaterResources"].Variables["water"].StoreOutput = true; f1["ImpactForests"].Variables["forests"].StoreOutput = true; f1["ImpactHeating"].Variables["heating"].StoreOutput = true; f1["ImpactCooling"].Variables["cooling"].StoreOutput = true; f1["ImpactAgriculture"].Variables["agcost"].StoreOutput = true; f1["ImpactSeaLevelRise"].Variables["drycost"].StoreOutput = true; f1["ImpactSeaLevelRise"].Variables["protcost"].StoreOutput = true; f1["ImpactSeaLevelRise"].Variables["entercost"].StoreOutput = true; f1["ImpactTropicalStorms"].Variables["hurrdam"].StoreOutput = true; f1["ImpactExtratropicalStorms"].Variables["extratropicalstormsdam"].StoreOutput = true; f1["ImpactBioDiversity"].Variables["species"].StoreOutput = true; f1["ImpactDeathMorbidity"].Variables["deadcost"].StoreOutput = true; f1["ImpactDeathMorbidity"].Variables["morbcost"].StoreOutput = true; f1["ImpactSeaLevelRise"].Variables["wetcost"].StoreOutput = true; f1["ImpactSeaLevelRise"].Variables["leavecost"].StoreOutput = true; f1["SocioEconomic"].Variables["income"].StoreOutput = true; f1["SocioEconomic"].Variables["population"].StoreOutput = true; if (AdditionalInitCode != null) { AdditionalInitCode(f1); } var result1 = f1.Run(parameters); i_output1.Load(result1); // Create Output object for run 2, set addmp to 1 so that // the extra greenhouse gases for the marginal run are // emitted and then run the model i_output2 = new ModelOutput(); var f2 = new Esmf.Model.ModelTyped <FundWorkflow>(); f2["ImpactWaterResources"].Variables["water"].StoreOutput = true; f2["ImpactForests"].Variables["forests"].StoreOutput = true; f2["ImpactHeating"].Variables["heating"].StoreOutput = true; f2["ImpactCooling"].Variables["cooling"].StoreOutput = true; f2["ImpactAgriculture"].Variables["agcost"].StoreOutput = true; f2["ImpactSeaLevelRise"].Variables["drycost"].StoreOutput = true; f2["ImpactSeaLevelRise"].Variables["protcost"].StoreOutput = true; f2["ImpactSeaLevelRise"].Variables["entercost"].StoreOutput = true; f2["ImpactTropicalStorms"].Variables["hurrdam"].StoreOutput = true; f2["ImpactExtratropicalStorms"].Variables["extratropicalstormsdam"].StoreOutput = true; f2["ImpactBioDiversity"].Variables["species"].StoreOutput = true; f2["ImpactDeathMorbidity"].Variables["deadcost"].StoreOutput = true; f2["ImpactDeathMorbidity"].Variables["morbcost"].StoreOutput = true; f2["ImpactSeaLevelRise"].Variables["wetcost"].StoreOutput = true; f2["ImpactSeaLevelRise"].Variables["leavecost"].StoreOutput = true; f2["SocioEconomic"].Variables["income"].StoreOutput = true; f2["SocioEconomic"].Variables["population"].StoreOutput = true; if (AdditionalInitCode != null) { AdditionalInitCode(f2); } f2.AddComponent("marginalemission", typeof(Fund.Components.MarginalEmission.MarginalEmissionComponent), typeof(Fund.Components.MarginalEmission.IMarginalEmissionState), "emissions"); f2["marginalemission"].Parameters["emissionperiod"].SetValue(_emissionyear); switch (_gas) { case MarginalGas.C: f2["marginalemission"].Parameters["emission"].Bind("emissions", "mco2"); f2["climateco2cycle"].Parameters["mco2"].Bind("marginalemission", "modemission"); break; case MarginalGas.CH4: f2["marginalemission"].Parameters["emission"].Bind("emissions", "globch4"); f2["climatech4cycle"].Parameters["globch4"].Bind("marginalemission", "modemission"); break; case MarginalGas.N2O: f2["marginalemission"].Parameters["emission"].Bind("emissions", "globn2o"); f2["climaten2ocycle"].Parameters["globn2o"].Bind("marginalemission", "modemission"); break; case MarginalGas.SF6: f2["marginalemission"].Parameters["emission"].Bind("emissions", "globsf6"); f2["climatesf6cycle"].Parameters["globsf6"].Bind("marginalemission", "modemission"); break; default: throw new NotImplementedException(); } var result2 = f2.Run(parameters); i_output2.Load(result2); Fund28LegacyWeightingCombinations.GetWeightingCombinationsFromName(_run.WeightingCombination, out i_weightingCombinations, _emissionyear); // Take out growth effect effect of run 2 by transforming // the damage from run 2 into % of GDP of run 2, and then // multiplying that with GDP of run 1 for (int year = 1; year < LegacyConstants.NYear; year++) { for (int region = 0; region < LegacyConstants.NoReg; region++) { for (int sector = 0; sector < LegacyConstants.NoSector; sector++) { i_output2.Damages[year, region, (Sector)sector] = (i_output2.Damages[year, region, (Sector)sector] / i_output2.Incomes[year, region]) * i_output1.Incomes[year, region]; } } } // Calculate the marginal damage between run 1 and 2 for each // year/region/sector i_marginalDamages = Damages.CalculateMarginalDamage(i_output1.Damages, i_output2.Damages); double[] i_weightedAggregatedDamages = new double[i_weightingCombinations.Length]; for (int i = 0; i < i_weightingCombinations.Length; i++) { i_weightingCombinations[i].CalculateWeights(i_output1); i_aggregatedDamage = i_weightingCombinations[i].AddDamagesUp(i_marginalDamages, _run.YearsToAggregate, _emissionyear); i_weightedAggregatedDamages[i] = i_aggregatedDamage; WriteAggregateDamage(RunId, i, i_aggregatedDamage, i_weightingCombinations); // Console.Write(i_weightingCombinations[i].Name + ": "); // Console.WriteLine(Convert.ToString(i_aggregatedDamage)); } if (m_YearRegionSectorWeightingSchemeCsv != null) { foreach (var i_Damage in i_marginalDamages) { if ((i_Damage.Year >= _emissionyear.Value) && (i_Damage.Year < _emissionyear.Value + _run.YearsToAggregate)) { for (int k = 0; k < i_weightingCombinations.Length; k++) { WriteMarginalDamage(RunId, i_Damage, k, i_weightingCombinations[k][i_Damage.Year, i_Damage.Region], i_weightingCombinations); } } } } return(i_weightedAggregatedDamages); }