Пример #1
0
        //---------------------------------------------------------------------

        private void WriteSpeciesMaps()
        {
            foreach (ISpecies species in selectedSpecies)
            {
                string path = MakeSpeciesMapName(species.Name);
                PlugIn.ModelCore.UI.WriteLine("   Writing {0} biomass map to {1} ...", species.Name, path);

                using (IOutputRaster <IntPixel> outputRaster = modelCore.CreateRaster <IntPixel>(path, modelCore.Landscape.Dimensions))
                {
                    IntPixel pixel = outputRaster.BufferPixel;
                    foreach (Site site in PlugIn.ModelCore.Landscape.AllSites)
                    {
                        if (site.IsActive)
                        {
                            pixel.MapCode.Value = (int)Math.Round((double)ComputeSpeciesBiomass(SiteVars.Cohorts[site][species]));
                        }
                        else
                        {
                            pixel.MapCode.Value = 0;
                        }

                        outputRaster.WriteBufferPixel();
                    }
                }
            }
        }
        //---------------------------------------------------------------------

        public override void Run()
        {
            //if keyword == maxage
            foreach (ISpecies species in selectedSpecies)
            {
                string path = MapNameTemplates.ReplaceTemplateVars(mapNameTemplate, species.Name, modelCore.CurrentTime);
                modelCore.UI.WriteLine("   Writing maximum age map for {0} to {1} ...", species.Name, path);
                using (IOutputRaster <ShortPixel> outputRaster = modelCore.CreateRaster <ShortPixel>(path, modelCore.Landscape.Dimensions))
                {
                    ShortPixel pixel = outputRaster.BufferPixel;
                    foreach (Site site in modelCore.Landscape.AllSites)
                    {
                        if (site.IsActive)
                        {
                            pixel.MapCode.Value = SiteVars.GetMaxAge(species, (ActiveSite)site);
                        }
                        else
                        {
                            pixel.MapCode.Value = 0;
                        }

                        outputRaster.WriteBufferPixel();
                    }
                }
            }

            WriteMapWithMaxAgeAmongAll();
        }
        //---------------------------------------------------------------------

        /// <summary>
        /// Runs the component for a particular timestep.
        /// </summary>
        /// <param name="currentTime">
        /// The current model timestep.
        /// </param>
        public override void Run()
        {
            foreach (IMapDefinition map in mapDefs)
            {
                List <IForestType> forestTypes = map.ForestTypes;

                string path = MapFileNames.ReplaceTemplateVars(mapNameTemplate, map.Name, modelCore.CurrentTime);
                modelCore.UI.WriteLine("   Writing Biomass Reclass map to {0} ...", path);
                using (IOutputRaster <BytePixel> outputRaster = modelCore.CreateRaster <BytePixel>(path, modelCore.Landscape.Dimensions))
                {
                    BytePixel pixel = outputRaster.BufferPixel;
                    foreach (Site site in modelCore.Landscape.AllSites)
                    {
                        if (site.IsActive)
                        {
                            pixel.MapCode.Value = CalcForestType(forestTypes, site);
                        }
                        else
                        {
                            pixel.MapCode.Value = 0;
                        }

                        outputRaster.WriteBufferPixel();
                    }
                }
            }
        }
Пример #4
0
        //---------------------------------------------------------------------


        private void CreateCommunityMap()
        {
            string path = MapNames.ReplaceTemplateVars(outputMapName, PlugIn.ModelCore.CurrentTime);

            //PlugIn.ModelCore.UI.WriteLine("   Writing community biomass map to {1} ...", path);
            PlugIn.ModelCore.UI.WriteLine("   Writing community biomass map to {0} ...", path);

            using (IOutputRaster <IntPixel> outputRaster = modelCore.CreateRaster <IntPixel>(path, modelCore.Landscape.Dimensions))
            {
                IntPixel pixel = outputRaster.BufferPixel;
                foreach (Site site in PlugIn.ModelCore.Landscape.AllSites)
                {
                    if (site.IsActive)
                    {
                        pixel.MapCode.Value = SiteVars.MapCode[site];
                    }
                    else
                    {
                        pixel.MapCode.Value = 0;
                    }

                    outputRaster.WriteBufferPixel();
                }
            }
        }
Пример #5
0
        //---------------------------------------------------------------------

        /// <summary>
        /// Writes an output map of prescriptions that harvested each active site.
        /// </summary>
        private void WritePrescriptionMap(int timestep)
        {
            string path = MapNames.ReplaceTemplateVars(nameTemplate, timestep);

            ModelCore.UI.WriteLine("   Writing prescription map to {0} ...", path);
            using (IOutputRaster <ShortPixel> outputRaster = modelCore.CreateRaster <ShortPixel>(path, modelCore.Landscape.Dimensions))
            {
                ShortPixel pixel = outputRaster.BufferPixel;
                foreach (Site site in modelCore.Landscape.AllSites)
                {
                    if (site.IsActive)
                    {
                        Prescription prescription = HarvestMgmtLib.SiteVars.Prescription[site];
                        if (prescription == null)
                        {
                            pixel.MapCode.Value = 1;
                        }
                        else
                        {
                            pixel.MapCode.Value = (short)(prescription.Number + 1);
                        }
                    }
                    else
                    {
                        //  Inactive site
                        pixel.MapCode.Value = 0;
                    }
                    outputRaster.WriteBufferPixel();
                }
            }
        }
        //---------------------------------------------------------------------


        private void WriteSpeciesMaps()
        {
            foreach (ISpecies species in selectedSpecies)
            {
                foreach (AgeClass ageclass in ageClasses[species.Name])
                {
                    string path = MakeSpeciesMapName(species.Name, ageclass.Name);
                    ModelCore.UI.WriteLine("   Writing {0} and {1} map to {2} ...", species.Name, ageclass.Name, path);
                    using (IOutputRaster <IntPixel> outputRaster = modelCore.CreateRaster <IntPixel>(path, modelCore.Landscape.Dimensions))
                    {
                        IntPixel pixel = outputRaster.BufferPixel;
                        foreach (Site site in modelCore.Landscape.AllSites)
                        {
                            if (site.IsActive)
                            {
                                pixel.MapCode.Value = (int)((float)Util.ComputeAgeClassBiomass(site, species, ageclass));
                            }
                            else
                            {
                                pixel.MapCode.Value = 0;
                            }

                            outputRaster.WriteBufferPixel();
                        }
                    }
                }
            }
        }
Пример #7
0
        //---------------------------------------------------------------------

        private IOutputRaster <ClassPixel> CreateMap(string mapname)
        {
            string path = MapFileNames.ReplaceTemplateVars(mapNameTemplate, mapname, modelCore.CurrentTime);

            modelCore.Log.WriteLine("Writing reclass map to {0} ...", path);
            return(modelCore.CreateRaster <ClassPixel>(path,
                                                       modelCore.Landscape.Dimensions,
                                                       modelCore.LandscapeMapMetadata));
        }
Пример #8
0
        //---------------------------------------------------------------------

        ///<summary>
        /// Run the plug-in at a particular timestep.
        ///</summary>
        public override void Run()
        {
            ModelCore.UI.WriteLine("Processing landscape for wind events ...");

            SiteVars.Event.SiteValues          = null;
            SiteVars.Severity.ActiveSiteValues = 0;

            int eventCount = 0;

            foreach (ActiveSite site in PlugIn.ModelCore.Landscape)
            {
                Event windEvent = Event.Initiate(site, Timestep);
                if (windEvent != null)
                {
                    LogEvent(PlugIn.ModelCore.CurrentTime, windEvent);
                    eventCount++;
                    summaryEventCount++;
                }
            }


            //ModelCore.UI.WriteLine("  Wind events: {0}", eventCount);

            //  Write wind severity map
            string     path       = MapNames.ReplaceTemplateVars(mapNameTemplate, PlugIn.modelCore.CurrentTime);
            Dimensions dimensions = new Dimensions(modelCore.Landscape.Rows, modelCore.Landscape.Columns);

            using (IOutputRaster <BytePixel> outputRaster = modelCore.CreateRaster <BytePixel>(path, dimensions))
            {
                BytePixel pixel = outputRaster.BufferPixel;
                foreach (Site site in PlugIn.ModelCore.Landscape.AllSites)
                {
                    if (site.IsActive)
                    {
                        if (SiteVars.Disturbed[site])
                        {
                            pixel.MapCode.Value = (byte)(SiteVars.Severity[site] + 1);
                        }
                        else
                        {
                            pixel.MapCode.Value = 1;
                        }
                    }
                    else
                    {
                        //  Inactive site
                        pixel.MapCode.Value = 0;
                    }
                    outputRaster.WriteBufferPixel();
                }
            }

            WriteSummaryLog(PlugIn.modelCore.CurrentTime);
            summaryTotalSites = 0;
            summaryEventCount = 0;
        }
Пример #9
0
        ///<summary>
        /// Run the plug-in at a particular timestep.
        ///</summary>
        public override void Run()
        {
            PlugIn.ModelCore.UI.WriteLine("   Processing landscape for Fire events ...");

            SiteVars.InitializeDisturbances(Timestep);
            SiteVars.Event.SiteValues           = null;
            SiteVars.Severity.ActiveSiteValues  = 0;
            SiteVars.Disturbed.ActiveSiteValues = false;

            // Update the FireRegions Map as necessary:
            foreach (IDynamicFireRegion dyneco in dynamicEcos)
            {
                if (dyneco.Year == PlugIn.modelCore.CurrentTime)
                {
                    PlugIn.ModelCore.UI.WriteLine("   Reading in new Fire Regions Map {0}.", dyneco.MapName);
                    FireRegions.ReadMap(dyneco.MapName);
                }
            }

            foreach (IFireRegion fireregion in FireRegions.Dataset)
            {
                summaryFireRegionEventCount[fireregion.Index] = 0;
            }

            summaryTotalSites = 0;
            summaryEventCount = 0;

            foreach (ActiveSite site in PlugIn.modelCore.Landscape)
            {
                Event FireEvent = Event.Initiate(site, PlugIn.modelCore.CurrentTime, Timestep);
                if (FireEvent != null)
                {
                    LogEvent(PlugIn.modelCore.CurrentTime, FireEvent);
                    summaryEventCount++;
                }
            }

            //  Write Fire severity map
            string path = MapNames.ReplaceTemplateVars(mapNameTemplate, PlugIn.modelCore.CurrentTime);

            using (IOutputRaster <BytePixel> outputRaster = modelCore.CreateRaster <BytePixel>(path, modelCore.Landscape.Dimensions))
            {
                BytePixel pixel = outputRaster.BufferPixel;
                foreach (Site site in modelCore.Landscape.AllSites)
                {
                    if (site.IsActive)
                    {
                        if (SiteVars.Disturbed[site])
                        {
                            pixel.MapCode.Value = (byte)(SiteVars.Severity[site] + 1);
                        }
                        else
                        {
                            pixel.MapCode.Value = 1;
                        }
                    }
                    else
                    {
                        //  Inactive site
                        pixel.MapCode.Value = 0;
                    }
                    outputRaster.WriteBufferPixel();
                }
            }

            WriteSummaryLog(PlugIn.modelCore.CurrentTime);
        }
Пример #10
0
        //---------------------------------------------------------------------
        ///<summary>
        /// Run the BDA extension at a particular timestep.
        ///</summary>
        public override void Run()
        {
            running = true;
            PlugIn.ModelCore.UI.WriteLine("   Processing landscape for Biomass Insect events ...");

            foreach (IInsect insect in manyInsect)
            {
                //SiteVars.BiomassRemoved.ActiveSiteValues = 0;
                //SiteVars.InitialOutbreakProb.ActiveSiteValues = 0.0;
                insect.BiomassRemoved.ActiveSiteValues = 0;
                //insect.InitialOutbreakProb.ActiveSiteValues = 0.0;

                if (insect.MortalityYear == PlugIn.ModelCore.CurrentTime)
                {
                    Outbreak.Mortality(insect);
                }

                // Copy the data from current to last
                foreach (ActiveSite site in PlugIn.ModelCore.Landscape)
                {
                    insect.LastYearDefoliation[site] = insect.ThisYearDefoliation[site];
                }

                insect.ActiveOutbreak = false;

                PlugIn.ModelCore.NormalDistribution.Mu    = 0.0;
                PlugIn.ModelCore.NormalDistribution.Sigma = 1.0;
                double randomNum = PlugIn.ModelCore.NormalDistribution.NextDouble();

                PlugIn.ModelCore.ExponentialDistribution.Lambda = 1 / (insect.MeanDuration);      // Mean = 1/lambda
                double randomNumE = PlugIn.ModelCore.ExponentialDistribution.NextDouble();

                // First, has enough time passed since the last outbreak?
                double timeBetweenOutbreaks = insect.MeanTimeBetweenOutbreaks + (insect.StdDevTimeBetweenOutbreaks * randomNum);
                double duration             = System.Math.Round(randomNumE + 1);
                double timeAfterDuration    = timeBetweenOutbreaks - duration;

                //PlugIn.ModelCore.UI.WriteLine("Calculated time between = {0}.  inputMeanTime={1}, inputStdTime={2}.", timeBetweenOutbreaks, insect.MeanTimeBetweenOutbreaks, insect.StdDevTimeBetweenOutbreaks);
                //PlugIn.ModelCore.UI.WriteLine("Calculated duration     = {0}.  inputMeanDura={1}, inputStdDura={2}.", duration, insect.MeanDuration, insect.StdDevDuration);
                //PlugIn.ModelCore.UI.WriteLine("Insect Start Time = {0}, Stop Time = {1}.", insect.OutbreakStartYear, insect.OutbreakStopYear);


                if (PlugIn.ModelCore.CurrentTime == 1)
                {
                    PlugIn.ModelCore.UI.WriteLine("   Year 1:  Setting initial start and stop times.");
                    insect.OutbreakStartYear = (int)(timeBetweenOutbreaks / 2.0) + 1;
                    insect.OutbreakStopYear  = insect.OutbreakStartYear + (int)duration - 1;
                    //PlugIn.ModelCore.UI.WriteLine("   {0} is not active.  StartYear={1}, StopYear={2}, CurrentYear={3}.", insect.Name, insect.OutbreakStartYear, insect.OutbreakStopYear, PlugIn.ModelCore.CurrentTime);
                }
                else if (insect.OutbreakStartYear <= PlugIn.ModelCore.CurrentTime &&
                         insect.OutbreakStopYear >= PlugIn.ModelCore.CurrentTime)
                {
                    //PlugIn.ModelCore.UI.WriteLine("   An outbreak starts or continues.  Start and stop time do not change.");
                    insect.ActiveOutbreak = true;
                    //PlugIn.ModelCore.UI.WriteLine("   {0} is active.  StartYear={1}, StopYear={2}, CurrentYear={3}.", insect.Name, insect.OutbreakStartYear, insect.OutbreakStopYear, PlugIn.ModelCore.CurrentTime);

                    insect.MortalityYear = PlugIn.ModelCore.CurrentTime + 1;
                }
                if (insect.OutbreakStopYear <= PlugIn.ModelCore.CurrentTime &&
                    timeAfterDuration > PlugIn.ModelCore.CurrentTime - insect.OutbreakStopYear)
                {
                    //PlugIn.ModelCore.UI.WriteLine("   In between outbreaks, reset start and stop times.");
                    insect.ActiveOutbreak = true;
                    //PlugIn.ModelCore.UI.WriteLine("   {0} is active.  StartYear={1}, StopYear={2}, CurrentYear={3}.", insect.Name, insect.OutbreakStartYear, insect.OutbreakStopYear, PlugIn.ModelCore.CurrentTime);

                    insect.MortalityYear = PlugIn.ModelCore.CurrentTime + 1;
                    //insect.OutbreakStartYear = PlugIn.ModelCore.CurrentTime + (int) timeBetweenOutbreaks;
                    //insect.OutbreakStopYear = insect.OutbreakStartYear + (int) duration;
                }
                //PlugIn.ModelCore.UI.WriteLine("  Insect Start Time = {0}, Stop Time = {1}.", insect.OutbreakStartYear, insect.OutbreakStopYear);

                if (insect.ActiveOutbreak)
                {
                    // PlugIn.ModelCore.UI.WriteLine("   OutbreakStartYear={0}.", insect.OutbreakStartYear);

                    if (insect.OutbreakStartYear == PlugIn.ModelCore.CurrentTime)
                    {
                        // Initialize neighborhoodGrowthReduction with patches
                        Outbreak.InitializeDefoliationPatches(insect);
                    }
                    else
                    {
                        insect.NeighborhoodDefoliation.ActiveSiteValues = 0;
                    }
                }

                // Now report on the previous year's defoliation, that which has been processed
                // through biomass succession.

                double sumDefoliation  = 0.0;
                int    numSites0_33    = 0;
                int    numSites33_66   = 0;
                int    numSites66_100  = 0;
                int    numInitialSites = 0;

                foreach (ActiveSite site in PlugIn.ModelCore.Landscape)
                {
                    sumDefoliation += insect.LastYearDefoliation[site];
                    if (insect.LastYearDefoliation[site] > 0.0 && insect.LastYearDefoliation[site] <= 0.33)
                    {
                        numSites0_33++;
                    }
                    else if (insect.LastYearDefoliation[site] > 0.33 && insect.LastYearDefoliation[site] <= 0.66)
                    {
                        numSites33_66++;
                    }
                    else if (insect.LastYearDefoliation[site] > 0.66 && insect.LastYearDefoliation[site] <= 1.0)
                    {
                        numSites66_100++;
                    }
                    else if (insect.LastYearDefoliation[site] > 1.0)
                    {
                        PlugIn.ModelCore.UI.WriteLine("Defoliation exceeds 1.0");
                    }
                    if (insect.Disturbed[site] && insect.InitialOutbreakProb[site] > 0)
                    {
                        numInitialSites++;
                    }
                }
                if (insect.OutbreakStartYear == PlugIn.ModelCore.CurrentTime)
                {
                    insect.InitialSites = numInitialSites;
                }

                double meanDefoliation = 0.0;
                if (numSites0_33 + numSites33_66 + numSites66_100 > 0)
                {
                    meanDefoliation = sumDefoliation / (double)(numSites0_33 + numSites33_66 + numSites66_100);
                }
                //PlugIn.ModelCore.UI.WriteLine("   sumDefoliation={0}, numSites={1}.", sumDefoliation, numSites0_33 + numSites33_66 + numSites66_100);

                int totalBioRemoved = 0;
                foreach (ActiveSite site in PlugIn.ModelCore.Landscape)
                {
                    //totalBioRemoved += SiteVars.BiomassRemoved[site];
                    totalBioRemoved += insect.BiomassRemoved[site];
                }

                //PlugIn.ModelCore.UI.WriteLine("   totalBioRemoved={0}.", totalBioRemoved);


                // ONly add to log & output maps during outbreak
                if ((insect.ActiveOutbreak && insect.OutbreakStartYear < PlugIn.ModelCore.CurrentTime) || (meanDefoliation > 0) || (insect.LastBioRemoved > 0))
                {
                    if (insect.ActiveOutbreak)
                    {
                        log.Write("{0},{1},{2},{3},{4:0.00},{5},{6},{7},{8},{9}",
                                  PlugIn.ModelCore.CurrentTime - 1, //0
                                  insect.Name,                      //1
                                  insect.OutbreakStartYear,         //2
                                  insect.OutbreakStopYear,          //3
                                  meanDefoliation,                  //4
                                  numSites0_33,                     //5
                                  numSites33_66,                    //6
                                  numSites66_100,                   //7
                                  insect.InitialSites,              //8
                                  insect.LastBioRemoved             //9
                                  );
                    }
                    else
                    {
                        log.Write("{0},{1},{2},{3},{4:0.00},{5},{6},{7},{8},{9}",
                                  PlugIn.ModelCore.CurrentTime - 1, //0
                                  insect.Name,                      //1
                                  insect.LastStartYear,             //2
                                  insect.LastStopYear,              //3
                                  meanDefoliation,                  //4
                                  numSites0_33,                     //5
                                  numSites33_66,                    //6
                                  numSites66_100,                   //7
                                  insect.InitialSites,              //8
                                  insect.LastBioRemoved             //9
                                  );
                    }

                    //foreach (IEcoregion ecoregion in Ecoregions.Dataset)
                    //    log.Write(",{0}", 1);

                    log.WriteLine("");


                    //----- Write Insect GrowthReduction maps --------
                    string path = MapNames.ReplaceTemplateVars(mapNameTemplate, insect.Name, PlugIn.ModelCore.CurrentTime - 1);
                    using (IOutputRaster <ShortPixel> outputRaster = modelCore.CreateRaster <ShortPixel>(path, modelCore.Landscape.Dimensions))
                    {
                        ShortPixel pixel = outputRaster.BufferPixel;

                        foreach (Site site in PlugIn.ModelCore.Landscape.AllSites)
                        {
                            if (site.IsActive)
                            {
                                pixel.MapCode.Value = (short)(insect.LastYearDefoliation[site] * 100.0);
                            }
                            else
                            {
                                //  Inactive site
                                pixel.MapCode.Value = 0;
                            }

                            outputRaster.WriteBufferPixel();
                        }
                    }

                    //----- Write Initial Patch maps --------
                    string path2 = MapNames.ReplaceTemplateVars(mapNameTemplate, ("InitialPatchMap-" + insect.Name), PlugIn.ModelCore.CurrentTime - 1);
                    using (IOutputRaster <ShortPixel> outputRaster = modelCore.CreateRaster <ShortPixel>(path2, modelCore.Landscape.Dimensions))
                    {
                        ShortPixel pixel = outputRaster.BufferPixel;
                        foreach (Site site in PlugIn.ModelCore.Landscape.AllSites)
                        {
                            if (site.IsActive)
                            {
                                if (insect.Disturbed[site])
                                {
                                    pixel.MapCode.Value = (short)(insect.InitialOutbreakProb[site] * 100);
                                }
                                else
                                {
                                    pixel.MapCode.Value = 0;
                                }
                            }
                            else
                            {
                                //  Inactive site
                                pixel.MapCode.Value = 0;
                            }
                            outputRaster.WriteBufferPixel();
                        }
                    }

                    //----- Write Biomass Reduction maps --------
                    string path3 = MapNames.ReplaceTemplateVars(mapNameTemplate, ("BiomassRemoved-" + insect.Name), PlugIn.ModelCore.CurrentTime);
                    using (IOutputRaster <ShortPixel> outputRaster = modelCore.CreateRaster <ShortPixel>(path3, modelCore.Landscape.Dimensions))
                    {
                        ShortPixel pixel = outputRaster.BufferPixel;
                        foreach (Site site in PlugIn.ModelCore.Landscape.AllSites)
                        {
                            if (site.IsActive)
                            {
                                pixel.MapCode.Value = (short)(insect.BiomassRemoved[site] / 100);  // convert to Mg/ha
                            }
                            else
                            {
                                //  Inactive site
                                pixel.MapCode.Value = 0;
                            }
                            outputRaster.WriteBufferPixel();
                        }
                    }
                }

                insect.ThisYearDefoliation.ActiveSiteValues = 0.0;  //reset this year to 0 for all sites
                insect.LastBioRemoved = totalBioRemoved;
                if (insect.OutbreakStopYear <= PlugIn.ModelCore.CurrentTime &&
                    timeAfterDuration > PlugIn.ModelCore.CurrentTime - insect.OutbreakStopYear)
                {
                    insect.LastStartYear     = insect.OutbreakStartYear;
                    insect.LastStopYear      = insect.OutbreakStopYear;
                    insect.OutbreakStartYear = PlugIn.ModelCore.CurrentTime + (int)timeBetweenOutbreaks;
                    insect.OutbreakStopYear  = insect.OutbreakStartYear + (int)duration;
                    //PlugIn.ModelCore.UI.WriteLine("  Insect Start Time = {0}, Stop Time = {1}.", insect.OutbreakStartYear, insect.OutbreakStopYear);
                }
            }
        }
