예제 #1
0
        //---------------------------------------------------------------------

        private Scenario LoadScenario(string path)
        {
            UI.WriteLine("Loading scenario from file \"{0}\" ...", path);
            ScenarioParser parser = new ScenarioParser(plugInDataset);

            return(Data.Load <Scenario>(path, parser));
        }
예제 #2
0
        //---------------------------------------------------------------------

        private static IScenario LoadScenario(string path)
        {
            UI.WriteLine("Loading scenario from file \"{0}\" ...", path);
            ScenarioParser parser = new ScenarioParser();

            return(Data.Load <IScenario>(path, parser));
        }
예제 #3
0
        public static int Main(string[] args)
        {
            try {
                UI.TextWriter = Console.Out;

                Version version = Assembly.GetExecutingAssembly().GetName().Version;
                string  release = "";
                if (version.Revision >= 2000)
                {
                    release = string.Format(" (beta release {0})", version.Revision - 2000);
                }
                else if (version.Revision >= 1000)
                {
                    release = string.Format(" (alpha release {0})", version.Revision - 1000);
                }
                UI.WriteLine("Landis-II {0}.{1}{2}", version.Major, version.Minor, release);
                UI.WriteLine("Copyright 2004-2005 University of Wisconsin");
                UI.WriteLine();

                if (args.Length == 0)
                {
                    UI.WriteLine("Error: No scenario file specified.");
                    return(1);
                }
                if (args.Length > 1)
                {
                    UI.WriteLine("Error: Extra argument(s) on command line:");
                    StringBuilder argsList = new StringBuilder();
                    argsList.Append(" ");
                    for (int i = 1; i < args.Length; ++i)
                    {
                        argsList.AppendFormat(" {0}", args[i]);
                    }
                    UI.WriteLine(argsList.ToString());
                    return(1);
                }

                Landis.Model.Run(args[0]);
                return(0);
            }
            catch (ApplicationException exc) {
                UI.WriteLine(exc.Message);
                return(1);
            }
            catch (Exception exc) {
                UI.WriteLine("Internal error occurred within the program:");
                UI.WriteLine("  {0}", exc.Message);
                if (exc.InnerException != null)
                {
                    UI.WriteLine("  {0}", exc.InnerException.Message);
                }
                UI.WriteLine();
                UI.WriteLine("Stack trace:");
                UI.WriteLine(exc.StackTrace);
                return(1);
            }
        }
예제 #4
0
        public static int Main(string[] args)
        {
            try {
                UI.TextWriter = Console.Out;

                Assembly       assembly       = Assembly.GetExecutingAssembly();
                VersionRelease versionRelease = new VersionRelease(assembly);
                UI.WriteLine("Landis-II {0}", versionRelease);
                UI.WriteLine("Copyright 2004-2005 University of Wisconsin");
                UI.WriteLine();

                if (args.Length == 0)
                {
                    UI.WriteLine("Error: No scenario file specified.");
                    return(1);
                }
                if (args.Length > 1)
                {
                    UI.WriteLine("Error: Extra argument(s) on command line:");
                    StringBuilder argsList = new StringBuilder();
                    argsList.Append(" ");
                    for (int i = 1; i < args.Length; ++i)
                    {
                        argsList.AppendFormat(" {0}", args[i]);
                    }
                    UI.WriteLine(argsList.ToString());
                    return(1);
                }

                string                 appDir    = Application.Directory;
                PlugIns.Dataset        plugIns   = new PlugIns.Dataset(Path.Combine(appDir, "plug-ins.xml"));
                RasterIO.DriverManager driverMgr = new RasterIO.DriverManager(Path.Combine(appDir, "raster-drivers.xml"));
                Model model = new Model(plugIns, driverMgr);
                model.Run(args[0]);
                return(0);
            }
            catch (ApplicationException exc) {
                UI.WriteLine(exc.Message);
                return(1);
            }
            catch (Exception exc) {
                UI.WriteLine("Internal error occurred within the program:");
                UI.WriteLine("  {0}", exc.Message);
                if (exc.InnerException != null)
                {
                    UI.WriteLine("  {0}", exc.InnerException.Message);
                }
                UI.WriteLine();
                UI.WriteLine("Stack trace:");
                UI.WriteLine(exc.StackTrace);
                return(1);
            }
        }
예제 #5
0
        //---------------------------------------------------------------------

        private void InitializeRandomNumGenerator(uint?seed)
        {
            if (seed.HasValue)
            {
                Landis.Util.Random.Initialize(seed.Value);
            }
            else
            {
                uint generatedSeed = Landis.Util.Random.GenerateSeed();
                Landis.Util.Random.Initialize(generatedSeed);
                UI.WriteLine("Initialized random number generator with seed = {0:#,##0}", generatedSeed);
            }
        }
예제 #6
0
        //---------------------------------------------------------------------

        private PlugIn[] LoadAndInitPlugIns(PlugInAndInitFile[] plugIns)
        {
            PlugIn[] loadedPlugIns = new PlugIn[plugIns.Length];
            foreach (int i in Indexes.Of(plugIns))
            {
                PlugInAndInitFile plugInAndInitFile = plugIns[i];
                UI.WriteLine("Loading {0} plug-in ...", plugInAndInitFile.Info.Name);
                PlugIn loadedPlugIn = Loader.Load <PlugIn>(plugInAndInitFile.Info);
                loadedPlugIn.Initialize(plugInAndInitFile.InitFile, this);
                loadedPlugIns[i] = loadedPlugIn;
                if (loadedPlugIn is PlugIns.I2PhaseInitialization)
                {
                    plugInsWith2PhaseInit.Add((PlugIns.I2PhaseInitialization)loadedPlugIn);
                }
                if (loadedPlugIn is PlugIns.ICleanUp)
                {
                    plugInsWithCleanUp.Add((PlugIns.ICleanUp)loadedPlugIn);
                }
            }
            return(loadedPlugIns);
        }
예제 #7
0
        //---------------------------------------------------------------------

        private static T[] LoadPlugIns <T>(IPlugIn[] plugIns,
                                           int startTime)
            where T : PlugIns.IPlugInWithTimestep
        {
            T[] loadedPlugIns = new T[plugIns.Length];
            foreach (int i in Indexes.Of(plugIns))
            {
                IPlugIn plugIn = plugIns[i];
                UI.WriteLine("Loading {0} plug-in ...", plugIn.Info.Name);
                T loadedPlugIn = PlugIns.Manager.Load <T>(plugIn.Info);
                loadedPlugIn.Initialize(plugIn.InitFile, startTime);
                loadedPlugIns[i] = loadedPlugIn;
                if (loadedPlugIn is PlugIns.I2PhaseInitialization)
                {
                    plugInsWith2PhaseInit.Add((PlugIns.I2PhaseInitialization)loadedPlugIn);
                }
                if (loadedPlugIn is PlugIns.ICleanUp)
                {
                    plugInsWithCleanUp.Add((PlugIns.ICleanUp)loadedPlugIn);
                }
            }
            return(loadedPlugIns);
        }
예제 #8
0
        //---------------------------------------------------------------------

        private void Run(PlugIn plugIn)
        {
            UI.WriteLine("Running {0} ...", plugIn.Name);
            plugIn.Run();
        }