Пример #11
0
        //---------------------------------------------------------------------

        public override void Run()
        {
            //1) Create the output species age stats maps
            foreach (KeyValuePair <string, IEnumerable <ISpecies> > sppAgeStatIter in ageStatSpecies)
            {
                //statIter.Key = statistic name
                //set a function pointer here for the statistic, so we don't have to do the switch operation for every single pixel every single time??
                CohortUtils.SpeciesCohortStatDelegate species_stat_func;

                switch (sppAgeStatIter.Key)
                {
                case "MAX":
                    species_stat_func = new CohortUtils.SpeciesCohortStatDelegate(CohortUtils.GetMaxAge);
                    break;

                case "MIN":
                    species_stat_func = new CohortUtils.SpeciesCohortStatDelegate(CohortUtils.GetMinAge);
                    break;

                case "MED":
                    species_stat_func = new CohortUtils.SpeciesCohortStatDelegate(CohortUtils.GetMedianAge);
                    break;

                case "AVG":
                    species_stat_func = new CohortUtils.SpeciesCohortStatDelegate(CohortUtils.GetAvgAge);
                    break;

                case "SD":
                    species_stat_func = new CohortUtils.SpeciesCohortStatDelegate(CohortUtils.GetStdDevAge);
                    break;

                default:
                    //this shouldn't ever occur
                    System.Console.WriteLine("Unhandled statistic: {0}, using MaxAge Instead", sppAgeStatIter.Key);
                    species_stat_func = new CohortUtils.SpeciesCohortStatDelegate(CohortUtils.GetMaxAge);
                    break;
                }

                foreach (ISpecies species in sppAgeStatIter.Value)
                {
                    string path = SpeciesMapNames.ReplaceTemplateVars(sppagestats_mapNames, species.Name, sppAgeStatIter.Key, modelCore.CurrentTime);
                    ModelCore.UI.WriteLine("   Writing {0} map for {1} to {2} ...", sppAgeStatIter.Key, species.Name, path);
                    using (IOutputRaster <IntPixel> outputRaster = modelCore.CreateRaster <IntPixel>(path, modelCore.Landscape.Dimensions))
                    {
                        IntPixel pixel = outputRaster.BufferPixel;
                        foreach (Site site in modelCore.Landscape.AllSites)
                        {
                            if (!site.IsActive) // and has the spp we want
                            {
                                pixel.MapCode.Value = 0;
                            }
                            else
                            {
                                //need to do a switch on statistic
                                pixel.MapCode.Value = (int)species_stat_func(species, site);
                            }

                            outputRaster.WriteBufferPixel();
                        }
                    }
                }
            }

            //2) Create the output site age stats maps
            foreach (string ageStatIter in siteAgeStats)
            {
                CohortUtils.SiteCohortStatDelegate site_stat_func;
                switch (ageStatIter)
                {
                case "MAX":
                    site_stat_func = new CohortUtils.SiteCohortStatDelegate(CohortUtils.GetMaxAge);
                    break;

                case "MIN":
                    site_stat_func = new CohortUtils.SiteCohortStatDelegate(CohortUtils.GetMinAge);
                    break;

                case "MED":
                    site_stat_func = new CohortUtils.SiteCohortStatDelegate(CohortUtils.GetMedianAge);
                    break;

                case "AVG":
                    site_stat_func = new CohortUtils.SiteCohortStatDelegate(CohortUtils.GetAvgAge);
                    break;

                case "SD":
                    site_stat_func = new CohortUtils.SiteCohortStatDelegate(CohortUtils.GetStdDevAge);
                    break;

                case "COUNT":
                    site_stat_func = new CohortUtils.SiteCohortStatDelegate(CohortUtils.GetCohortCount);
                    break;

                case "RICH":
                    site_stat_func = new CohortUtils.SiteCohortStatDelegate(CohortUtils.GetAgeRichness);
                    break;

                case "EVEN":
                    site_stat_func = new CohortUtils.SiteCohortStatDelegate(CohortUtils.GetAgeEvenness);
                    break;

                default:
                    System.Console.WriteLine("Unhandled statistic: {0}, using MaxAge Instead", ageStatIter);
                    site_stat_func = new CohortUtils.SiteCohortStatDelegate(CohortUtils.GetMaxAge);
                    break;
                }

                string path = SiteMapNames.ReplaceTemplateVars(siteagestats_mapNames, ageStatIter, modelCore.CurrentTime);
                ModelCore.UI.WriteLine("   Writing {0} site map to {1} ...", ageStatIter, path);
                using (IOutputRaster <IntPixel> outputRaster = modelCore.CreateRaster <IntPixel>(path, modelCore.Landscape.Dimensions))
                {
                    IntPixel pixel = outputRaster.BufferPixel;
                    foreach (Site site in modelCore.Landscape.AllSites)
                    {
                        if (!site.IsActive)
                        {
                            pixel.MapCode.Value = 0;
                        }
                        else
                        {
                            pixel.MapCode.Value = (int)site_stat_func(site);
                        }

                        outputRaster.WriteBufferPixel();
                    }
                }
            }

            //3) Create the output site species stats maps
            foreach (string sppStatIter in siteSppStats)
            {
                CohortUtils.SiteCohortStatDelegate site_stat_func;
                switch (sppStatIter)
                {
                case "RICH":
                    //FIXME
                    site_stat_func = new CohortUtils.SiteCohortStatDelegate(CohortUtils.GetSppRichness);
                    break;

                //add in richness
                default:
                    System.Console.WriteLine("Unhandled statistic: {0}, using Species Richness Instead", sppStatIter);
                    site_stat_func = new CohortUtils.SiteCohortStatDelegate(CohortUtils.GetSppRichness);
                    break;
                }

                string path = SiteMapNames.ReplaceTemplateVars(sitesppstats_mapNames, sppStatIter, modelCore.CurrentTime);
                ModelCore.UI.WriteLine("   Writing {0} site map to {1} ...", sppStatIter, path);
                using (IOutputRaster <IntPixel> outputRaster = modelCore.CreateRaster <IntPixel>(path, modelCore.Landscape.Dimensions))
                {
                    IntPixel pixel = outputRaster.BufferPixel;
                    foreach (Site site in modelCore.Landscape.AllSites)
                    {
                        if (!site.IsActive)
                        {
                            pixel.MapCode.Value = 0;
                        }
                        else
                        {
                            pixel.MapCode.Value = (int)site_stat_func(site);
                        }

                        outputRaster.WriteBufferPixel();
                    }
                }
            }
        }
Пример #12
0
        //---------------------------------------------------------------------

        private void WriteMaps(int currentTime)
        {
            string[] paths = { "scrapple-fire", "special-dead-wood-{timestep}.img" };
            //string path = MapNames.ReplaceTemplateVars("scrapple-fire/special-dead-wood-{timestep}.img", currentTime);
            string path = MapNames.ReplaceTemplateVars(Path.Combine(paths), currentTime);

            using (IOutputRaster <IntPixel> outputRaster = modelCore.CreateRaster <IntPixel>(path, modelCore.Landscape.Dimensions))
            {
                IntPixel pixel = outputRaster.BufferPixel;
                foreach (Site site in PlugIn.ModelCore.Landscape.AllSites)
                {
                    if (site.IsActive)
                    {
                        if (SiteVars.Disturbed[site] && SiteVars.Intensity[site] > 0)
                        {
                            pixel.MapCode.Value = (int)(SiteVars.SpecialDeadWood[site]);
                        }
                        else
                        {
                            pixel.MapCode.Value = 0;
                        }
                    }
                    else
                    {
                        //  Inactive site
                        pixel.MapCode.Value = 0;
                    }
                    outputRaster.WriteBufferPixel();
                }
            }
            string[] paths2 = { "scrapple-fire", "ignition-type-{timestep}.img" };
            //path = MapNames.ReplaceTemplateVars("scrapple-fire/ignition-type-{timestep}.img", currentTime);
            path = MapNames.ReplaceTemplateVars(Path.Combine(paths2), currentTime);


            using (IOutputRaster <ShortPixel> outputRaster = modelCore.CreateRaster <ShortPixel>(path, modelCore.Landscape.Dimensions))
            {
                ShortPixel pixel = outputRaster.BufferPixel;
                foreach (Site site in PlugIn.ModelCore.Landscape.AllSites)
                {
                    if (site.IsActive)
                    {
                        if (SiteVars.Disturbed[site] && SiteVars.Intensity[site] > 0)
                        {
                            pixel.MapCode.Value = (short)(SiteVars.TypeOfIginition[site] + 1);
                        }
                        else
                        {
                            pixel.MapCode.Value = 0;
                        }
                    }
                    else
                    {
                        //  Inactive site
                        pixel.MapCode.Value = 0;
                    }
                    outputRaster.WriteBufferPixel();
                }
            }

            string[] paths3 = { "scrapple-fire", "fire-intensity-{timestep}.img" };
            path = MapNames.ReplaceTemplateVars(Path.Combine(paths3), currentTime);
            //path = MapNames.ReplaceTemplateVars("scrapple-fire/fire-intensity-{timestep}.img", currentTime);
            using (IOutputRaster <ShortPixel> outputRaster = modelCore.CreateRaster <ShortPixel>(path, modelCore.Landscape.Dimensions))
            {
                ShortPixel pixel = outputRaster.BufferPixel;
                foreach (Site site in PlugIn.ModelCore.Landscape.AllSites)
                {
                    if (site.IsActive)
                    {
                        if (SiteVars.Disturbed[site] && SiteVars.Intensity[site] > 0)
                        {
                            pixel.MapCode.Value = (short)(SiteVars.Intensity[site]);
                        }
                        else
                        {
                            pixel.MapCode.Value = 0;
                        }
                    }
                    else
                    {
                        //  Inactive site
                        pixel.MapCode.Value = 0;
                    }
                    outputRaster.WriteBufferPixel();
                }
            }

            string[] paths4 = { "scrapple-fire", "fire-spread-probability-{timestep}.img" };
            path = MapNames.ReplaceTemplateVars(Path.Combine(paths4), currentTime);
            //path = MapNames.ReplaceTemplateVars("scrapple-fire/fire-spread-probability-{timestep}.img", currentTime);
            using (IOutputRaster <ShortPixel> outputRaster = modelCore.CreateRaster <ShortPixel>(path, modelCore.Landscape.Dimensions))
            {
                ShortPixel pixel = outputRaster.BufferPixel;
                foreach (Site site in PlugIn.ModelCore.Landscape.AllSites)
                {
                    if (site.IsActive)
                    {
                        if (SiteVars.Disturbed[site] && SiteVars.Intensity[site] > 0)
                        {
                            pixel.MapCode.Value = (short)(SiteVars.SpreadProbability[site] * 100);
                        }
                        else
                        {
                            pixel.MapCode.Value = 0;
                        }
                    }
                    else
                    {
                        //  Inactive site
                        pixel.MapCode.Value = 0;
                    }
                    outputRaster.WriteBufferPixel();
                }
            }

            string[] paths5 = { "scrapple-fire", "day-of-fire-{timestep}.img" };
            path = MapNames.ReplaceTemplateVars(Path.Combine(paths5), currentTime);
            //path = MapNames.ReplaceTemplateVars("scrapple-fire/day-of-fire-{timestep}.img", currentTime);
            using (IOutputRaster <ShortPixel> outputRaster = modelCore.CreateRaster <ShortPixel>(path, modelCore.Landscape.Dimensions))
            {
                ShortPixel pixel = outputRaster.BufferPixel;
                foreach (Site site in PlugIn.ModelCore.Landscape.AllSites)
                {
                    if (site.IsActive)
                    {
                        if (SiteVars.Disturbed[site] && SiteVars.Intensity[site] > 0)
                        {
                            pixel.MapCode.Value = (short)(SiteVars.DayOfFire[site]);
                        }
                        else
                        {
                            pixel.MapCode.Value = 0;
                        }
                    }
                    else
                    {
                        //  Inactive site
                        pixel.MapCode.Value = 0;
                    }
                    outputRaster.WriteBufferPixel();
                }
            }

            string[] paths6 = { "scrapple-fire", "smolder-consumption-{timestep}.img" };
            path = MapNames.ReplaceTemplateVars(Path.Combine(paths6), currentTime);
            //path = MapNames.ReplaceTemplateVars("scrapple-fire/smolder-consumption-{timestep}.img", currentTime);
            using (IOutputRaster <IntPixel> outputRaster = modelCore.CreateRaster <IntPixel>(path, modelCore.Landscape.Dimensions))
            {
                IntPixel pixel = outputRaster.BufferPixel;
                foreach (Site site in PlugIn.ModelCore.Landscape.AllSites)
                {
                    if (site.IsActive)
                    {
                        if (SiteVars.Disturbed[site] && SiteVars.Intensity[site] > 0)
                        {
                            pixel.MapCode.Value = SiteVars.SmolderConsumption[site];
                        }
                        else
                        {
                            pixel.MapCode.Value = 0;
                        }
                    }
                    else
                    {
                        //  Inactive site
                        pixel.MapCode.Value = 0;
                    }
                    outputRaster.WriteBufferPixel();
                }
            }

            string[] paths7 = { "scrapple-fire", "flaming-consumptions-{timestep}.img" };
            path = MapNames.ReplaceTemplateVars(Path.Combine(paths7), currentTime);
            //path = MapNames.ReplaceTemplateVars("scrapple-fire/flaming-consumption-{timestep}.img", currentTime);
            using (IOutputRaster <IntPixel> outputRaster = modelCore.CreateRaster <IntPixel>(path, modelCore.Landscape.Dimensions))
            {
                IntPixel pixel = outputRaster.BufferPixel;
                foreach (Site site in PlugIn.ModelCore.Landscape.AllSites)
                {
                    if (site.IsActive)
                    {
                        if (SiteVars.Disturbed[site] && SiteVars.Intensity[site] > 0)
                        {
                            pixel.MapCode.Value = SiteVars.FlamingConsumption[site];
                        }
                        else
                        {
                            pixel.MapCode.Value = 0;
                        }
                    }
                    else
                    {
                        //  Inactive site
                        pixel.MapCode.Value = 0;
                    }
                    outputRaster.WriteBufferPixel();
                }
            }

            string[] paths8 = { "scrapple-fire", "event-ID-{timestep}.img" };
            path = MapNames.ReplaceTemplateVars(Path.Combine(paths8), currentTime);
            //path = MapNames.ReplaceTemplateVars("scrapple-fire/event-ID-{timestep}.img", currentTime);
            using (IOutputRaster <IntPixel> outputRaster = modelCore.CreateRaster <IntPixel>(path, modelCore.Landscape.Dimensions))
            {
                IntPixel pixel = outputRaster.BufferPixel;
                foreach (Site site in PlugIn.ModelCore.Landscape.AllSites)
                {
                    if (site.IsActive)
                    {
                        if (SiteVars.Disturbed[site] && SiteVars.Intensity[site] > 0)
                        {
                            pixel.MapCode.Value = SiteVars.EventID[site];
                        }
                        else
                        {
                            pixel.MapCode.Value = 0;
                        }
                    }
                    else
                    {
                        //  Inactive site
                        pixel.MapCode.Value = 0;
                    }
                    outputRaster.WriteBufferPixel();
                }
            }
        }