예제 #9
0
        //---------------------------------------------------------------------

        private float?GetCellLength(IMetadata metadata,
                                    ref string cellLengthStr)
        {
            float mapCellLength = 0;

            float cellWidth    = 0;
            bool  hasCellWidth = metadata.TryGetValue(AbscissaResolution.Name,
                                                      ref cellWidth);
            float cellHeight    = 0;
            bool  hasCellHeight = metadata.TryGetValue(OrdinateResolution.Name,
                                                       ref cellHeight);

            if (hasCellWidth && hasCellHeight)
            {
                if (cellWidth != cellHeight)
                {
                    throw CellLengthException("Cell width ({0}) in map is not = to cell height ({1})",
                                              cellWidth, cellHeight);
                }
                if (cellWidth <= 0.0)
                {
                    throw CellLengthException("Cell width ({0}) in map is not > 0",
                                              cellWidth);
                }

                string units = null;
                if (!metadata.TryGetValue(PlanarDistanceUnits.Name, ref units))
                {
                    UI.WriteLine("Map doesn't have units for cell dimensions; assuming meters");
                    units = PlanarDistanceUnits.Meters;
                }
                if (units == PlanarDistanceUnits.Meters)
                {
                    mapCellLength = cellWidth;
                }
                else if (units == PlanarDistanceUnits.InternationalFeet)
                {
                    mapCellLength = (float)(cellWidth * 0.3048);
                }
                else if (units == PlanarDistanceUnits.SurveyFeet)
                {
                    mapCellLength = (float)(cellWidth * (1200.0 / 3937));
                }
                else
                {
                    throw CellLengthException("Map has unknown units for cell dimensions: {0}",
                                              units);
                }
                cellLengthStr = string.Format("{0} meters{1}", mapCellLength,
                                              (units == PlanarDistanceUnits.Meters) ? ""
                                                                                     : string.Format(" ({0} {1})", cellWidth, units));
                return(mapCellLength);
            }
            else if (hasCellWidth && !hasCellHeight)
            {
                throw CellLengthException("Map has cell width (x-dimension) but no height (y-dimension).");
            }
            else if (!hasCellWidth && hasCellHeight)
            {
                throw CellLengthException("Map has cell height (y-dimension) but no width (x-dimension).");
            }
            return(null);
        }
예제 #10
0
        //---------------------------------------------------------------------

        private void ProcessMetadata(IMetadata metadata,
                                     Scenario scenario)
        {
            landscapeMapMetadata = metadata;

            string warning          = "";
            float? mapCellLength    = null;
            string mapCellLengthStr = "";

            try {
                mapCellLength = GetCellLength(metadata, ref mapCellLengthStr);
            }
            catch (ApplicationException exc) {
                string message = exc.Message;
                if (!message.StartsWith(cellLengthExceptionPrefix))
                {
                    throw;
                }
                message = message.Replace(cellLengthExceptionPrefix, "");
                if (scenario.CellLength.HasValue)
                {
                    warning = message;
                }
                else
                {
                    throw new ApplicationException("Error: " + message);
                }
            }

            if (scenario.CellLength.HasValue)
            {
                cellLength = scenario.CellLength.Value;
                UI.WriteLine("Cell length: {0} meters", cellLength);
                if (mapCellLength.HasValue)
                {
                    if (cellLength == mapCellLength.Value)
                    {
                        UI.WriteLine("Cell length in map: {0}", mapCellLengthStr);
                    }
                    else
                    {
                        UI.WriteLine("Warning: Cell length in map: {0}", mapCellLengthStr);
                    }
                }
                else
                {
                    if (warning.Length > 0)
                    {
                        UI.WriteLine("Warning: {0}", warning);
                    }
                    else
                    {
                        UI.WriteLine("Map has no cell length");
                    }
                }
            }
            else
            {
                //    No CellLength parameter in scenario file
                if (mapCellLength.HasValue)
                {
                    UI.WriteLine("Cell length in map: {0}", mapCellLengthStr);
                    cellLength = mapCellLength.Value;
                }
                else
                {
                    string[] message = new string[] {
                        "Error: Ecoregion map doesn't have cell dimensions; therefore, the",
                        "       CellLength parameter must be in the scenario file."
                    };
                    throw new MultiLineException(message);
                }
            }

            cellArea = (float)((cellLength * cellLength) / 10000);
        }
예제 #11
0
        //---------------------------------------------------------------------

        private void LoadEcoregions(string path)
        {
            UI.WriteLine("Loading ecoregions from file \"{0}\" ...", path);
            Ecoregions.DatasetParser parser = new Ecoregions.DatasetParser();
            ecoregions = Data.Load <Ecoregions.IDataset>(path, parser);
        }
예제 #12
0
        //---------------------------------------------------------------------

        private void LoadSpecies(string path)
        {
            UI.WriteLine("Loading species data from file \"{0}\" ...", path);
            Species.DatasetParser parser = new Species.DatasetParser();
            species = Data.Load <Species.IDataset>(path, parser);
        }