Пример #13
0
        //---------------------------------------------------------------------

        /// <summary>
        /// Runs the component for a particular timestep.
        /// </summary>
        /// <param name="currentTime">
        /// The current model timestep.
        /// </param>
        public override void Run()
        {
            if (SiteVars.TimeOfLastFire == null)
            {
                SiteVars.ReInitialize();
            }

            SiteVars.FuelType.ActiveSiteValues      = 0;
            SiteVars.DecidFuelType.ActiveSiteValues = 0;

            modelCore.UI.WriteLine("  Calculating the Dynamic Fuel Type for all active cells...");
            foreach (ActiveSite site in modelCore.Landscape)
            {
                CalcFuelType(site, fuelTypes, disturbanceTypes);
                SiteVars.PercentDeadFir[site] = CalcPercentDeadFir(site);
            }

            string path = MapNames.ReplaceTemplateVars(mapNameTemplate, modelCore.CurrentTime);

            modelCore.UI.WriteLine("   Writing Fuel map to {0} ...", path);
            using (IOutputRaster <BytePixel> outputRaster = modelCore.CreateRaster <BytePixel>(path, modelCore.Landscape.Dimensions))
            {
                BytePixel pixel = outputRaster.BufferPixel;
                foreach (Site site in modelCore.Landscape.AllSites)
                {
                    if (site.IsActive)
                    {
                        pixel.MapCode.Value = (byte)((int)SiteVars.FuelType[site] + 1);
                    }
                    else
                    {
                        pixel.MapCode.Value = 0;
                    }
                    outputRaster.WriteBufferPixel();
                }
            }

            string conpath = MapNames.ReplaceTemplateVars(pctConiferMapNameTemplate, modelCore.CurrentTime);

            modelCore.UI.WriteLine("   Writing % Conifer map to {0} ...", conpath);
            using (IOutputRaster <BytePixel> outputRaster = modelCore.CreateRaster <BytePixel>(conpath, modelCore.Landscape.Dimensions))
            {
                BytePixel pixel = outputRaster.BufferPixel;
                foreach (Site site in modelCore.Landscape.AllSites)
                {
                    if (site.IsActive)
                    {
                        pixel.MapCode.Value = (byte)((int)SiteVars.PercentConifer[site]);
                    }
                    else
                    {
                        pixel.MapCode.Value = 0;
                    }
                    outputRaster.WriteBufferPixel();
                }
            }
            string firpath = MapNames.ReplaceTemplateVars(pctDeadFirMapNameTemplate, modelCore.CurrentTime);

            modelCore.UI.WriteLine("   Writing % Dead Fir map to {0} ...", firpath);
            using (IOutputRaster <BytePixel> outputRaster = modelCore.CreateRaster <BytePixel>(firpath, modelCore.Landscape.Dimensions))
            {
                BytePixel pixel = outputRaster.BufferPixel;
                foreach (Site site in modelCore.Landscape.AllSites)
                {
                    if (site.IsActive)
                    {
                        pixel.MapCode.Value = (byte)((int)SiteVars.PercentDeadFir[site]);
                    }
                    else
                    {
                        pixel.MapCode.Value = 0;
                    }
                    outputRaster.WriteBufferPixel();
                }
            }
        }
Пример #14
0
        //---------------------------------------------------------------------
        ///<summary>
        /// Run the BDA extension at a particular timestep.
        ///</summary>
        public override void Run()
        {
            PlugIn.ModelCore.UI.WriteLine("   Processing landscape for BDA events ...");
            if (!reinitialized)
            {
                InitializePhase2();
            }

            //SiteVars.Epidemic.SiteValues = null;

            int eventCount = 0;

            foreach (IAgent activeAgent in manyAgentParameters)
            {
                activeAgent.TimeSinceLastEpidemic += Timestep;

                int ROS = RegionalOutbreakStatus(activeAgent, Timestep);

                if (ROS > 0)
                {
                    Epidemic.Initialize(activeAgent);
                    Epidemic currentEpic = Epidemic.Simulate(activeAgent,
                                                             PlugIn.ModelCore.CurrentTime,
                                                             Timestep,
                                                             ROS);
                    //activeAgent.TimeSinceLastEpidemic = activeAgent.TimeSinceLastEpidemic + Timestep;

                    if (currentEpic != null)
                    {
                        LogEvent(PlugIn.ModelCore.CurrentTime, currentEpic, ROS, activeAgent);

                        if (currentEpic.MeanSeverity > 0) //Temporary fix to work with VizTool
                        {
                            //----- Write BDA severity maps --------
                            string path = MapNames.ReplaceTemplateVars(mapNameTemplate, activeAgent.AgentName, PlugIn.ModelCore.CurrentTime);
                            //IOutputRaster<SeverityPixel> map = CreateMap(PlugIn.ModelCore.CurrentTime, activeAgent.AgentName);
                            //using (map) {
                            //    SeverityPixel pixel = new SeverityPixel();
                            using (IOutputRaster <ShortPixel> outputRaster = modelCore.CreateRaster <ShortPixel>(path, modelCore.Landscape.Dimensions))
                            {
                                ShortPixel pixel = outputRaster.BufferPixel;
                                foreach (Site site in PlugIn.ModelCore.Landscape.AllSites)
                                {
                                    if (site.IsActive)
                                    {
                                        if (SiteVars.Disturbed[site])
                                        {
                                            pixel.MapCode.Value = (short)(activeAgent.Severity[site] + 1);
                                        }
                                        else
                                        {
                                            pixel.MapCode.Value = 1;
                                        }
                                    }
                                    else
                                    {
                                        //  Inactive site
                                        pixel.MapCode.Value = 0;
                                    }
                                    outputRaster.WriteBufferPixel();
                                }
                            }
                        }
                        if (!(srdMapNames == null))
                        {
                            //----- Write BDA SRD maps --------
                            string path2 = MapNames.ReplaceTemplateVars(srdMapNames, activeAgent.AgentName, PlugIn.ModelCore.CurrentTime);
                            using (IOutputRaster <ShortPixel> outputRaster = modelCore.CreateRaster <ShortPixel>(path2, modelCore.Landscape.Dimensions))
                            {
                                ShortPixel pixel = outputRaster.BufferPixel;
                                foreach (Site site in PlugIn.ModelCore.Landscape.AllSites)
                                {
                                    if (site.IsActive)
                                    {
                                        pixel.MapCode.Value = (short)System.Math.Round(SiteVars.SiteResourceDom[site] * 100.00);
                                    }
                                    else
                                    {
                                        //  Inactive site
                                        pixel.MapCode.Value = 0;
                                    }
                                    outputRaster.WriteBufferPixel();
                                }
                            }
                        }
                        if (!(nrdMapNames == null))
                        {
                            //----- Write BDA NRD maps --------
                            string path3 = MapNames.ReplaceTemplateVars(nrdMapNames, activeAgent.AgentName, PlugIn.ModelCore.CurrentTime);
                            using (IOutputRaster <ShortPixel> outputRaster = modelCore.CreateRaster <ShortPixel>(path3, modelCore.Landscape.Dimensions))
                            {
                                ShortPixel pixel = outputRaster.BufferPixel;

                                foreach (Site site in PlugIn.ModelCore.Landscape.AllSites)
                                {
                                    if (site.IsActive)
                                    {
                                        pixel.MapCode.Value = (short)System.Math.Round(SiteVars.NeighborResourceDom[site] * 100.00);
                                    }
                                    else
                                    {
                                        //  Inactive site
                                        pixel.MapCode.Value = 0;
                                    }
                                    outputRaster.WriteBufferPixel();
                                }
                            }
                        }
                        if (!(vulnMapNames == null))
                        {
                            //----- Write BDA Vulnerability maps --------
                            string path4 = MapNames.ReplaceTemplateVars(vulnMapNames, activeAgent.AgentName, PlugIn.ModelCore.CurrentTime);
                            using (IOutputRaster <ShortPixel> outputRaster = modelCore.CreateRaster <ShortPixel>(path4, modelCore.Landscape.Dimensions))
                            {
                                ShortPixel pixel = outputRaster.BufferPixel;

                                foreach (Site site in PlugIn.ModelCore.Landscape.AllSites)
                                {
                                    if (site.IsActive)
                                    {
                                        pixel.MapCode.Value = (short)System.Math.Round(SiteVars.Vulnerability[site] * 100.00);
                                    }
                                    else
                                    {
                                        //  Inactive site
                                        pixel.MapCode.Value = 0;
                                    }
                                    outputRaster.WriteBufferPixel();
                                }
                            }
                        }

                        eventCount++;
                    }
                }
            }
        }
Пример #15
0
        //---------------------------------------------------------------------
        ///<summary>
        /// Run the plug-in at a particular timestep.
        ///</summary>
        public override void Run()
        {
            modelCore.UI.WriteLine("   Processing Drought Disturbance ...");

            double totalRemoved = 0;
            int    totalKilled  = 0;
            double dy_sum       = 0;
            int    siteCount    = 0;

            double[] removedSpp      = new double[PlugIn.ModelCore.Species.Count];
            int[]    killedSpp       = new int[PlugIn.ModelCore.Species.Count];
            double[] extraRemovedSpp = new double[PlugIn.ModelCore.Species.Count];
            foreach (ISpecies species in PlugIn.ModelCore.Species)
            {
                removedSpp[species.Index]      = 0;
                killedSpp[species.Index]       = 0;
                extraRemovedSpp[species.Index] = 0;
            }

            foreach (ActiveSite site in PlugIn.ModelCore.Landscape)
            {
                double siteBioRemoved = 0;
                double dy             = SiteVars.DroughtYears[site];
                if (dy > dy_max)
                {
                    dy = dy_max;
                }
                dy_sum    += dy;
                siteCount += 1;
                if (dy > dy_min)
                {
                    // Sort Cohorts be decreasing age
                    List <ICohort> cohortList = new List <ICohort>();
                    foreach (ISpeciesCohorts speciesCohorts in SiteVars.Cohorts[site])
                    {
                        foreach (ICohort cohort in speciesCohorts)
                        {
                            cohortList.Add(cohort);
                        }
                    }
                    cohortList = cohortList.OrderByDescending(x => x.Age).ToList();


                    foreach (ISpecies species in PlugIn.ModelCore.Species)
                    {
                        double bioRemovedSpp      = removedSpp[species.Index];
                        int    cohortKilledSpp    = killedSpp[species.Index];
                        double extraBioRemovedSpp = extraRemovedSpp[species.Index];
                        // Calculate 95% CI of intercept and slope
                        double int_max   = parameters.Drought_Y[species] + (1.96 * parameters.Drought_YSE[species]);
                        double int_min   = parameters.Drought_Y[species] - (1.96 * parameters.Drought_YSE[species]);
                        double slope_max = parameters.Drought_B[species] + (1.96 * parameters.Drought_BSE[species]);
                        double slope_min = parameters.Drought_B[species] - (1.96 * parameters.Drought_BSE[species]);

                        // Calculate upper and lower CI predicted values
                        double maxPropMort   = int_max + slope_max * dy;
                        double minPropMort   = int_min + slope_min * dy;
                        double rangePropMort = maxPropMort - minPropMort;

                        int bioRemoved      = 0;
                        int cohortsKilled   = 0;
                        int extraRemoved    = 0;
                        int woodyRemoved    = 0;
                        int nonWoodyRemoved = 0;

                        if (rangePropMort > 0)
                        {
                            double Tbiomass        = 0;
                            double propLongev      = 0;
                            int    oldestCohortBio = 0;
                            //foreach (ISpeciesCohorts speciesCohorts in SiteVars.Cohorts[site])
                            //{
                            //foreach (ICohort cohort in speciesCohorts)
                            foreach (ICohort cohort in cohortList)
                            {
                                if (cohort.Species == species)
                                {
                                    Tbiomass += cohort.Biomass;
                                    if (((double)cohort.Age / (double)cohort.Species.Longevity) > propLongev)
                                    {
                                        propLongev      = (double)cohort.Age / (double)cohort.Species.Longevity;
                                        oldestCohortBio = cohort.Biomass;
                                    }
                                }
                            }
                            //}
                            if (Tbiomass > 0)
                            {
                                double predictPctMort   = (minPropMort + (rangePropMort * propLongev));
                                double backTransPctMort = predictPctMort;
                                double backTrans0       = 0;
                                if (parameters.BackTransform == "EXP")
                                {
                                    // Back-transform - EXP()
                                    backTransPctMort = Math.Exp(predictPctMort);
                                    if (parameters.IntCorrect == "Y")
                                    {
                                        backTrans0 = Math.Exp(parameters.Drought_Y[species]);
                                    }
                                }
                                else if (parameters.BackTransform == "SQUARE")
                                {
                                    //Back-transform - Square
                                    backTransPctMort = Math.Pow(predictPctMort, 2);
                                    if (parameters.IntCorrect == "Y")
                                    {
                                        backTrans0 = Math.Pow(parameters.Drought_Y[species], 2);
                                    }
                                }
                                // Account for timestep
                                double actualPctMort = (backTransPctMort - backTrans0) * Timestep;
                                //double actualPctMort = predictPctMort * Timestep;
                                actualPctMort = Math.Min(actualPctMort, 100);
                                //Convert to proportion
                                double actualPropMort = actualPctMort / 100.0;

                                // Calculate biomass removed
                                bioRemoved = (int)Math.Round(Tbiomass * actualPropMort);

                                /*
                                 * // Drought kills oldest cohort 50% of time
                                 * if (bioRemoved < oldestCohortBio)
                                 * {
                                 *  int oldBioDiff = oldestCohortBio - bioRemoved;
                                 *  if (PlugIn.ModelCore.GenerateUniform() > 0.5)
                                 *      bioRemoved += oldBioDiff;
                                 *  else
                                 *  {
                                 *      bioRemoved -= oldBioDiff;
                                 *      if (bioRemoved < 0)
                                 *          bioRemoved = 0;
                                 *  }
                                 * }
                                 */

                                int remainBioRem = bioRemoved;

                                //Remove biomass from cohorts, starting with the oldest
                                //foreach (ISpeciesCohorts speciesCohorts in SiteVars.Cohorts[site])
                                //{
                                //foreach (ICohort cohort in speciesCohorts)
                                foreach (ICohort cohort in cohortList)
                                {
                                    if (cohort.Species == species)
                                    {
                                        if (remainBioRem > 0)
                                        {
                                            int nonWoody = cohort.ComputeNonWoodyBiomass(site);
                                            int woody    = (cohort.Biomass - nonWoody);
                                            if (cohort.Biomass > remainBioRem)
                                            {
                                                if ((remainBioRem / cohort.Biomass) > 0.9)
                                                {
                                                    extraRemoved = (cohort.Biomass - remainBioRem);
                                                    remainBioRem = cohort.Biomass;
                                                    cohortsKilled++;
                                                }
                                                else
                                                {
                                                    double nonWoodRatio = (double)nonWoody / (double)woody;
                                                    nonWoody = (int)Math.Round(remainBioRem * nonWoodRatio);
                                                    woody    = remainBioRem - nonWoody;
                                                }

                                                PartialDisturbance.RecordBiomassReduction(cohort, remainBioRem);
                                                remainBioRem     = 0;
                                                woodyRemoved    += woody;
                                                nonWoodyRemoved += nonWoody;
                                            }
                                            else
                                            {
                                                remainBioRem = remainBioRem - cohort.Biomass;
                                                PartialDisturbance.RecordBiomassReduction(cohort, cohort.Biomass);
                                                cohortsKilled++;
                                                woodyRemoved    += woody;
                                                nonWoodyRemoved += nonWoody;
                                            }
                                        }
                                    }
                                }
                            }
                            //}
                        }
                        siteBioRemoved += bioRemoved;
                        bioRemovedSpp  += bioRemoved;
                        Landis.Extension.Succession.Biomass.ForestFloor.AddWoody(woodyRemoved, species, site);
                        Landis.Extension.Succession.Biomass.ForestFloor.AddLitter(nonWoodyRemoved, species, site);
                        cohortKilledSpp               += cohortsKilled;
                        extraBioRemovedSpp            += extraRemoved;
                        removedSpp[species.Index]      = bioRemovedSpp;
                        killedSpp[species.Index]       = cohortKilledSpp;
                        extraRemovedSpp[species.Index] = extraBioRemovedSpp;
                        totalKilled += cohortsKilled;
                    }
                    PartialDisturbance.ReduceCohortBiomass(site);
                }
                SiteVars.DroughtBioRemoved[site] = (ushort)siteBioRemoved;
                totalRemoved += siteBioRemoved;
            }
            double avg_dy = dy_sum / siteCount;

            int i = 0;

            eventLog.Clear();
            EventsLog el = new EventsLog();

            el.Time           = ModelCore.CurrentTime;
            el.AverageDrought = avg_dy;
            el.BiomassRemoved = new double[PlugIn.ModelCore.Species.Count];
            foreach (ISpecies species in PlugIn.ModelCore.Species)
            {
                el.BiomassRemoved[i] = removedSpp[species.Index];
                i = i + 1;
            }
            i = 0;
            el.TotalBiomassRemoved  = totalRemoved;
            el.CohortsKilledSpecies = new int[PlugIn.ModelCore.Species.Count];
            foreach (ISpecies species in PlugIn.ModelCore.Species)
            {
                el.CohortsKilledSpecies[i] = killedSpp[species.Index];
                i = i + 1;
            }
            i = 0;
            el.TotalCohortsKilled = totalKilled;
            el.ExtraRemoved       = new double[PlugIn.ModelCore.Species.Count];
            foreach (ISpecies species in PlugIn.ModelCore.Species)
            {
                el.ExtraRemoved[i] = extraRemovedSpp[species.Index];
                i = i + 1;
            }
            eventLog.AddObject(el);
            eventLog.WriteToFile();

            //  Write Biomass Removed map
            string path = MapNames.ReplaceTemplateVars(mapNameTemplate, modelCore.CurrentTime);

            modelCore.UI.WriteLine("   Writing Drought Biomass Removed map to {0} ...", path);
            using (IOutputRaster <ShortPixel> outputRaster = modelCore.CreateRaster <ShortPixel>(path, modelCore.Landscape.Dimensions))
            {
                ShortPixel pixel = outputRaster.BufferPixel;
                foreach (Site site in modelCore.Landscape.AllSites)
                {
                    if (site.IsActive)
                    {
                        pixel.MapCode.Value = (short)(SiteVars.DroughtBioRemoved[site]);
                    }
                    else
                    {
                        //  Inactive site
                        pixel.MapCode.Value = 0;
                    }
                    outputRaster.WriteBufferPixel();
                }
            }
            // Modify establishment
            if (avg_dy >= dy_min)
            {
                foreach (ISpecies species in PlugIn.ModelCore.Species)
                {
                    double drought_Mod = 1.0;
                    if (parameters.Drought_Sens[species] == 2)
                    {
                        drought_Mod = 0.5;
                    }
                    else if (parameters.Drought_Sens[species] == 3)
                    {
                        drought_Mod = 0.0;
                    }
                    if (drought_Mod < 1)
                    {
                        foreach (IEcoregion ecoregion in PlugIn.ModelCore.Ecoregions)
                        {
                            Landis.Extension.Succession.Biomass.SpeciesData.EstablishModifier[species, ecoregion] *= drought_Mod;
                        }
                    }
                }
            }
            else
            {
                modelCore.UI.WriteLine("   Drought does not exceed threshold this timestep ...");
            }
        }
        //---------------------------------------------------------------------

        public override void Run()
        {
            if (PlugIn.ModelCore.CurrentTime > 0)
            {
                SiteVars.InitializeDisturbances();
            }

            // Update Pest only once.
            SpeciesData.EstablishProbability = Establishment.GenerateNewEstablishProbabilities(Timestep);
            EcoregionData.AnnualNDeposition  = new Ecoregions.AuxParm <double>(PlugIn.ModelCore.Ecoregions);

            base.RunReproductionFirst();


            if (ModelCore.CurrentTime % Timestep == 0)
            {
                // Write monthly log file:
                // Output must reflect the order of operation:
                int[] months = new int[12] {
                    6, 7, 8, 9, 10, 11, 0, 1, 2, 3, 4, 5
                };

                if (OtherData.CalibrateMode)
                {
                    months = new int[12] {
                        6, 7, 8, 9, 10, 11, 0, 1, 2, 3, 4, 5
                    }
                }
                ;

                for (int i = 0; i < 12; i++)
                {
                    int month = months[i];
                    Outputs.WriteMonthlyLogFile(month);
                }
                Outputs.WritePrimaryLogFile(PlugIn.ModelCore.CurrentTime);
                Outputs.WriteShortPrimaryLogFile(PlugIn.ModelCore.CurrentTime);

                string pathH2O = MapNames.ReplaceTemplateVars(@"NECN_Hydro\Annual-water-budget-{timestep}.img", PlugIn.ModelCore.CurrentTime);
                using (IOutputRaster <IntPixel> outputRaster = PlugIn.ModelCore.CreateRaster <IntPixel>(pathH2O, PlugIn.ModelCore.Landscape.Dimensions))
                {
                    IntPixel pixel = outputRaster.BufferPixel;
                    foreach (Site site in PlugIn.ModelCore.Landscape.AllSites)
                    {
                        if (site.IsActive)
                        {
                            pixel.MapCode.Value = (int)((SiteVars.AnnualPPT_AET[site]));
                        }
                        else
                        {
                            //  Inactive site
                            pixel.MapCode.Value = 0;
                        }
                        outputRaster.WriteBufferPixel();
                    }
                }

                if (SoilCarbonMapNames != null)// && (PlugIn.ModelCore.CurrentTime % SoilCarbonMapFrequency) == 0)
                {
                    string path = MapNames.ReplaceTemplateVars(SoilCarbonMapNames, PlugIn.ModelCore.CurrentTime);
                    using (IOutputRaster <IntPixel> outputRaster = modelCore.CreateRaster <IntPixel>(path, modelCore.Landscape.Dimensions))
                    {
                        IntPixel pixel = outputRaster.BufferPixel;
                        foreach (Site site in PlugIn.ModelCore.Landscape.AllSites)
                        {
                            if (site.IsActive)
                            {
                                pixel.MapCode.Value = (int)((SiteVars.SOM1surface[site].Carbon + SiteVars.SOM1soil[site].Carbon + SiteVars.SOM2[site].Carbon + SiteVars.SOM3[site].Carbon));
                            }
                            else
                            {
                                //  Inactive site
                                pixel.MapCode.Value = 0;
                            }
                            outputRaster.WriteBufferPixel();
                        }
                    }
                }

                if (SoilNitrogenMapNames != null)// && (PlugIn.ModelCore.CurrentTime % SoilNitrogenMapFrequency) == 0)
                {
                    string path2 = MapNames.ReplaceTemplateVars(SoilNitrogenMapNames, PlugIn.ModelCore.CurrentTime);
                    using (IOutputRaster <ShortPixel> outputRaster = modelCore.CreateRaster <ShortPixel>(path2, modelCore.Landscape.Dimensions))
                    {
                        ShortPixel pixel = outputRaster.BufferPixel;
                        foreach (Site site in PlugIn.ModelCore.Landscape.AllSites)
                        {
                            if (site.IsActive)
                            {
                                pixel.MapCode.Value = (short)(SiteVars.MineralN[site]);
                            }
                            else
                            {
                                //  Inactive site
                                pixel.MapCode.Value = 0;
                            }
                            outputRaster.WriteBufferPixel();
                        }
                    }
                }

                if (ANPPMapNames != null)// && (PlugIn.ModelCore.CurrentTime % ANPPMapFrequency) == 0)
                {
                    string path3 = MapNames.ReplaceTemplateVars(ANPPMapNames, PlugIn.ModelCore.CurrentTime);
                    using (IOutputRaster <ShortPixel> outputRaster = modelCore.CreateRaster <ShortPixel>(path3, modelCore.Landscape.Dimensions))
                    {
                        ShortPixel pixel = outputRaster.BufferPixel;
                        foreach (Site site in PlugIn.ModelCore.Landscape.AllSites)
                        {
                            if (site.IsActive)
                            {
                                pixel.MapCode.Value = (short)SiteVars.AGNPPcarbon[site];
                            }
                            else
                            {
                                //  Inactive site
                                pixel.MapCode.Value = 0;
                            }
                            outputRaster.WriteBufferPixel();
                        }
                    }
                }
                if (ANEEMapNames != null)// && (PlugIn.ModelCore.CurrentTime % ANEEMapFrequency) == 0)
                {
                    string path4 = MapNames.ReplaceTemplateVars(ANEEMapNames, PlugIn.ModelCore.CurrentTime);
                    using (IOutputRaster <ShortPixel> outputRaster = modelCore.CreateRaster <ShortPixel>(path4, modelCore.Landscape.Dimensions))
                    {
                        ShortPixel pixel = outputRaster.BufferPixel;
                        foreach (Site site in PlugIn.ModelCore.Landscape.AllSites)
                        {
                            if (site.IsActive)
                            {
                                pixel.MapCode.Value = (short)(SiteVars.AnnualNEE[site] + 1000);
                            }
                            else
                            {
                                //  Inactive site
                                pixel.MapCode.Value = 0;
                            }
                            outputRaster.WriteBufferPixel();
                        }
                    }
                }
                if (TotalCMapNames != null)// && (PlugIn.ModelCore.CurrentTime % TotalCMapFrequency) == 0)
                {
                    string path5 = MapNames.ReplaceTemplateVars(TotalCMapNames, PlugIn.ModelCore.CurrentTime);
                    using (IOutputRaster <IntPixel> outputRaster = modelCore.CreateRaster <IntPixel>(path5, modelCore.Landscape.Dimensions))
                    {
                        IntPixel pixel = outputRaster.BufferPixel;
                        foreach (Site site in PlugIn.ModelCore.Landscape.AllSites)
                        {
                            if (site.IsActive)
                            {
                                pixel.MapCode.Value = (int)(Outputs.GetOrganicCarbon(site) +
                                                            SiteVars.CohortLeafC[site] +
                                                            SiteVars.CohortFRootC[site] +
                                                            SiteVars.CohortWoodC[site] +
                                                            SiteVars.CohortCRootC[site] +
                                                            SiteVars.SurfaceDeadWood[site].Carbon +
                                                            SiteVars.SoilDeadWood[site].Carbon);
                            }
                            else
                            {
                                //  Inactive site
                                pixel.MapCode.Value = 0;
                            }
                            outputRaster.WriteBufferPixel();
                        }
                    }
                }
            }
        }
Пример #17
0
        //---------------------------------------------------------------------

        private void WriteMaps(int currentTime)
        {
            string path = MapNames.ReplaceTemplateVars("scrapple-fire/special-dead-wood-{timestep}.img", currentTime);

            using (IOutputRaster <IntPixel> outputRaster = modelCore.CreateRaster <IntPixel>(path, modelCore.Landscape.Dimensions))
            {
                IntPixel pixel = outputRaster.BufferPixel;
                foreach (Site site in PlugIn.ModelCore.Landscape.AllSites)
                {
                    if (site.IsActive)
                    {
                        if (SiteVars.Disturbed[site])
                        {
                            pixel.MapCode.Value = (int)(SiteVars.SpecialDeadWood[site]);
                        }
                        else
                        {
                            pixel.MapCode.Value = 0;
                        }
                    }
                    else
                    {
                        //  Inactive site
                        pixel.MapCode.Value = 0;
                    }
                    outputRaster.WriteBufferPixel();
                }
            }
            path = MapNames.ReplaceTemplateVars("scrapple-fire/ignition-type-{timestep}.img", currentTime);

            using (IOutputRaster <ShortPixel> outputRaster = modelCore.CreateRaster <ShortPixel>(path, modelCore.Landscape.Dimensions))
            {
                ShortPixel pixel = outputRaster.BufferPixel;
                foreach (Site site in PlugIn.ModelCore.Landscape.AllSites)
                {
                    if (site.IsActive)
                    {
                        if (SiteVars.Disturbed[site])
                        {
                            pixel.MapCode.Value = (short)(SiteVars.TypeOfIginition[site] + 1);
                        }
                        else
                        {
                            pixel.MapCode.Value = 0;
                        }
                    }
                    else
                    {
                        //  Inactive site
                        pixel.MapCode.Value = 0;
                    }
                    outputRaster.WriteBufferPixel();
                }
            }

            path = MapNames.ReplaceTemplateVars("scrapple-fire/fire-intensity-{timestep}.img", currentTime);
            using (IOutputRaster <ShortPixel> outputRaster = modelCore.CreateRaster <ShortPixel>(path, modelCore.Landscape.Dimensions))
            {
                ShortPixel pixel = outputRaster.BufferPixel;
                foreach (Site site in PlugIn.ModelCore.Landscape.AllSites)
                {
                    if (site.IsActive)
                    {
                        if (SiteVars.Disturbed[site])
                        {
                            pixel.MapCode.Value = (short)(SiteVars.Intensity[site]);
                        }
                        else
                        {
                            pixel.MapCode.Value = 0;
                        }
                    }
                    else
                    {
                        //  Inactive site
                        pixel.MapCode.Value = 0;
                    }
                    outputRaster.WriteBufferPixel();
                }
            }

            path = MapNames.ReplaceTemplateVars("scrapple-fire/fire-spread-probability-{timestep}.img", currentTime);
            using (IOutputRaster <ShortPixel> outputRaster = modelCore.CreateRaster <ShortPixel>(path, modelCore.Landscape.Dimensions))
            {
                ShortPixel pixel = outputRaster.BufferPixel;
                foreach (Site site in PlugIn.ModelCore.Landscape.AllSites)
                {
                    if (site.IsActive)
                    {
                        if (SiteVars.Disturbed[site])
                        {
                            pixel.MapCode.Value = (short)(SiteVars.SpreadProbability[site] * 100);
                        }
                        else
                        {
                            pixel.MapCode.Value = 0;
                        }
                    }
                    else
                    {
                        //  Inactive site
                        pixel.MapCode.Value = 0;
                    }
                    outputRaster.WriteBufferPixel();
                }
            }

            path = MapNames.ReplaceTemplateVars("scrapple-fire/day-of-fire-{timestep}.img", currentTime);
            using (IOutputRaster <ShortPixel> outputRaster = modelCore.CreateRaster <ShortPixel>(path, modelCore.Landscape.Dimensions))
            {
                ShortPixel pixel = outputRaster.BufferPixel;
                foreach (Site site in PlugIn.ModelCore.Landscape.AllSites)
                {
                    if (site.IsActive)
                    {
                        if (SiteVars.Disturbed[site])
                        {
                            pixel.MapCode.Value = (short)(SiteVars.DayOfFire[site]);
                        }
                        else
                        {
                            pixel.MapCode.Value = 0;
                        }
                    }
                    else
                    {
                        //  Inactive site
                        pixel.MapCode.Value = 0;
                    }
                    outputRaster.WriteBufferPixel();
                }
            }

            path = MapNames.ReplaceTemplateVars("scrapple-fire/smolder-consumption-{timestep}.img", currentTime);
            using (IOutputRaster <IntPixel> outputRaster = modelCore.CreateRaster <IntPixel>(path, modelCore.Landscape.Dimensions))
            {
                IntPixel pixel = outputRaster.BufferPixel;
                foreach (Site site in PlugIn.ModelCore.Landscape.AllSites)
                {
                    if (site.IsActive)
                    {
                        if (SiteVars.Disturbed[site])
                        {
                            pixel.MapCode.Value = SiteVars.SmolderConsumption[site];
                        }
                        else
                        {
                            pixel.MapCode.Value = 0;
                        }
                    }
                    else
                    {
                        //  Inactive site
                        pixel.MapCode.Value = 0;
                    }
                    outputRaster.WriteBufferPixel();
                }
            }

            path = MapNames.ReplaceTemplateVars("scrapple-fire/flaming-consumption-{timestep}.img", currentTime);
            using (IOutputRaster <IntPixel> outputRaster = modelCore.CreateRaster <IntPixel>(path, modelCore.Landscape.Dimensions))
            {
                IntPixel pixel = outputRaster.BufferPixel;
                foreach (Site site in PlugIn.ModelCore.Landscape.AllSites)
                {
                    if (site.IsActive)
                    {
                        if (SiteVars.Disturbed[site])
                        {
                            pixel.MapCode.Value = SiteVars.FlamingConsumption[site];
                        }
                        else
                        {
                            pixel.MapCode.Value = 0;
                        }
                    }
                    else
                    {
                        //  Inactive site
                        pixel.MapCode.Value = 0;
                    }
                    outputRaster.WriteBufferPixel();
                }
            }
        }