예제 #13
0
        //---------------------------------------------------------------------

        /// <summary>
        /// Runs a model scenario.
        /// </summary>
        public void Run(string scenarioPath)
        {
            siteVarRegistry.Clear();

            Scenario scenario = LoadScenario(scenarioPath);

            startTime      = scenario.StartTime;
            endTime        = scenario.EndTime;
            timeSinceStart = 0;
            currentTime    = startTime;
            InitializeRandomNumGenerator(scenario.RandomNumberSeed);

            LoadSpecies(scenario.Species);
            LoadEcoregions(scenario.Ecoregions);

            UI.WriteLine("Initializing landscape from ecoregions map \"{0}\" ...", scenario.EcoregionsMap);
            Ecoregions.Map ecoregionsMap = new Ecoregions.Map(scenario.EcoregionsMap,
                                                              ecoregions,
                                                              rasterDriverMgr);
            ProcessMetadata(ecoregionsMap.Metadata, scenario);
            using (IInputGrid <EcoregionCode> grid = ecoregionsMap.OpenAsInputGrid()) {
                UI.WriteLine("Map dimensions: {0} = {1:#,##0} cell{2}", grid.Dimensions,
                             grid.Count, (grid.Count == 1 ? "" : "s"));
                landscape = new Landscape(grid, scenario.BlockSize.HasValue ? scenario.BlockSize.Value : 1);
            }
            UI.WriteLine("Sites: {0:#,##0} active ({1:p1}), {2:#,##0} inactive ({3:p1})",
                         landscape.ActiveSiteCount, (landscape.Count > 0 ? ((double)landscape.ActiveSiteCount) / landscape.Count : 0),
                         landscape.InactiveSiteCount, (landscape.Count > 0 ? ((double)landscape.InactiveSiteCount) / landscape.Count : 0));

            ecoregionSiteVar = ecoregionsMap.CreateSiteVar(landscape);

            plugInsWith2PhaseInit = new List <PlugIns.I2PhaseInitialization>();
            plugInsWithCleanUp    = new List <PlugIns.ICleanUp>();

            try {
                UI.WriteLine("Loading {0} plug-in ...", scenario.Succession.Info.Name);
                succession = Loader.Load <SuccessionPlugIn>(scenario.Succession.Info);
                succession.Initialize(scenario.Succession.InitFile, this);
                succession.InitializeSites(scenario.InitialCommunities,
                                           scenario.InitialCommunitiesMap);

                PlugIn[] disturbancePlugIns = LoadAndInitPlugIns(scenario.Disturbances);
                PlugIn[] otherPlugIns       = LoadAndInitPlugIns(scenario.OtherPlugIns);

                //    Perform 2nd phase of initialization for those plug-ins
                //    that have it.
                foreach (PlugIns.I2PhaseInitialization plugIn in plugInsWith2PhaseInit)
                {
                    plugIn.InitializePhase2();
                }

                //  Run output plug-ins for TimeSinceStart = 0 (time step 0)
                foreach (PlugIn plugIn in otherPlugIns)
                {
                    if (plugIn.PlugInType.IsMemberOf("output"))
                    {
                        Run(plugIn);
                    }
                }

                //******************// for Rob
                //  Main time loop  //
                //******************//

                for (currentTime++, timeSinceStart++;
                     currentTime <= endTime;
                     currentTime++, timeSinceStart++)
                {
                    bool isSuccTimestep = IsPlugInTimestep(succession);

                    List <PlugIn> distPlugInsToRun;
                    distPlugInsToRun = GetPlugInsToRun(disturbancePlugIns);
                    bool isDistTimestep = distPlugInsToRun.Count > 0;

                    List <PlugIn> otherPlugInsToRun;
                    otherPlugInsToRun = GetPlugInsToRun(otherPlugIns);

                    if (!isSuccTimestep && !isDistTimestep &&
                        otherPlugInsToRun.Count == 0)
                    {
                        continue;
                    }

                    UI.WriteLine("Current time: {0}", currentTime);

                    if (isDistTimestep)
                    {
                        if (scenario.DisturbancesRandomOrder)
                        {
                            Util.Random.Shuffle(distPlugInsToRun);
                        }
                        foreach (PlugIn distPlugIn in distPlugInsToRun)
                        {
                            Run(distPlugIn);
                        }
                    }

                    if (isSuccTimestep || isDistTimestep)
                    {
                        Run(succession);
                    }

                    foreach (PlugIn otherPlugIn in otherPlugInsToRun)
                    {
                        Run(otherPlugIn);
                    }
                }  // main time loop
            }
            finally {
                foreach (PlugIns.ICleanUp plugIn in plugInsWithCleanUp)
                {
                    plugIn.CleanUp();
                }
            }
        }