Пример #18
0
        //---------------------------------------------------------------------

        ///<summary>
        /// Run the plug-in at a particular timestep.
        ///</summary>
        public override void Run()
        {
            SiteVars.InitializeFuelType();
            modelCore.UI.WriteLine("   Processing landscape for Fire events ...");

            if (FireRegions.Dataset.Count == 0)
            {
                throw new ApplicationException("Fire region data set is empty.");
            }

            SiteVars.Event.SiteValues                       = null;
            SiteVars.Severity.ActiveSiteValues              = 0;
            SiteVars.Disturbed.ActiveSiteValues             = false;
            SiteVars.TravelTime.ActiveSiteValues            = Double.PositiveInfinity;
            SiteVars.MinNeighborTravelTime.ActiveSiteValues = Double.PositiveInfinity;
            SiteVars.RateOfSpread.ActiveSiteValues          = 0.0;

            foreach (IFireRegion fire_region in FireRegions.Dataset)
            {
                summaryFireRegionEventCount[fire_region.Index] = 0;
            }

            summaryTotalSites = 0;
            summaryEventCount = 0;

            // Update the FireRegions Map as necessary:
            //modelCore.UI.WriteLine("    Dynamic Fire:  Loading Dynamic Fire Regions...");
            foreach (IDynamicFireRegion dyneco in dynamicEcos)
            {
                if (dyneco.Year == modelCore.CurrentTime)
                {
                    modelCore.UI.WriteLine("   Reading in new Fire FireRegions Map {0}.", dyneco.MapName);
                    foreach (IFireRegion fire_region in FireRegions.Dataset)
                    {
                        fire_region.FireRegionSites.Clear(); // = new List<Location>();
                    }
                    FireRegions.ReadMap(dyneco.MapName);     //Sites added to their respective fire_region lists
                }
            }

            //Update the weather table as necessary:
            foreach (IDynamicWeather dynweather in dynamicWeather)
            {
                if (dynweather.Year == modelCore.CurrentTime)
                {
                    modelCore.UI.WriteLine("  Reading in new Weather Table {0}", dynweather.FileName);
                    WeatherDataTable = Weather.ReadWeatherFile(dynweather.FileName, FireRegions.Dataset, seasonParameters);
                }
            }

            // Fill in open types as needed:
            modelCore.UI.WriteLine("   Dynamic Fire:  Filling open types as needed ...");
            foreach (ActiveSite site in modelCore.Landscape)
            {
                IFireRegion fire_region = SiteVars.FireRegion[site];

                if (fire_region == null)
                {
                    throw new System.ApplicationException("Error: SiteVars.FireRegion is empty.");
                }

                //if(SiteVars.CFSFuelType[site] == 0)
                //    throw new System.ApplicationException("Error: SiteVars.CFSFuelType is empty.");


                if (Event.FuelTypeParms[SiteVars.CFSFuelType[site]] == null)
                {
                    modelCore.UI.WriteLine("Error:  SiteVars.CFSFuelType[site]={0}.", SiteVars.CFSFuelType[site]);
                    throw new System.ApplicationException("Error: Event BaseFuel Empty.");
                }

                if (Event.FuelTypeParms[SiteVars.CFSFuelType[site]].BaseFuel == BaseFuelType.NoFuel)
                {
                    if (SiteVars.PercentDeadFir[site] == 0)
                    {
                        SiteVars.CFSFuelType[site] = fire_region.OpenFuelType;
                    }
                }
            }
            if (isDebugEnabled)
            {
                modelCore.UI.WriteLine("Done filling open types");
            }

            modelCore.UI.WriteLine("   Dynamic Fire:  Igniting Fires ...");
            foreach (IFireRegion fire_region in FireRegions.Dataset)
            {
                if (isDebugEnabled)
                {
                    modelCore.UI.WriteLine("   There are {0} site locations in fire region {1}", fire_region.FireRegionSites.Count, fire_region.Name);
                }
                if (fire_region.EcoIgnitionNum > 0)
                {
                    //PoissonDistribution randVar = new PoissonDistribution(RandomNumberGenerator.Singleton);
                    double doubleLambda;
                    int    ignGenerated = 0;

                    if (isDebugEnabled)
                    {
                        modelCore.UI.WriteLine("{0}: EcoIgnitionNum = {1}, computing ignGenerated ...", fire_region.Name, fire_region.EcoIgnitionNum);
                    }
                    if (fire_region.EcoIgnitionNum < 1)
                    {
                        // Adjust ignition probability for multiple years
                        // (The inverse of the probability of NOT having any ignition for the time period.)
                        // P = 1 - (1-Pignition)^timestep
                        //doubleLambda = 1 - System.Math.Pow(1.0 - fire_region.EcoIgnitionNum, Timestep);

                        for (int i = 1; i <= Timestep; i++)
                        {
                            int annualFires = 0;
                            if (modelCore.GenerateUniform() <= fire_region.EcoIgnitionNum)
                            {
                                annualFires = 1;
                            }
                            ignGenerated += annualFires;
                        }
                    }
                    else
                    {
                        doubleLambda = fire_region.EcoIgnitionNum;
                        bool boolLarge = false;

                        // 745 is the upper limit for valid Poisson lambdas.  If greater than
                        // 745, divide by 10 and readjust back up below.
                        if (doubleLambda > 745)
                        {
                            doubleLambda = doubleLambda / 10;
                            boolLarge    = true;
                        }
                        PlugIn.ModelCore.PoissonDistribution.Lambda = doubleLambda;
                        //randVar.Lambda = doubleLambda;

                        for (int i = 1; i <= Timestep; i++)
                        {
                            int annualFires = PlugIn.ModelCore.PoissonDistribution.Next();
                            if (boolLarge)
                            {
                                annualFires = annualFires * 10;  //readjust if necessary.
                            }
                            ignGenerated += annualFires;
                        }
                    }
                    if (isDebugEnabled)
                    {
                        modelCore.UI.WriteLine("  Ignitions generated = {0}; Shuffling {0} cells ...", ignGenerated, fire_region.FireRegionSites.Count);
                    }

                    List <Location> cellsPerFireRegion = new List <Location>(0);
                    foreach (Location location in fire_region.FireRegionSites)
                    {
                        cellsPerFireRegion.Add(location);
                    }

                    cellsPerFireRegion = Shuffle(cellsPerFireRegion);
                    int fireCount = 0;

                    //Try to create poissonNumber of fires in each fire_region.
                    //Fires should only initiate if a fire event has not previously occurred
                    //at that site.

                    foreach (Location siteLocation in cellsPerFireRegion)
                    {
                        Site site = modelCore.Landscape.GetSite(siteLocation);

                        ActiveSite asite = (ActiveSite)site;

                        if (fireCount >= ignGenerated)
                        {
                            continue;                             //exit loop if the required number of fires has occurred.
                        }
                        if (SiteVars.Event[asite] == null)
                        {
                            fireCount++;
                            if (isDebugEnabled)
                            {
                                modelCore.UI.WriteLine("    fireCount = {0}", fireCount);
                            }
                            Event FireEvent = Event.Initiate(asite, Timestep, fireSizeType, bui, seasonParameters, severityCalibrate);
                            if (isDebugEnabled)
                            {
                                modelCore.UI.WriteLine("    fire event {0} started at {1}",
                                                       FireEvent == null ? "not ": "",
                                                       asite.Location);
                            }
                            if (FireEvent != null)
                            {
                                LogEvent(modelCore.CurrentTime, FireEvent);
                                summaryEventCount++;
                                //fireCount++;  //RMS test
                            }
                        }
                    }
                }
            }

            // Track the time of last fire; registered in SiteVars.cs for other extensions to access.
            if (isDebugEnabled)
            {
                modelCore.UI.WriteLine("Assigning TimeOfLastFire site var ...");
            }
            foreach (Site site in modelCore.Landscape.AllSites)
            {
                if (SiteVars.Disturbed[site])
                {
                    SiteVars.TimeOfLastFire[site] = modelCore.CurrentTime;
                }
            }


            //  Write Fire severity map
            string path = MapNames.ReplaceTemplateVars(mapNameTemplate, modelCore.CurrentTime);

            modelCore.UI.WriteLine("   Writing Fire severity map to {0} ...", path);
            using (IOutputRaster <BytePixel> outputRaster = modelCore.CreateRaster <BytePixel>(path, modelCore.Landscape.Dimensions))
            {
                BytePixel pixel = outputRaster.BufferPixel;
                foreach (Site site in modelCore.Landscape.AllSites)
                {
                    if (site.IsActive)
                    {
                        if (SiteVars.Disturbed[site])
                        {
                            pixel.MapCode.Value = (byte)(SiteVars.Severity[site] + 2);
                        }
                        else
                        {
                            pixel.MapCode.Value = 1;
                        }
                    }
                    else
                    {
                        //  Inactive site
                        pixel.MapCode.Value = 0;
                    }
                    outputRaster.WriteBufferPixel();
                }
            }

            path = MapNames.ReplaceTemplateVars("./DFFS-output/TimeOfLastFire-{timestep}.img", modelCore.CurrentTime);
            modelCore.UI.WriteLine("   Writing Travel Time output map to {0} ...", path);
            using (IOutputRaster <ShortPixel> outputRaster = modelCore.CreateRaster <ShortPixel>(path, modelCore.Landscape.Dimensions))
            {
                ShortPixel pixel = outputRaster.BufferPixel;
                foreach (Site site in modelCore.Landscape.AllSites)
                {
                    if (site.IsActive)
                    {
                        pixel.MapCode.Value = (short)(SiteVars.TimeOfLastFire[site]);
                    }
                    else
                    {
                        pixel.MapCode.Value = 0;
                    }
                    outputRaster.WriteBufferPixel();
                }
            }

            WriteSummaryLog(modelCore.CurrentTime);

            if (isDebugEnabled)
            {
                modelCore.UI.WriteLine("Done running extension");
            }
        }
Пример #19
0
        //---------------------------------------------------------------------
        ///<summary>
        /// Run Biomass Insects extension at a particular timestep.
        ///</summary>
        public override void Run()
        {
            running = true;
            PlugIn.ModelCore.UI.WriteLine("   Processing landscape for Biomass Insect events ...");

            SiteVars.SiteDefoliation.ActiveSiteValues = 0;

            foreach (IInsect insect in manyInsect)
            {
                //SiteVars.BiomassRemoved.ActiveSiteValues = 0;
                //SiteVars.InitialOutbreakProb.ActiveSiteValues = 0.0;

                if (insect.MortalityYear == PlugIn.ModelCore.CurrentTime)
                {
                    Outbreak.Mortality(insect);
                }

                if (insect.MortalityYear != PlugIn.ModelCore.CurrentTime)
                {
                    insect.LastBioRemoved = 0;
                }

                // Copy the data from current to last
                foreach (ActiveSite site in PlugIn.ModelCore.Landscape)
                {
                    double thisYearDefol = insect.ThisYearDefoliation[site];
                    insect.LastYearDefoliation[site] = thisYearDefol;
                    SiteVars.SiteDefoliation[site]  += (int)Math.Round(thisYearDefol * 100);
                    if (thisYearDefol > 0)
                    {
                        SiteVars.TimeOfLastEvent[site] = PlugIn.ModelCore.CurrentTime - 1;
                        SiteVars.InsectName[site]      = insect.Name;
                    }
                }


                insect.ThisYearDefoliation.ActiveSiteValues = 0.0;

                insect.ActiveOutbreak     = false;
                insect.SingleOutbreakYear = false;

                //PlugIn.ModelCore.NormalDistribution.Mu = 0.0;
                //PlugIn.ModelCore.NormalDistribution.Sigma = 1.0;
                //double randomNum = PlugIn.ModelCore.NormalDistribution.NextDouble();
                //randomNum = PlugIn.ModelCore.NormalDistribution.NextDouble();
                double randomNum = Distribution.GenerateRandomNum(DistributionType.Normal, 0.0, 1.0);

                DistributionType distDuration = insect.DurationDistribution;

                double randomNumE = Distribution.GenerateRandomNum(distDuration, insect.DurationParameter1, insect.DurationParameter2);

                // First, has enough time passed since the last outbreak? This is calculated each year,
                // but only used in last year of an outbreak to generate next outbreak characteristics.
                double timeBetweenOutbreaks = insect.MeanTimeBetweenOutbreaks + (insect.StdDevTimeBetweenOutbreaks * randomNum);
                double duration             = System.Math.Round(randomNumE);
                if (distDuration == DistributionType.Exponential || distDuration == DistributionType.Normal)
                {
                    duration = System.Math.Max(duration + 1, 1); // Duration cannot be less than 1. Added to allow Normal distribution parameters.
                }
                else
                {
                    duration = System.Math.Max(duration, 1);  // Duration cannot be less than 1.
                }

                // Apply optional maximum - if not used maxDur = Inf
                if (duration > insect.MaxDuration)
                {
                    duration = insect.MaxDuration;
                }

                double timeAfterDuration = timeBetweenOutbreaks - duration;

                // Users can parameterize model to have overlapping outbreaks, but then patches will not initialize correctly.
                // Do below to prevent overlapping outbreaks of same insect. This will affect the realized distribution of time between outbreaks somewhat.
                while (timeAfterDuration <= 1.0)
                {
                    PlugIn.ModelCore.UI.WriteLine("CAUTION: Time Between Outbreaks TOO SMALL (< 1), you may need to adjust timing parameters:  {0}.", timeAfterDuration);
                    timeBetweenOutbreaks = timeBetweenOutbreaks + 1;
                    timeAfterDuration    = timeBetweenOutbreaks - duration;
                }

                //PlugIn.ModelCore.UI.WriteLine("Calculated time between = {0:0.00}.  inputMeanTime={1:0.00}, inputStdTime={2:0.00}., timeAftDur={3:0.00}.", timeBetweenOutbreaks, insect.MeanTimeBetweenOutbreaks, insect.StdDevTimeBetweenOutbreaks, timeAfterDuration);

                // The logic below determines whether an outbreak is active. And sets a new outbreak duration and timeBetweenOutbreaks
                // for the next outbreak if is the last year of an outbreak.

                // The very first outbreak is set first.
                if (PlugIn.ModelCore.CurrentTime == 1)
                {
                    PlugIn.ModelCore.UI.WriteLine("   Year 1:  Setting initial start and stop times.");
                    double randomNum1 = PlugIn.ModelCore.GenerateUniform();
                    //insect.OutbreakStartYear = (int) (timeBetweenOutbreaks / 2.0) + 1;
                    insect.OutbreakStartYear = Math.Max(2, (int)(randomNum1 * timeBetweenOutbreaks + 1)); // New, try making 1st start year more random. 1st outbreak has to occur > year1 to for InitializeDefoliationPatches to work properly.
                    insect.OutbreakStartYear = Math.Max(insect.OutbreakStartYear, insect.StartYear);      // BRM - optional start year (first outbreak can't be before StartYear)
                    insect.OutbreakStopYear  = insect.OutbreakStartYear + (int)duration - 1;
                    // PlugIn.ModelCore.UI.WriteLine("   {0} is not active.  StartYear={1}, StopYear={2}, CurrentYear={3}.", insect.Name, insect.OutbreakStartYear, insect.OutbreakStopYear, PlugIn.ModelCore.CurrentTime);
                }
                else if (insect.OutbreakStartYear <= PlugIn.ModelCore.CurrentTime &&
                         insect.OutbreakStopYear > PlugIn.ModelCore.CurrentTime) // first year of a multiyear outbreak
                {
                    // PlugIn.ModelCore.UI.WriteLine("   An outbreak starts or continues.  Start and stop time do not change.");
                    insect.ActiveOutbreak = true;
                    PlugIn.ModelCore.UI.WriteLine("   {0} is active.  StartYear={1}, StopYear={2}, CurrentYear={3}.", insect.Name, insect.OutbreakStartYear, insect.OutbreakStopYear, PlugIn.ModelCore.CurrentTime);

                    insect.MortalityYear = PlugIn.ModelCore.CurrentTime + 1;
                    insect.LastStartYear = insect.OutbreakStartYear; // Added here for Brian's log file.
                    insect.LastStopYear  = insect.OutbreakStopYear;  // Added here for Brian's log file.
                }
                //Special case for single year outbreak.
                else if (insect.OutbreakStartYear == PlugIn.ModelCore.CurrentTime &&
                         insect.OutbreakStopYear == PlugIn.ModelCore.CurrentTime)
                {
                    insect.ActiveOutbreak = true;
                    PlugIn.ModelCore.UI.WriteLine("   {0} is active.  StartYear={1}, StopYear={2}, CurrentYear={3}.", insect.Name, insect.OutbreakStartYear, insect.OutbreakStopYear, PlugIn.ModelCore.CurrentTime);

                    if (insect.OutbreakStartYear == insect.OutbreakStopYear) // shouldn't need this. JRF
                    {
                        insect.SingleOutbreakYear = true;
                    }
                    insect.MortalityYear     = PlugIn.ModelCore.CurrentTime + 1;
                    insect.LastStartYear     = insect.OutbreakStartYear; // Added here for Brian's log file.
                    insect.LastStopYear      = insect.OutbreakStopYear;  // Added here for Brian's log file.
                    insect.OutbreakStartYear = PlugIn.ModelCore.CurrentTime + (int)timeBetweenOutbreaks;
                    insect.OutbreakStopYear  = insect.OutbreakStartYear + (int)duration - 1;
                }

                else if (insect.OutbreakStopYear <= PlugIn.ModelCore.CurrentTime &&
                         timeAfterDuration > PlugIn.ModelCore.CurrentTime - insect.OutbreakStopYear)
                {
                    // PlugIn.ModelCore.UI.WriteLine("   In between outbreaks, reset start and stop times.");
                    insect.ActiveOutbreak = true;
                    PlugIn.ModelCore.UI.WriteLine("   {0} is active.  StartYear={1}, StopYear={2}, CurrentYear={3}.", insect.Name, insect.OutbreakStartYear, insect.OutbreakStopYear, PlugIn.ModelCore.CurrentTime);

                    insect.MortalityYear     = PlugIn.ModelCore.CurrentTime + 1;
                    insect.LastStartYear     = insect.OutbreakStartYear; // Added here for Brian's log file.
                    insect.LastStopYear      = insect.OutbreakStopYear;  // Added here for Brian's log file.
                    insect.OutbreakStartYear = PlugIn.ModelCore.CurrentTime + (int)timeBetweenOutbreaks;
                    insect.OutbreakStopYear  = insect.OutbreakStartYear + (int)duration - 1;
                }
                PlugIn.ModelCore.UI.WriteLine("  Insect Start Time = {0}, Stop Time = {1}.", insect.OutbreakStartYear, insect.OutbreakStopYear);

                // Now that logic determining when an outbreak will be active is done, tell model what to do when outbreak is occurring.
                if (insect.ActiveOutbreak)
                {
                    //  PlugIn.ModelCore.UI.WriteLine("   OutbreakStartYear={0}.", insect.OutbreakStartYear);

                    if (insect.OutbreakStartYear == PlugIn.ModelCore.CurrentTime || insect.SingleOutbreakYear)
                    {
                        // Initialize neighborhoodGrowthReduction with patches
                        Outbreak.InitializeDefoliationPatches(insect);
                    }
                    else
                    {
                        insect.NeighborhoodDefoliation.ActiveSiteValues = 0;
                    }
                }

                // Now report on the previous year's defoliation, that which has been processed
                // through biomass succession. Calculations for logfile.

                double sumDefoliation  = 0.0;
                double meanDefoliation = 0.0;
                int    numSites0_33    = 0;
                int    numSites33_66   = 0;
                int    numSites66_100  = 0;
                int    numInitialSites = 0;
                int    numSitesActive  = 0; // Just get a sum of all active sites to calculate mean defoliation accurately for log file.

                // ONly calculate for log file when outbreak or mortality is active <- Modified, JRF, add to log file each year.
                if (insect.ActiveOutbreak || insect.SingleOutbreakYear || (insect.LastStopYear + 1 >= PlugIn.ModelCore.CurrentTime) || (insect.LastBioRemoved > 0))
                {
                    foreach (ActiveSite site in PlugIn.ModelCore.Landscape)
                    {
                        sumDefoliation += insect.LastYearDefoliation[site];
                        if (insect.LastYearDefoliation[site] > 0.0 && insect.LastYearDefoliation[site] <= 0.33)
                        {
                            numSites0_33++;
                        }
                        if (insect.LastYearDefoliation[site] > 0.33 && insect.LastYearDefoliation[site] <= 0.66)
                        {
                            numSites33_66++;
                        }
                        if (insect.LastYearDefoliation[site] > 0.66 && insect.LastYearDefoliation[site] <= 1.0)
                        {
                            numSites66_100++;
                        }
                        if (insect.Disturbed[site] && SiteVars.InitialOutbreakProb[site] > 0)
                        {
                            numInitialSites++;
                        }
                        numSitesActive++;
                    }
                    if (insect.OutbreakStartYear == PlugIn.ModelCore.CurrentTime)
                    {
                        insect.InitialSites = numInitialSites;
                    }

                    if (numSites0_33 + numSites33_66 + numSites66_100 > 0)
                    {
                        meanDefoliation = sumDefoliation / (double)numSitesActive;
                    }
                    //PlugIn.ModelCore.UI.WriteLine("   sumDefoliation={0}, numSites={1}.", sumDefoliation, numSites0_33 + numSites33_66 + numSites66_100);
                }

                int totalBioRemoved = 0;
                foreach (ActiveSite site in PlugIn.ModelCore.Landscape)
                {
                    totalBioRemoved += SiteVars.BiomassRemoved[site]; // kg across all defoliated sites
                }
                insect.LastBioRemoved = totalBioRemoved;              //Assign variables for the logfile
                // PlugIn.ModelCore.UI.WriteLine("   totalBioRemoved={0}.", totalBioRemoved);


                // ONly add to log & output maps during outbreak <- Modified, JRF, add to log file each year.
                //if ((insect.ActiveOutbreak && insect.OutbreakStartYear < PlugIn.ModelCore.CurrentTime) || (meanDefoliation > 0) || (insect.LastBioRemoved > 0))
                //{

                /*  Old code for log file
                 *  if (meanDefoliation > 0)
                 *  {
                 *
                 *          log.Write("{0},{1},{2},{3},{4:0.0000},{5},{6},{7},{8},{9}",
                 *                  PlugIn.ModelCore.CurrentTime-1,  //0
                 *                  insect.Name,  //1
                 *                  insect.LastStartYear,  //2
                 *                  insect.LastStopYear,  //3
                 *                  meanDefoliation, //4
                 *                  numSites0_33, //5
                 *                  numSites33_66,  //6
                 *                  numSites66_100, //7
                 *                  insect.InitialSites, //8
                 *                  insect.LastBioRemoved //9
                 *                  );
                 *  }
                 *
                 *  else
                 *  {
                 *      log.Write("{0},{1},{2},{3},{4:0.0000},{5},{6},{7},{8},{9}",
                 *              PlugIn.ModelCore.CurrentTime - 1,  //0
                 *              insect.Name,  //1
                 *              0,  //2
                 *              0,  //3
                 *              meanDefoliation, //4
                 *              numSites0_33, //5
                 *              numSites33_66,  //6
                 *              numSites66_100, //7
                 *              0, //8
                 *              insect.LastBioRemoved //9
                 *              );
                 *  }
                 *
                 *
                 *  //foreach (IEcoregion ecoregion in Ecoregions.Dataset)
                 *  //    log.Write(",{0}", 1);
                 *
                 *  log.WriteLine("");
                 */

                eventLog.Clear();
                EventsLog el = new EventsLog();

                el.Time                     = PlugIn.ModelCore.CurrentTime - 1;
                el.InsectName               = insect.Name;
                el.MeanDefoliation          = meanDefoliation;
                el.NumSitesDefoliated0_33   = numSites0_33;
                el.NumSitesDefoliated33_66  = numSites33_66;
                el.NumSitesDefoliated66_100 = numSites66_100;
                el.NumOutbreakInitialSites  = insect.InitialSites;
                el.MortalityBiomass         = insect.LastBioRemoved;

                if (insect.ActiveOutbreak)
                {
                    el.StartYear = insect.OutbreakStartYear;
                    el.StopYear  = insect.OutbreakStopYear;
                }
                else
                {
                    el.StartYear = insect.LastStartYear;
                    el.StopYear  = insect.LastStopYear;
                }

                eventLog.AddObject(el);
                eventLog.WriteToFile();

                //----- Write Insect Defoliation/GrowthReduction maps --------
                string path = MapNames.ReplaceTemplateVars(mapNameTemplate, insect.Name, PlugIn.ModelCore.CurrentTime - 1);
                using (IOutputRaster <ShortPixel> outputRaster = modelCore.CreateRaster <ShortPixel>(path, modelCore.Landscape.Dimensions))
                {
                    ShortPixel pixel = outputRaster.BufferPixel;

                    foreach (Site site in PlugIn.ModelCore.Landscape.AllSites)
                    {
                        if (site.IsActive)
                        {
                            pixel.MapCode.Value = (short)(insect.LastYearDefoliation[site] * 100.0);
                        }
                        else
                        {
                            //  Inactive site
                            pixel.MapCode.Value = 0;
                        }

                        outputRaster.WriteBufferPixel();
                    }
                }

                //----- Write Initial Patch maps --------
                string path2 = MapNames.ReplaceTemplateVars(mapNameTemplate, ("InitialPatchMap" + insect.Name), PlugIn.ModelCore.CurrentTime);
                using (IOutputRaster <ShortPixel> outputRaster = modelCore.CreateRaster <ShortPixel>(path2, modelCore.Landscape.Dimensions))
                {
                    ShortPixel pixel = outputRaster.BufferPixel;
                    foreach (Site site in PlugIn.ModelCore.Landscape.AllSites)
                    {
                        if (site.IsActive)
                        {
                            if (insect.Disturbed[site])
                            {
                                pixel.MapCode.Value = (short)(SiteVars.InitialOutbreakProb[site] * 100);
                            }
                            else
                            {
                                pixel.MapCode.Value = 0;
                            }
                        }
                        else
                        {
                            //  Inactive site
                            pixel.MapCode.Value = 0;
                        }
                        outputRaster.WriteBufferPixel();
                        //Zero out the InitialOutbreakProb after output maps are written.
                        SiteVars.InitialOutbreakProb[site] = 0;
                    }
                }

                //----- Write Biomass Reduction maps --------
                string path3 = MapNames.ReplaceTemplateVars(mapNameTemplate, ("BiomassRemoved" + insect.Name), PlugIn.ModelCore.CurrentTime);
                using (IOutputRaster <ShortPixel> outputRaster = modelCore.CreateRaster <ShortPixel>(path3, modelCore.Landscape.Dimensions))
                {
                    ShortPixel pixel = outputRaster.BufferPixel;
                    foreach (Site site in PlugIn.ModelCore.Landscape.AllSites)
                    {
                        if (site.IsActive)
                        {
                            if (SiteVars.BiomassRemoved[site] > 0)
                            {
                                pixel.MapCode.Value = Math.Max((short)1, (short)(SiteVars.BiomassRemoved[site] / 100));     // convert to Mg/ha
                            }
                            else
                            {
                                pixel.MapCode.Value = 0;
                            }
                        }
                        else
                        {
                            //  Inactive site
                            pixel.MapCode.Value = 0;
                        }
                        outputRaster.WriteBufferPixel();
                        //Zero out the BiomassRemoved after the last insect mortality event in a given year.
                        SiteVars.BiomassRemoved[site] = 0;
                    }
                }
                //}

                //insect.ThisYearDefoliation.ActiveSiteValues = 0.0;  //reset this year to 0 for all sites, this was already done at the top of loop to initialize defoliation patchs, Outbreak.cs
            }
        }