예제 #14
0
        public static int Main(string[] args)
        {
            try {
                // The log4net section in the application's configuration file
                // requires the environment variable WORKING_DIR be set to the
                // current working directory.
                Environment.SetEnvironmentVariable("WORKING_DIR", Environment.CurrentDirectory);
                log4net.Config.XmlConfigurator.Configure();

                UI.TextWriter = Console.Out;

                string version = GetAppSetting("version");
                if (version == "")
                {
                    throw new Exception("The application setting \"version\" is empty or blank");
                }
                string release = GetAppSetting("release");
                if (release != "")
                {
                    release = string.Format(" ({0})", release);
                }
                UI.WriteLine("LANDIS-II {0}{1}", version, release);

                Assembly assembly = Assembly.GetExecutingAssembly();
                foreach (object attribute in assembly.GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false))
                {
                    UI.WriteLine(((AssemblyCopyrightAttribute)attribute).Copyright);
                }
                UI.WriteLine();

                if (args.Length == 0)
                {
                    UI.WriteLine("Error: No scenario file specified.");
                    return(1);
                }
                if (args.Length > 1)
                {
                    UI.WriteLine("Error: Extra argument(s) on command line:");
                    StringBuilder argsList = new StringBuilder();
                    argsList.Append(" ");
                    for (int i = 1; i < args.Length; ++i)
                    {
                        argsList.AppendFormat(" {0}", args[i]);
                    }
                    UI.WriteLine(argsList.ToString());
                    return(1);
                }

                string                 appDir    = Application.Directory;
                PlugIns.IDataset       plugIns   = PlugIns.Admin.Dataset.LoadOrCreate(PlugIns.Admin.Dataset.DefaultPath);
                RasterIO.DriverManager driverMgr = new RasterIO.DriverManager(Path.Combine(appDir, "raster-drivers.xml"));
                Model model = new Model(plugIns, driverMgr);
                model.Run(args[0]);
                return(0);
            }
            catch (ApplicationException exc) {
                UI.WriteLine(exc.Message);
                return(1);
            }
            catch (Exception exc) {
                UI.WriteLine("Internal error occurred within the program:");
                UI.WriteLine("  {0}", exc.Message);
                if (exc.InnerException != null)
                {
                    UI.WriteLine("  {0}", exc.InnerException.Message);
                }
                UI.WriteLine();
                UI.WriteLine("Stack trace:");
                UI.WriteLine(exc.StackTrace);
                return(1);
            }
        }