Пример #20
0
        public void Run()
        {
            Console.WriteLine("Running the example LANDIS-II extension...");

            Console.WriteLine("Ecoregion codes:");
            foreach (Site site in core.Landscape.AllSites)
            {
                Console.Write("  {0}", core.EcoregionCodes[site]);
                if (site.Location.Column == core.Landscape.Columns)
                {
                    Console.WriteLine();
                }
            }
            Console.WriteLine();

            short[,] data = new short[90, 140];
            int        rows       = data.GetLength(0);
            int        columns    = data.GetLength(1);
            Dimensions dimensions = new Dimensions(rows, columns);

            for (int r = 0; r < rows; ++r)
            {
                for (int c = 0; c < columns; ++c)
                {
                    data[r, c] = (short)((c * 100) + r);
                }
            }

            string rasterPath = "slope-aspect.img";

            using (IOutputRaster <SlopeAspectPixel> outputRaster = core.CreateRaster <SlopeAspectPixel>(rasterPath, dimensions))
            {
                SlopeAspectPixel pixel = outputRaster.BufferPixel;
                for (int row = 0; row < rows; ++row)
                {
                    for (int column = 0; column < columns; ++column)
                    {
                        pixel.Slope.Value  = (float)(data[row, column] / 100.0);
                        pixel.Aspect.Value = data[row, column];
                        outputRaster.WriteBufferPixel();
                    }
                }
            }

            Console.WriteLine("Opening input raster \"{0}\":", rasterPath);
            // Have to use pixel with two float bands because GDAL allows only
            // one shared data type across all the raster bands when creating
            // a raster.
            //
            // TO DO: Consider changing spatial library's API so that all the
            //        bands in an input or output raster have the same type.
            using (IInputRaster <SlopeAspectPixel_float> inputRaster = core.OpenRaster <SlopeAspectPixel_float>(rasterPath))
            {
                Console.WriteLine("  Dimensions: {0}", inputRaster.Dimensions);

                SlopeAspectPixel_float pixel = inputRaster.BufferPixel;
                int slopeErrors  = 0;
                int aspectErrors = 0;
                for (int row = 1; row <= inputRaster.Dimensions.Rows; ++row)
                {
                    for (int column = 1; column <= inputRaster.Dimensions.Columns; ++column)
                    {
                        inputRaster.ReadBufferPixel();

                        // Check the actual slope and aspect values to expected values
                        float expectedSlope = (float)(data[row - 1, column - 1] / 100.0);
                        if (pixel.Slope.Value != expectedSlope)
                        {
                            Console.WriteLine("({0}, {1}) : expected Slope ({2}) not = actual Slope ({3})", row, column, expectedSlope, pixel.Slope.Value);
                            slopeErrors++;
                        }
                        float expectedAspect = data[row - 1, column - 1];
                        if (pixel.Aspect.Value != expectedAspect)
                        {
                            Console.WriteLine("({0}, {1}) : expected Aspect ({2}) not = actual Aspect ({3})", row, column, expectedAspect, pixel.Aspect.Value);
                            aspectErrors++;
                        }
                    }
                }
                Console.WriteLine("# of mismatched slope values: {0}", slopeErrors);
                Console.WriteLine("# of mismatched aspect values: {0}", aspectErrors);
            }
        }
Пример #21
0
        internal bool GenerateWindFieldRaster(
            string mapNameTemplate, ICore modelCore, ContinentalGrid continentalGrid)
        {
            this.ContinentalGrid = continentalGrid;
            Dimensions dimensions          = new Dimensions(modelCore.Landscape.Rows, modelCore.Landscape.Columns);
            int        columns             = modelCore.Landscape.Columns;
            int        rows                = modelCore.Landscape.Rows;
            double     lowerLeftWindspeed  = this.GetWindSpeed(0, 0);
            double     lowerRightWindSpeed = this.GetWindSpeed(columns, 0);
            double     upperRightWindSpeed = this.GetWindSpeed(columns, rows);
            double     upperLeftWindSpeed  = this.GetWindSpeed(0, rows);
            double     maxWS               = (new[] { lowerLeftWindspeed, lowerRightWindSpeed, upperRightWindSpeed, upperLeftWindSpeed }).Max();

            //double minWS = (new[] { lowerLeftWindspeed, lowerRightWindSpeed, upperRightWindSpeed, upperLeftWindSpeed }).Min();
            this.studyAreaImpacts = true;
            if (maxWS < HurricaneEvent.MinimumWSforDamage)
            {
                //PlugIn.ModelCore.UI.WriteLine("   Hurricane Not Sufficient to Cause Damage:  MaxWS={0}, HurricaneMinWS={1}", maxWS, MinimumWSforDamage);
                this.studyAreaImpacts = false;
                //return false;
            }


            SiteVars.WindSpeed.ActiveSiteValues = 0.0;

            foreach (ActiveSite site in PlugIn.ModelCore.Landscape.ActiveSites)
            {
                currentSite = site;
                SiteVars.WindSpeed[currentSite] = this.GetWindSpeed(site.Location.Column, site.Location.Row);
                KillSiteCohorts(currentSite);
            }

            double activeAreaMinWS = 999.0;
            double activeAreaMaxWS = 0.0;

            string path = MapNames.ReplaceTemplateVars(mapNameTemplate, modelCore.CurrentTime);
            IOutputRaster <BytePixel> outputRaster = null;

            using (outputRaster = modelCore.CreateRaster <BytePixel>(path, dimensions))
            {
                BytePixel pixel = outputRaster.BufferPixel;
                foreach (Site site in PlugIn.ModelCore.Landscape.AllSites)
                {
                    if (site.IsActive)
                    {
                        double windspeed = SiteVars.WindSpeed[site];
                        pixel.MapCode.Value = (byte)windspeed;
                        if (windspeed < activeAreaMinWS)
                        {
                            activeAreaMinWS = windspeed;
                        }
                        if (windspeed > activeAreaMaxWS)
                        {
                            activeAreaMaxWS = windspeed;
                        }
                    }
                    else
                    {
                        //  Inactive site
                        pixel.MapCode.Value = (byte)0;
                    }
                    outputRaster.WriteBufferPixel();
                }
            }
            this.StudyAreaMinWindspeed = activeAreaMinWS;
            this.StudyAreaMaxWindspeed = activeAreaMaxWS;
            //PlugIn.ModelCore.UI.WriteLine("   Hurricane Caused Damage:  AreaMaxWS={0}, AreaMinWS={1}", activeAreaMaxWS, activeAreaMinWS);
            return(true);
        }
Пример #22
0
        //---------------------------------------------------------------------
        ///<summary>
        /// Run the EDA extension at a particular timestep.
        ///</summary>
        public override void Run()
        {
            ModelCore.UI.WriteLine("   Processing landscape for EDA events ...");
            if (!reinitialized)
            {
                InitializePhase2();
            }

            int eventCount = 0;

            int agentIndex = 0;

            foreach (IAgent activeAgent in manyAgentParameters)
            {
                Epidemic.Initialize(activeAgent);

                if (activeAgent.DispersalType == DispersalType.STATIC)
                {
                    ModelCore.UI.WriteLine("   Simulating spread of epidemic...");
                    Epidemic currentEpic = Epidemic.Simulate(activeAgent, ModelCore.CurrentTime, agentIndex);
                    if (currentEpic != null)
                    {
                        LogEvent(ModelCore.CurrentTime, currentEpic, activeAgent);

                        //----- Write Infection Status maps (SUSCEPTIBLE (0), INFECTED (cryptic-non symptomatic) (1), DISEASED (symptomatic) (2) --------
                        string path = MapNames.ReplaceTemplateVars(statusMapName, activeAgent.AgentName, ModelCore.CurrentTime);
                        modelCore.UI.WriteLine("   Writing infection status map to {0} ...", path);
                        using (IOutputRaster <BytePixel> outputRaster = modelCore.CreateRaster <BytePixel>(path, modelCore.Landscape.Dimensions))
                        {
                            BytePixel pixel = outputRaster.BufferPixel;
                            foreach (Site site in ModelCore.Landscape.AllSites)
                            {
                                if (site.IsActive)
                                {
                                    pixel.MapCode.Value = (byte)(SiteVars.InfStatus[site][agentIndex] + 1);
                                }
                                else
                                {
                                    //Inactive site
                                    pixel.MapCode.Value = 0;
                                }
                                outputRaster.WriteBufferPixel();
                            }
                        }

                        if (!(mortMapNames == null))
                        {
                            //----- Write Cohort Mortality Maps (number dead cohorts for selected species) --------
                            string path2 = MapNames.ReplaceTemplateVars(mortMapNames, activeAgent.AgentName, ModelCore.CurrentTime);
                            modelCore.UI.WriteLine("   Writing cohort mortality map to {0} ...", path2);
                            using (IOutputRaster <ShortPixel> outputRaster = modelCore.CreateRaster <ShortPixel>(path2, modelCore.Landscape.Dimensions))
                            {
                                ShortPixel pixel = outputRaster.BufferPixel;
                                foreach (Site site in ModelCore.Landscape.AllSites)
                                {
                                    if (site.IsActive)
                                    {
                                        pixel.MapCode.Value = (short)(SiteVars.NumberMortSppKilled[site][agentIndex]);
                                    }
                                    else
                                    {
                                        //Inactive site
                                        pixel.MapCode.Value = -999; //should work with "short" type
                                    }
                                    outputRaster.WriteBufferPixel();
                                }
                            }
                        }

                        eventCount++;
                    }
                }
                else if (activeAgent.DispersalType == DispersalType.DYNAMIC)
                {
                    /*****************TODO*******************/
                    Console.WriteLine("Dynamic dispersal type has not been implemented yet!!");
                }

                agentIndex++;
            }
        }
Пример #23
0
        //---------------------------------------------------------------------

        /// <summary>
        /// Runs the component for a particular timestep.
        /// </summary>
        /// <param name="currentTime">
        /// The current model timestep.
        /// </param>
        public override void Run()
        {
            // The index variable increments with each suitability file - an index of multiple wildlife input files
            int index = 0;

            foreach (string suitabilityFile in suitabilityFiles)
            {
                // get suitability parameters
                ISuitabilityParameters mySuitabilityParameters = suitabilityParameters[index];

                foreach (Site site in modelCore.Landscape.ActiveSites)
                {
                    double suitabilityValue = 0;
                    // calculate dominant age as site variable (DomAge), store for retrieval
                    //  Note: DomAge site variable is an array of values giving dominant age for this year and last year
                    UpdateDominantAge(site);

                    // calculate forest type as site variable (ForestType), store for retreival
                    //  Note: ForestType site variable is an array of values giving the index of forest type for this year and last year
                    UpdateForestType(index, mySuitabilityParameters, site);

                    // depending on suitability type, calculate final suitability value

                    if (mySuitabilityParameters.SuitabilityType == "AgeClass_ForestType")
                    {
                        //   get forest type (calculated above with UpdateForestType)
                        int currentForestType = SiteVars.ForestType[site][index][0];

                        if (currentForestType > 0)
                        {
                            IForestType forestType = mySuitabilityParameters.ForestTypes[0].ForestTypes[currentForestType - 1];
                            //   calculate dominant age among species in forest type
                            int domFTAge = CalculateDomAgeForestType(site, forestType);
                            //   look up suitability in suitabilityTable for combination of forest type and age
                            Dictionary <int, double> suitabilityRow = mySuitabilityParameters.Suitabilities[forestType.Name];

                            foreach (KeyValuePair <int, double> item in suitabilityRow)
                            {
                                int ageLimit = item.Key;
                                if (domFTAge <= ageLimit)
                                {
                                    suitabilityValue = item.Value;
                                    break;
                                }
                            }
                        }
                        else
                        {
                            suitabilityValue = 0;
                        }
                        //  write sitevar for suitability value
                        SiteVars.SuitabilityValue[site][index] = suitabilityValue;
                    }
                    // if suitabilityType == AgeClass_TimeSinceDisturbance:
                    else if (mySuitabilityParameters.SuitabilityType == "AgeClass_TimeSinceDisturbance")
                    {
                        int    ageAtDisturbanceYear = 0;
                        int    timeSinceDisturbance = 0;
                        double suitabilityWeight    = 0.0;
                        // if disturbanceType == "Fire" then:
                        if (mySuitabilityParameters.DisturbanceType == "Fire")
                        {
                            // Check if fire severity output exists
                            if (SiteVars.FireSeverity == null)
                            {
                                string mesg = string.Format("The DisturbanceType is Fire, but FireSeverity SiteVariable is not defined.  Please double-check that a fire extension is running.");
                                throw new System.ApplicationException(mesg);
                            }
                            else
                            {
                                //   Check this year fire severity
                                int currentFireSeverity = (int)SiteVars.FireSeverity[site];
                                int timeofLastFire      = SiteVars.TimeOfLastFire[site];
                                //   if > 0 then update sites with new values
                                if (currentFireSeverity > 0 && timeofLastFire == ModelCore.CurrentTime)
                                {
                                    //      translate to suitability weight
                                    suitabilityWeight = mySuitabilityParameters.FireSeverities[currentFireSeverity];

                                    SiteVars.SuitabilityWeight[site][index] = suitabilityWeight;

                                    //      if suitability weight > 0 then
                                    if (suitabilityWeight > 0)
                                    {
                                        //        store sitevar YearOfFire by index
                                        SiteVars.YearOfFire[site][index] = ModelCore.CurrentTime;
                                        //        read previous year dominant age
                                        int prevYearDomAge = SiteVars.DominantAge[site][1];
                                        //        store sitevar AgeAtFireYear by index
                                        SiteVars.AgeAtFireYear[site][index] = prevYearDomAge;
                                    }
                                }
                                //  read sitevar AgeAtDisturbanceYear for age value
                                ageAtDisturbanceYear = SiteVars.AgeAtFireYear[site][index];
                                //  read sitevar YearOfFire
                                int yearOfFire = SiteVars.YearOfFire[site][index];
                                //  calculate timeSinceDisturbance = currentYear - YearOfFire
                                timeSinceDisturbance = ModelCore.CurrentTime - yearOfFire;
                            }
                        }
                        // if disturbanceType == "Harvest" then:
                        else if (mySuitabilityParameters.DisturbanceType == "Harvest")
                        {
                            // Check if harvest prescription output exists
                            if (SiteVars.PrescriptionName == null)
                            {
                                string mesg = string.Format("The DisturbanceType is Harvest, but prescriptionName SiteVariable is not defined.  Please double-check that a Harvest extension is running.");
                                throw new System.ApplicationException(mesg);
                            }
                            else
                            {
                                //  Check this year harvest prescription names
                                string currentprescriptionName = SiteVars.PrescriptionName[site];
                                int    timeofLastHarvest       = SiteVars.TimeOfLastHarvest[site];
                                //   if != null then
                                if (currentprescriptionName != null && timeofLastHarvest == ModelCore.CurrentTime)
                                {
                                    //      translate to suitability weight
                                    suitabilityWeight = mySuitabilityParameters.HarvestPrescriptions[currentprescriptionName];
                                    //      if suitability weight > 0 then
                                    if (suitabilityWeight > 0)
                                    {
                                        //        store sitevar YearOfHarvest by index
                                        SiteVars.YearOfHarvest[site][index] = ModelCore.CurrentTime;
                                        //        read previous year dominant age
                                        int prevYearDomAge = SiteVars.DominantAge[site][1];
                                        //        store sitevar AgeAtHarvestYear by index
                                        SiteVars.AgeAtHarvestYear[site][index] = prevYearDomAge;
                                        //        store sitevar SuitabilityWeight by index
                                        SiteVars.SuitabilityWeight[site][index] = suitabilityWeight;
                                    }
                                }
                                //  read sitevar AgeAtDisturbanceYear for age value
                                ageAtDisturbanceYear = SiteVars.AgeAtHarvestYear[site][index];
                                //  read sitevar YearOfHarvest
                                int yearOfHarvest = SiteVars.YearOfHarvest[site][index];
                                //  calculate timeSinceDisturbance = currentYear - YearOfHarvest
                                timeSinceDisturbance = ModelCore.CurrentTime - yearOfHarvest;
                            }
                        }
                        //  look up suitabilty in suitabilityTable for combination of AgeAtDisturbanceYear and timeSinceDisturbance
                        foreach (KeyValuePair <string, Dictionary <int, double> > suitabilityRow in mySuitabilityParameters.Suitabilities)
                        {
                            int maxTimeSinceDist = int.Parse(suitabilityRow.Key);
                            if (timeSinceDisturbance <= maxTimeSinceDist)
                            {
                                foreach (KeyValuePair <int, double> item in suitabilityRow.Value)
                                {
                                    int ageLimit = item.Key;
                                    if (ageAtDisturbanceYear <= ageLimit)
                                    {
                                        suitabilityValue = (item.Value * SiteVars.SuitabilityWeight[site][index]);
                                        break;
                                    }
                                }
                                break;
                            }
                        }


                        // write sitevar for suitability value
                        SiteVars.SuitabilityValue[site][index] = suitabilityValue;
                    }

                    // if suitabilityType == ForestType_TimeSinceDisturbance:
                    else if (mySuitabilityParameters.SuitabilityType == "ForestType_TimeSinceDisturbance")
                    {
                        int    forestTypeAtDisturbanceYear = 0;
                        int    timeSinceDisturbance        = 0;
                        double suitabilityWeight           = 0.0;
                        // if disturbanceType == "Fire" then:
                        if (mySuitabilityParameters.DisturbanceType == "Fire")
                        {
                            // Check if fire output exists
                            if (SiteVars.FireSeverity == null)
                            {
                                string mesg = string.Format("The DisturbanceType is Fire, but FireSeverity SiteVariable is not defined.  Please double-check that a Fire extension is running.");
                                throw new System.ApplicationException(mesg);
                            }
                            else
                            {
                                //   Check this year fire severity
                                int currentFireSeverity = SiteVars.FireSeverity[site];
                                int timeofLastFire      = SiteVars.TimeOfLastFire[site];
                                //   if > 0 then
                                if (currentFireSeverity > 0 && timeofLastFire == ModelCore.CurrentTime)
                                {
                                    //      translate to suitability weight
                                    suitabilityWeight = mySuitabilityParameters.FireSeverities[currentFireSeverity];

                                    //      if suitability weight > 0 then
                                    if (suitabilityWeight > 0)
                                    {
                                        //        store sitevar YearOfFire by index
                                        SiteVars.YearOfFire[site][index] = ModelCore.CurrentTime;
                                        //        read previous year forest type
                                        int prevYearForType = SiteVars.ForestType[site][index][1];
                                        //        store sitevar forestTypeAtFireYear by index
                                        SiteVars.ForestTypeAtFireYear[site][index] = prevYearForType;
                                        //        store sitevar SuitabilityWeight by index
                                        SiteVars.SuitabilityWeight[site][index] = suitabilityWeight;
                                    }
                                }
                            }
                            //  read sitevar ForestTypeFireYear for age value
                            forestTypeAtDisturbanceYear = SiteVars.ForestTypeAtFireYear[site][index];
                            //  read sitevar YearOfFire
                            int yearOfFire = SiteVars.YearOfFire[site][index];
                            //  calculate timeSinceDisturbance = currentYear - YearOfFire
                            timeSinceDisturbance = ModelCore.CurrentTime - yearOfFire;
                        }
                        // if disturbanceType == "Harvest" then:
                        else if (mySuitabilityParameters.DisturbanceType == "Harvest")
                        {
                            // Check if harvest prescription output exists
                            if (SiteVars.PrescriptionName == null)
                            {
                                string mesg = string.Format("The DisturbanceType is Harvest, but prescriptionName SiteVariable is not defined.  Please double-check that a Harvest extension is running.");
                                throw new System.ApplicationException(mesg);
                            }
                            else
                            {
                                //  Check this year harvest prescription names
                                string currentprescriptionName = SiteVars.PrescriptionName[site];
                                int    timeofLastHarvest       = SiteVars.TimeOfLastHarvest[site];
                                //   if != null then
                                if (currentprescriptionName != null && timeofLastHarvest == ModelCore.CurrentTime)
                                {
                                    //      translate to suitability weight
                                    suitabilityWeight = mySuitabilityParameters.HarvestPrescriptions[currentprescriptionName];
                                    //      if suitability weight > 0 then
                                    if (suitabilityWeight > 0)
                                    {
                                        //        store sitevar YearOfHarvest by index
                                        SiteVars.YearOfHarvest[site][index] = ModelCore.CurrentTime;
                                        //        read previous year forest type
                                        int prevYearForType = SiteVars.ForestType[site][index][1];
                                        //        store sitevar forestTypeAtHarvestYear by index
                                        SiteVars.ForestTypeAtHarvestYear[site][index] = prevYearForType;
                                        //        store sitevar SuitabilityWeight by index
                                        SiteVars.SuitabilityWeight[site][index] = suitabilityWeight;
                                    }
                                }
                                //  read sitevar AgeAtHarvestYear for age value
                                forestTypeAtDisturbanceYear = SiteVars.ForestTypeAtHarvestYear[site][index];
                                //  read sitevar YearOfHarvest
                                int yearOfHarvest = SiteVars.YearOfHarvest[site][index];
                                //  calculate timeSinceDisturbance = currentYear - YearOfHarvest
                                timeSinceDisturbance = ModelCore.CurrentTime - yearOfHarvest;
                            }
                        }
                        if (forestTypeAtDisturbanceYear > 0)
                        {
                            IForestType forestType = mySuitabilityParameters.ForestTypes[0].ForestTypes[forestTypeAtDisturbanceYear - 1];

                            // look up suitability in suitabilityTable for combination of forest type and timeSinceDisturbance
                            Dictionary <int, double> suitabilityRow = mySuitabilityParameters.Suitabilities[forestType.Name];

                            foreach (KeyValuePair <int, double> item in suitabilityRow)
                            {
                                int maxTimeSinceDist = item.Key;
                                if (timeSinceDisturbance <= maxTimeSinceDist)
                                {
                                    suitabilityValue = (item.Value * SiteVars.SuitabilityWeight[site][index]);
                                    break;
                                }
                            }
                        }
                        else
                        {
                            suitabilityValue = 0;
                        }

                        // write sitevar for suitability value
                        SiteVars.SuitabilityValue[site][index] = suitabilityValue;
                    }
                }
                // if output timestep then write all maps
                if ((ModelCore.CurrentTime % parameters.OutputTimestep) == 0)
                {
                    string mapName = mySuitabilityParameters.HabitatName;
                    string path    = MapFileNames.ReplaceTemplateVars(mapNameTemplate, mapName, modelCore.CurrentTime);
                    ModelCore.UI.WriteLine("   Writing Habitat Output map to {0} ...", path);
                    using (IOutputRaster <IntPixel> outputRaster = modelCore.CreateRaster <IntPixel>(path, modelCore.Landscape.Dimensions))
                    {
                        IntPixel pixel = outputRaster.BufferPixel;
                        foreach (Site site in modelCore.Landscape.AllSites)
                        {
                            if (site.IsActive)
                            {
                                pixel.MapCode.Value = (int)(SiteVars.SuitabilityValue[site][index] * 100);
                            }
                            else
                            {
                                pixel.MapCode.Value = 0;
                            }

                            outputRaster.WriteBufferPixel();
                        }
                    }
                }


                /*Copied from biomass-reclass
                 * foreach (IMapDefinition map in mapDefs)
                 * {
                 *  List<IForestType> forestTypes = map.ForestTypes;
                 *
                 *  string path = MapFileNames.ReplaceTemplateVars(mapNameTemplate, map.Name, modelCore.CurrentTime);
                 *  modelCore.Log.WriteLine("   Writing Biomass Reclass map to {0} ...", path);
                 *  using (IOutputRaster<BytePixel> outputRaster = modelCore.CreateRaster<BytePixel>(path, modelCore.Landscape.Dimensions))
                 *  {
                 *      BytePixel pixel = outputRaster.BufferPixel;
                 *      foreach (Site site in modelCore.Landscape.AllSites)
                 *      {
                 *          if (site.IsActive)
                 *              pixel.MapCode.Value = CalcForestType(forestTypes, site);
                 *          else
                 *              pixel.MapCode.Value = 0;
                 *
                 *          outputRaster.WriteBufferPixel();
                 *      }
                 *  }
                 *
                 * }
                 * */
                index++;
            }
        }