예제 #15
0
        //---------------------------------------------------------------------

        /// <summary>
        /// Runs a model scenario.
        /// </summary>
        public static void Run(string scenarioPath)
        {
            //  Initialize plug-ins manager with the default plug-ins
            //	database in the folder where application resides.
            PlugIns.Manager.Initialize(PlugIns.Database.DefaultPath);

            IScenario scenario  = LoadScenario(scenarioPath);
            int       startTime = 1;

            InitializeRandomNumGenerator(scenario.RandomNumberSeed);

            LoadSpecies(scenario.Species);
            LoadEcoregions(scenario.Ecoregions);

            UI.WriteLine("Initializing landscape from ecoregions map \"{0}\" ...", scenario.EcoregionsMap);
            Ecoregions.Map ecoregionsMap = new Ecoregions.Map(scenario.EcoregionsMap,
                                                              Model.Ecoregions);
            ProcessMetadata(ecoregionsMap.Metadata, scenario);
            using (Landscape.IInputGrid <bool> grid = ecoregionsMap.OpenAsInputGrid()) {
                UI.WriteLine("Map dimensions: {0} = {1:#,##0} cell{2}", grid.Dimensions,
                             grid.Count, (grid.Count == 1 ? "" : "s"));
                landscape = new Landscape.Landscape(grid);
            }
            UI.WriteLine("Sites: {0:#,##0} active ({1:p1}), {2:#,##0} inactive ({3:p1})",
                         landscape.ActiveSiteCount, (landscape.Count > 0 ? ((double)landscape.ActiveSiteCount) / landscape.Count : 0),
                         landscape.InactiveSiteCount, (landscape.Count > 0 ? ((double)landscape.InactiveSiteCount) / landscape.Count : 0));
            landscapeMapDims = new RasterIO.Dimensions((int)landscape.Rows,
                                                       (int)landscape.Columns);
            siteVars = new SiteVariables(landscape, ecoregionsMap);

            DisturbedSiteEnumerator disturbedSites = new DisturbedSiteEnumerator(landscape,
                                                                                 SiteVars.Disturbed);

            plugInsWith2PhaseInit = new List <PlugIns.I2PhaseInitialization>();
            plugInsWithCleanUp    = new List <PlugIns.ICleanUp>();
            try {
                //  Load and initialize plug-ins.

                UI.WriteLine("Loading {0} plug-in ...", scenario.Succession.Info.Name);
                succession = PlugIns.Manager.Load <ISuccession>(scenario.Succession.Info);
                succession.Initialize(scenario.Succession.InitFile, startTime);
                succession.InitializeSites(scenario.InitialCommunities,
                                           scenario.InitialCommunitiesMap);

                IDisturbance[] disturbancePlugIns = LoadPlugIns <IDisturbance>(scenario.Disturbances, startTime);
                IOutput[]      outputPlugIns      = LoadPlugIns <IOutput>(scenario.Outputs, startTime);

                //	Perform 2nd phase of initialization for those plug-ins
                //	that have it.
                foreach (PlugIns.I2PhaseInitialization plugIn in plugInsWith2PhaseInit)
                {
                    plugIn.InitializePhase2();
                }

                //  Run those output plug-ins whose next time to run is startTime-1.
                foreach (IOutput outPlugIn in GetPlugInsToRun <IOutput>(outputPlugIns, startTime - 1))
                {
                    outPlugIn.Run(startTime - 1);
                }

                //******************// for Rob
                //  Main time loop  //
                //******************//
                // currentTime (years)
                int endTime = startTime + scenario.Duration - 1;
                for (int currentTime = startTime; currentTime <= endTime; ++currentTime)
                {
                    List <IDisturbance> distPlugInsToRun;
                    distPlugInsToRun = GetPlugInsToRun <IDisturbance>(disturbancePlugIns, currentTime);
                    bool isDistTimestep = distPlugInsToRun.Count > 0;

                    List <IOutput> outPlugInsToRun;
                    outPlugInsToRun = GetPlugInsToRun <IOutput>(outputPlugIns, currentTime);
                    bool isOutTimestep = outPlugInsToRun.Count > 0;

                    bool isSuccTimestep = succession.NextTimeToRun == currentTime;

                    //  If not a succession timestep, a disturance timestep or
                    //  an output timestep, then go to the next timestep.
                    if (!(isSuccTimestep || isDistTimestep || isOutTimestep))
                    {
                        continue;
                    }

                    UI.WriteLine("Current time: {0}", currentTime);

                    if (isDistTimestep)
                    {
                        if (scenario.DisturbancesRandomOrder)
                        {
                            Util.Random.Shuffle(distPlugInsToRun);
                        }
                        foreach (IDisturbance distPlugIn in distPlugInsToRun)
                        {
                            distPlugIn.Run(currentTime);
                        }
                    }

                    if (isSuccTimestep || isDistTimestep)
                    {
                        IEnumerable <MutableActiveSite> sites;
                        if (isSuccTimestep)
                        {
                            sites = Model.Landscape.ActiveSites;
                        }
                        else
                        {
                            sites = disturbedSites;
                        }
                        succession.AgeCohorts(sites, currentTime);
                        succession.ComputeShade(sites);
                        succession.ReproduceCohorts(sites);
                    }

                    //  Run output plug-ins.
                    foreach (IOutput outPlugIn in outPlugInsToRun)
                    {
                        outPlugIn.Run(currentTime);
                    }

                    if (!isSuccTimestep)
                    {
                        SiteVars.Disturbed.ActiveSiteValues = false;
                    }
                }                  // main time loop
            }
            finally {
                foreach (PlugIns.ICleanUp plugIn in plugInsWithCleanUp)
                {
                    plugIn.CleanUp();
                }
            }
        }