Пример #24
0
        //---------------------------------------------------------------------

        /// <summary>
        /// Runs the component for a particular timestep.
        /// </summary>
        /// <param name="currentTime">
        /// The current model timestep.
        /// </param>
        public override void Run()
        {
            // Calculate Local Variables
            foreach (IMapDefinition map in mapDefs)
            {
                List <IForestType> forestTypes = map.ForestTypes;

                foreach (Site site in modelCore.Landscape.AllSites)
                {
                    int mapCode = 0;
                    if (site.IsActive)
                    {
                        mapCode = CalcForestType(forestTypes, site);
                    }
                    else
                    {
                        mapCode = 0;
                    }
                    SiteVars.LocalVars[site][map.Name] = mapCode;
                }
            }

            // Calculate Derived Variables
            foreach (IVariableDefinition var in varDefs)
            {
                foreach (Site site in modelCore.Landscape.AllSites)
                {
                    SiteVars.DerivedVars[site][var.Name] = 0;
                }
                List <string> variables = var.Variables;
                List <string> operators = var.Operators;

                // Parse variable name into mapDef and fortype
                for (int i = 0; i < variables.Count; i++)
                {
                    string fullVar = variables[i];
                    // string[] varSplit = Regex.Split(fullVar, "\\[.*?\\]");
                    string[] varSplit = fullVar.Split(new char[] { '[', ']' }, StringSplitOptions.RemoveEmptyEntries);
                    string   mapName  = varSplit[0];
                    string   varName  = varSplit[1];
                    int      mapCode  = 0;

                    foreach (IMapDefinition map in mapDefs)
                    {
                        if (map.Name == mapName)
                        {
                            int forTypeCnt = 1;
                            foreach (IForestType forestType in map.ForestTypes)
                            {
                                if (forestType.Name == varName)
                                {
                                    mapCode = forTypeCnt;
                                }
                                forTypeCnt++;
                            }
                        }
                    }
                    foreach (Site site in modelCore.Landscape.AllSites)
                    {
                        if (SiteVars.LocalVars[site][mapName] == mapCode)
                        {
                            SiteVars.DerivedVars[site][var.Name] = 1;
                        }
                    }
                }
            }

            // Calculate Neighborhood Variables
            foreach (INeighborVariableDefinition neighborVar in neighborVarDefs)
            {
                //Parse LocalVar
                string fullVar = neighborVar.LocalVariable;
                //string[] varSplit = Regex.Split(fullVar, "[]");
                string[] varSplit = fullVar.Split(new char[] { '[', ']' }, StringSplitOptions.RemoveEmptyEntries);
                string   varName  = "";
                int      mapCode  = 0;
                string   mapName  = "";
                if (varSplit.Length > 1)
                {
                    mapName = varSplit[0];
                    varName = varSplit[1];

                    foreach (IMapDefinition map in mapDefs)
                    {
                        if (map.Name == mapName)
                        {
                            int forTypeCnt = 1;
                            foreach (IForestType forestType in map.ForestTypes)
                            {
                                if (forestType.Name == varName)
                                {
                                    mapCode = forTypeCnt;
                                }
                                forTypeCnt++;
                            }
                        }
                    }
                }
                else
                {
                    varName = fullVar;
                }

                // Calculate neighborhood
                double CellLength = PlugIn.ModelCore.CellLength;
                PlugIn.ModelCore.UI.WriteLine("Creating Dispersal Neighborhood List.");

                List <RelativeLocation> neighborhood = new List <RelativeLocation>();
                int neighborRadius = neighborVar.NeighborRadius;
                int numCellRadius  = (int)(neighborRadius / CellLength);
                PlugIn.ModelCore.UI.WriteLine("NeighborRadius={0}, CellLength={1}, numCellRadius={2}",
                                              neighborRadius, CellLength, numCellRadius);
                double centroidDistance = 0;
                double cellLength       = CellLength;

                for (int row = (numCellRadius * -1); row <= numCellRadius; row++)
                {
                    for (int col = (numCellRadius * -1); col <= numCellRadius; col++)
                    {
                        centroidDistance = DistanceFromCenter(row, col);

                        //PlugIn.ModelCore.Log.WriteLine("Centroid Distance = {0}.", centroidDistance);
                        if (centroidDistance <= neighborRadius)
                        {
                            neighborhood.Add(new RelativeLocation(row, col));
                        }
                    }
                }
                // Calculate neighborhood value (% area of forest types)
                foreach (Site site in modelCore.Landscape.AllSites)
                {
                    int totalNeighborCells  = 0;
                    int targetNeighborCells = 0;
                    foreach (RelativeLocation relativeLoc in neighborhood)
                    {
                        Site neighbor = site.GetNeighbor(relativeLoc);
                        if (neighbor != null && neighbor.IsActive)
                        {
                            if (mapName == "")
                            {
                                if (SiteVars.DerivedVars[neighbor][varName] > 0)
                                {
                                    targetNeighborCells++;
                                }
                            }
                            else if (SiteVars.LocalVars[neighbor][mapName] == mapCode)
                            {
                                targetNeighborCells++;
                            }
                            totalNeighborCells++;
                        }
                    }
                    double pctValue = 100.0 * (double)targetNeighborCells / (double)totalNeighborCells;

                    // Calculate transformation
                    double transformValue = pctValue;
                    if (neighborVar.Transform.Equals("log10", StringComparison.OrdinalIgnoreCase))
                    //if (neighborVar.Transform == "log10")
                    {
                        transformValue = Math.Log10(pctValue + 1);
                    }
                    else if (neighborVar.Transform.Equals("ln", StringComparison.OrdinalIgnoreCase))
                    //else if (neighborVar.Transform == "ln")
                    {
                        transformValue = Math.Log(pctValue + 1);
                    }

                    // Write Site Variable
                    SiteVars.NeighborVars[site][neighborVar.Name] = (float)transformValue;
                }
            }

            // Calculate Climate Variables

            foreach (IClimateVariableDefinition climateVar in climateVarDefs)
            {
                Dictionary <IEcoregion, Dictionary <string, double> > ecoClimateVars = new Dictionary <IEcoregion, Dictionary <string, double> >();

                string varName       = climateVar.Name;
                string climateLibVar = climateVar.ClimateLibVariable;
                string climateYear   = climateVar.Year;
                int    minMonth      = climateVar.MinMonth;
                int    maxMonth      = climateVar.MaxMonth;
                string transform     = climateVar.Transform;

                int currentYear = PlugIn.ModelCore.CurrentTime;
                int actualYear  = currentYear;

                int firstActiveEco = 0;
                foreach (IEcoregion ecoregion in modelCore.Ecoregions)
                {
                    if (ecoregion.Active)
                    {
                        firstActiveEco = ecoregion.Index;
                        break;
                    }
                }
                if (Climate.Future_MonthlyData != null)
                {
                    AnnualClimate_Monthly AnnualWeather = Climate.Future_MonthlyData[Climate.Future_MonthlyData.Keys.Min()][firstActiveEco];
                    int maxSpinUpYear = Climate.Spinup_MonthlyData.Keys.Max();

                    if (PlugIn.ModelCore.CurrentTime > 0)
                    {
                        currentYear = (PlugIn.ModelCore.CurrentTime - 1) + Climate.Future_MonthlyData.Keys.Min();
                        if (climateYear == "prev")
                        {
                            if (Climate.Future_MonthlyData.ContainsKey(currentYear - 1))
                            {
                                AnnualWeather = Climate.Future_MonthlyData[currentYear - 1][firstActiveEco];
                            }
                            else
                            {
                                AnnualWeather = Climate.Spinup_MonthlyData[maxSpinUpYear][firstActiveEco];
                            }
                        }
                        else
                        {
                            AnnualWeather = Climate.Future_MonthlyData[currentYear][firstActiveEco];
                        }
                    }
                    if (PlugIn.ModelCore.CurrentTime == 0)
                    {
                        if (climateYear == "prev")
                        {
                            AnnualWeather = Climate.Spinup_MonthlyData[maxSpinUpYear - 1][firstActiveEco];
                        }
                        else
                        {
                            AnnualWeather = Climate.Spinup_MonthlyData[maxSpinUpYear][firstActiveEco];
                        }
                    }
                    actualYear = AnnualWeather.Year;
                }
                else
                {
                    if (climateYear == "prev")
                    {
                        actualYear = currentYear - 1;
                    }
                }

                if (climateVar.SourceName == "Library")
                {
                    foreach (IEcoregion ecoregion in modelCore.Ecoregions)
                    {
                        if (ecoregion.Active)
                        {
                            if (!ecoClimateVars.ContainsKey(ecoregion))
                            {
                                ecoClimateVars.Add(ecoregion, new Dictionary <string, double>());
                            }
                            AnnualClimate_Monthly AnnualWeather = Climate.Future_MonthlyData[Climate.Future_MonthlyData.Keys.Min()][ecoregion.Index];
                            int maxSpinUpYear = Climate.Spinup_MonthlyData.Keys.Max();

                            if (PlugIn.ModelCore.CurrentTime == 0)
                            {
                                if (climateYear == "prev")
                                {
                                    AnnualWeather = Climate.Spinup_MonthlyData[maxSpinUpYear - 1][ecoregion.Index];
                                }
                                else
                                {
                                    AnnualWeather = Climate.Spinup_MonthlyData[maxSpinUpYear][ecoregion.Index];
                                }
                            }
                            else if (climateYear == "prev")
                            {
                                if (!Climate.Future_MonthlyData.ContainsKey(currentYear - 1))
                                {
                                    AnnualWeather = Climate.Spinup_MonthlyData[maxSpinUpYear][ecoregion.Index];
                                }
                                else
                                {
                                    AnnualWeather = Climate.Future_MonthlyData[currentYear - 1][ecoregion.Index];
                                }
                            }
                            else
                            {
                                AnnualWeather = Climate.Future_MonthlyData[currentYear][ecoregion.Index];
                            }

                            double monthTotal = 0;
                            int    monthCount = 0;
                            double varValue   = 0;
                            var    monthRange = Enumerable.Range(minMonth, (maxMonth - minMonth) + 1);
                            foreach (int monthIndex in monthRange)
                            {
                                //if (climateVar.ClimateLibVariable == "PDSI")
                                //{

                                //double monthPDSI = PDSI_Calculator.PDSI_Monthly[monthIndex-1];
                                //   varValue = monthPDSI;
                                //}
                                if (climateVar.ClimateLibVariable.Equals("precip", StringComparison.OrdinalIgnoreCase))
                                //if (climateVar.ClimateLibVariable == "Precip")
                                {
                                    double monthPrecip = AnnualWeather.MonthlyPrecip[monthIndex - 1];
                                    varValue = monthPrecip * 10.0; //Convert cm to mm
                                }
                                else if (climateVar.ClimateLibVariable.Equals("temp", StringComparison.OrdinalIgnoreCase))
                                //else if (climateVar.ClimateLibVariable == "Temp")
                                {
                                    double monthTemp = AnnualWeather.MonthlyTemp[monthIndex - 1];
                                    varValue = monthTemp;
                                }
                                else
                                {
                                    string mesg = string.Format("Climate variable {0} is {1}; expected 'precip' or 'temp'.", climateVar.Name, climateVar.ClimateLibVariable);
                                    throw new System.ApplicationException(mesg);
                                }
                                monthTotal += varValue;
                                monthCount++;
                            }
                            double avgValue       = monthTotal / (double)monthCount;
                            double transformValue = avgValue;
                            if (transform.Equals("log10", StringComparison.OrdinalIgnoreCase))
                            //if (transform == "Log10")
                            {
                                transformValue = Math.Log10(avgValue + 1);
                            }
                            else if (transform.Equals("ln", StringComparison.OrdinalIgnoreCase))
                            //else if (transform == "ln")
                            {
                                transformValue = Math.Log(avgValue + 1);
                            }
                            if (!ecoClimateVars[ecoregion].ContainsKey(varName))
                            {
                                ecoClimateVars[ecoregion].Add(varName, 0.0);
                            }
                            ecoClimateVars[ecoregion][varName] = transformValue;
                        }
                    }

                    foreach (Site site in modelCore.Landscape.AllSites)
                    {
                        IEcoregion ecoregion    = PlugIn.ModelCore.Ecoregion[site];
                        double     climateValue = 0;
                        if (ecoregion != null)
                        {
                            climateValue = ecoClimateVars[ecoregion][varName];
                        }
                        // Write Site Variable
                        SiteVars.ClimateVars[site][varName] = (float)climateValue;
                    }
                }
                else
                {
                    double monthTotal = 0;
                    int    monthCount = 0;
                    double varValue   = 0;
                    var    monthRange = Enumerable.Range(minMonth, (maxMonth - minMonth) + 1);
                    foreach (int monthIndex in monthRange)
                    {
                        string    selectString = "Year = '" + actualYear + "' AND Month = '" + monthIndex + "'";
                        DataRow[] rows         = parameters.ClimateDataTable.Select(selectString);
                        if (rows.Length == 0)
                        {
                            string mesg = string.Format("Climate data is empty. No record exists for variable {0} in year {1}.", climateVar.Name, actualYear);
                            if (actualYear == 0)
                            {
                                mesg = mesg + "  Note that if using the options Monthly_AverageAllYears or Daily_AverageAllYears you should provide average values for climate variables listed as Year 0.";
                            }
                            throw new System.ApplicationException(mesg);
                        }
                        foreach (DataRow row in rows)
                        {
                            varValue = Convert.ToDouble(row[climateVar.ClimateLibVariable]);
                        }
                        monthTotal += varValue;
                        monthCount++;
                    }
                    double avgValue       = monthTotal / (double)monthCount;
                    double transformValue = avgValue;
                    if (transform.Equals("log10", StringComparison.OrdinalIgnoreCase))
                    //if (transform == "Log10")
                    {
                        transformValue = Math.Log10(avgValue + 1);
                    }
                    else if (transform.Equals("ln", StringComparison.OrdinalIgnoreCase))
                    //else if (transform == "ln")
                    {
                        transformValue = Math.Log(avgValue + 1);
                    }
                    foreach (Site site in modelCore.Landscape.AllSites)
                    {
                        SiteVars.ClimateVars[site][varName] = (float)transformValue;
                    }
                }
            }


            Dictionary <string, float>[] ecoregionAvgValues = new Dictionary <string, float> [ModelCore.Ecoregions.Count];
            Dictionary <string, float>   landscapeAvgValues = new Dictionary <string, float>();

            int[] activeSiteCount = new int[ModelCore.Ecoregions.Count];
            foreach (IEcoregion ecoregion in ModelCore.Ecoregions)
            {
                ecoregionAvgValues[ecoregion.Index] = new Dictionary <string, float>();
                activeSiteCount[ecoregion.Index]    = 0;
            }
            foreach (ActiveSite site in ModelCore.Landscape)
            {
                IEcoregion ecoregion = ModelCore.Ecoregion[site];
                activeSiteCount[ecoregion.Index]++;
            }

            // Calculate Species Models
            foreach (IModelDefinition model in modelDefs)
            {
                float [] ecoregionSum = new float[ModelCore.Ecoregions.Count];
                float    landscapeSum = 0;

                foreach (Site site in modelCore.Landscape.AllSites)
                {
                    IEcoregion ecoregion    = ModelCore.Ecoregion[site];
                    double     modelPredict = 0;
                    int        paramIndex   = 0;
                    foreach (string parameter in model.Parameters)
                    {
                        string paramType  = model.ParamTypes[paramIndex];
                        double paramValue = model.Values[paramIndex];
                        if (paramType.Equals("int", StringComparison.OrdinalIgnoreCase))
                        //if (paramType == "int")
                        {
                            modelPredict += paramValue;
                        }
                        else if (paramType.Equals("neighbor", StringComparison.OrdinalIgnoreCase))
                        //else if (paramType == "neighbor")
                        {
                            double modelValue = SiteVars.NeighborVars[site][parameter] * paramValue;
                            modelPredict += modelValue;
                        }
                        else if (paramType.Equals("climate", StringComparison.OrdinalIgnoreCase))
                        //else if (paramType == "climate")
                        {
                            double modelValue = SiteVars.ClimateVars[site][parameter] * paramValue;
                            modelPredict += modelValue;
                        }
                        else if (paramType.Equals("biomass", StringComparison.OrdinalIgnoreCase))
                        //else if (paramType =="biomass")
                        {
                            double modelValue = Util.ComputeBiomass(SiteVars.Cohorts[site]) * paramValue;
                            modelPredict += modelValue;
                        }
                        else
                        {
                            string mesg = string.Format("For model {0}, parameter {1} has parameter type {2}; expected 'int', 'neighbor','climate' or 'biomass'.", model.Name, parameter, paramType);
                            throw new System.ApplicationException(mesg);
                        }

                        paramIndex++;
                    }
                    // Back-transform model prediction
                    float finalPredict = (float)Math.Exp(modelPredict);
                    // Write Site Variable
                    SiteVars.SpeciesModels[site][model.Name] = (float)finalPredict;
                    if (site.IsActive)
                    {
                        ecoregionSum[ecoregion.Index] += finalPredict;
                        landscapeSum += finalPredict;
                    }
                }
                foreach (IEcoregion ecoregion in ModelCore.Ecoregions)
                {
                    //ecoregionAvgValues[ecoregion.Index].Add(model.Name, 0);
                    ecoregionAvgValues[ecoregion.Index][model.Name] = ecoregionSum[ecoregion.Index] / activeSiteCount[ecoregion.Index];
                }
                landscapeAvgValues[model.Name] = landscapeSum / ModelCore.Landscape.ActiveSiteCount;
            }


            foreach (IModelDefinition model in modelDefs)
            {
                habitatLog.Write("{0},", ModelCore.CurrentTime);
                habitatLog.Write("{0},", model.Name);
                habitatLog.Write("{0}", landscapeAvgValues[model.Name]);
                foreach (IEcoregion ecoregion in ModelCore.Ecoregions)
                {
                    habitatLog.Write(",{0}", ecoregionAvgValues[ecoregion.Index][model.Name]);
                }
                habitatLog.WriteLine("");
            }


            /*
             * foreach (IModelDefinition model in modelDefs)
             * {
             *   foreach (IEcoregion ecoregion in ModelCore.Ecoregions)
             *   {
             *       habitatLog.Clear();
             *       SpeciesHabitatLog shl = new SpeciesHabitatLog();
             *       shl.Time = ModelCore.CurrentTime;
             *       shl.Ecoregion = ecoregion.Name;
             *       shl.EcoregionIndex = ecoregion.Index;
             *       shl.NumSites = activeSiteCount[ecoregion.Index];
             *       //shl.SppHabitat[ecoregion.Index][model.Name] = avgHabitat[ecoregion.Index][;
             *   }
             * }
             * */

            // Ouput Maps
            if (!(parameters.LocalVarMapFileNames == null))
            {
                //----- Write LocalVar maps --------
                foreach (MapDefinition localVar in parameters.ReclassMaps)
                {
                    string localVarPath = MapFileNames.ReplaceTemplateVars(parameters.LocalVarMapFileNames, localVar.Name, PlugIn.ModelCore.CurrentTime);
                    using (IOutputRaster <BytePixel> outputRaster = modelCore.CreateRaster <BytePixel>(localVarPath, modelCore.Landscape.Dimensions))
                    {
                        BytePixel pixel = outputRaster.BufferPixel;
                        foreach (Site site in PlugIn.ModelCore.Landscape.AllSites)
                        {
                            if (site.IsActive)
                            {
                                pixel.MapCode.Value = (byte)(SiteVars.LocalVars[site][localVar.Name] + 1);
                            }
                            else
                            {
                                //  Inactive site
                                pixel.MapCode.Value = 0;
                            }
                            outputRaster.WriteBufferPixel();
                        }
                    }
                }
            }
            if (!(parameters.NeighborMapFileNames == null))
            {
                //----- Write LocalVar maps --------
                foreach (NeighborVariableDefinition neighborVar in parameters.NeighborVars)
                {
                    string neighborVarPath = NeighborMapFileNames.ReplaceTemplateVars(parameters.NeighborMapFileNames, neighborVar.Name, PlugIn.ModelCore.CurrentTime);
                    using (IOutputRaster <ShortPixel> outputRaster = modelCore.CreateRaster <ShortPixel>(neighborVarPath, modelCore.Landscape.Dimensions))
                    {
                        ShortPixel pixel = outputRaster.BufferPixel;
                        foreach (Site site in PlugIn.ModelCore.Landscape.AllSites)
                        {
                            if (site.IsActive)
                            {
                                pixel.MapCode.Value = (short)(System.Math.Round(SiteVars.NeighborVars[site][neighborVar.Name] * 100.0));
                            }
                            else
                            {
                                //  Inactive site
                                pixel.MapCode.Value = 0;
                            }
                            outputRaster.WriteBufferPixel();
                        }
                    }
                }
            }
            if (!(parameters.ClimateMapFileNames == null))
            {
                //----- Write LocalVar maps --------
                foreach (ClimateVariableDefinition climateVar in parameters.ClimateVars)
                {
                    string climateVarPath = ClimateMapFileNames.ReplaceTemplateVars(parameters.ClimateMapFileNames, climateVar.Name, PlugIn.ModelCore.CurrentTime);
                    using (IOutputRaster <ShortPixel> outputRaster = modelCore.CreateRaster <ShortPixel>(climateVarPath, modelCore.Landscape.Dimensions))
                    {
                        ShortPixel pixel = outputRaster.BufferPixel;
                        foreach (Site site in PlugIn.ModelCore.Landscape.AllSites)
                        {
                            if (site.IsActive)
                            {
                                pixel.MapCode.Value = (short)(System.Math.Round(SiteVars.ClimateVars[site][climateVar.Name] * 100.0));
                            }
                            else
                            {
                                //  Inactive site
                                pixel.MapCode.Value = 0;
                            }
                            outputRaster.WriteBufferPixel();
                        }
                    }
                }
            }
            if (!(parameters.SpeciesMapFileNames == null))
            {
                //----- Write Species Model maps --------
                foreach (ModelDefinition sppModel in parameters.Models)
                {
                    string sppModelPath = SpeciesMapFileNames.ReplaceTemplateVars(parameters.SpeciesMapFileNames, sppModel.Name, PlugIn.ModelCore.CurrentTime);
                    using (IOutputRaster <ShortPixel> outputRaster = modelCore.CreateRaster <ShortPixel>(sppModelPath, modelCore.Landscape.Dimensions))
                    {
                        ShortPixel pixel = outputRaster.BufferPixel;
                        foreach (Site site in PlugIn.ModelCore.Landscape.AllSites)
                        {
                            if (site.IsActive)
                            {
                                pixel.MapCode.Value = (short)System.Math.Round(SiteVars.SpeciesModels[site][sppModel.Name] * 100.0);
                                //pixel.MapCode.Value = (short)System.Math.Round(SiteVars.SpeciesModels[site][sppModel.Name]);
                            }
                            else
                            {
                                //  Inactive site
                                pixel.MapCode.Value = 0;
                            }
                            outputRaster.WriteBufferPixel();
                        }
                    }
                }
            }
        }