Ejemplo n.º 1
0
        public void EnsureServicesResolve()
        {
            var simulations = new Simulations()
            {
                Children = new List <IModel>()
                {
                    new DataStore(),
                    new Simulation()
                    {
                        Children = new List <IModel>()
                        {
                            new Clock(),
                            new MockSummary(),
                            new ModelWithServices()
                        }
                    }
                }
            };

            simulations.ParentAllDescendants();

            var links = new Links();

            links.Resolve(simulations.Children[1], true);

            var modelWithServices = simulations.Children[1].Children[2] as ModelWithServices;

            Assert.IsNotNull(modelWithServices.storage);
            Assert.IsNotNull(modelWithServices.locator);
            Assert.IsNotNull(modelWithServices.events);
        }
Ejemplo n.º 2
0
        public void TestSimNameRegex()
        {
            string models = typeof(IModel).Assembly.Location;
            IModel sim1   = Utilities.GetRunnableSim().Children[1];

            sim1.Name = "sim1";

            IModel sim2 = Utilities.GetRunnableSim().Children[1];

            sim2.Name = "sim2";

            IModel sim3 = Utilities.GetRunnableSim().Children[1];

            sim3.Name = "simulation3";

            IModel sim4 = Utilities.GetRunnableSim().Children[1];

            sim4.Name = "Base";

            Simulations sims = Simulations.Create(new[] { sim1, sim2, sim3, sim4, new DataStore() });

            sims.ParentAllDescendants();

            string apsimxFileName = Path.ChangeExtension(Path.GetTempFileName(), ".apsimx");

            sims.Write(apsimxFileName);

            // Need to quote the regex on unix systems.
            string args;

            args = @"/Verbose /SimulationNameRegexPattern:sim\d";

            string stdout = Utilities.RunModels(sims, args);

            Assert.True(stdout.Contains("sim1"));
            Assert.True(stdout.Contains("sim2"));
            Assert.False(stdout.Contains("simulation3"));
            Assert.False(stdout.Contains("Base"));

            args   = @"/Verbose /SimulationNameRegexPattern:sim1";
            stdout = Utilities.RunModels(sims, args);

            Assert.True(stdout.Contains("sim1"));
            Assert.False(stdout.Contains("sim2"));
            Assert.False(stdout.Contains("simulation3"));
            Assert.False(stdout.Contains("Base"));

            args   = @"/Verbose /SimulationNameRegexPattern:(simulation3)|(Base)";
            stdout = Utilities.RunModels(sims, args);

            Assert.False(stdout.Contains("sim1"));
            Assert.False(stdout.Contains("sim2"));
            Assert.True(stdout.Contains("simulation3"));
            Assert.True(stdout.Contains("Base"));
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Generates an .apsimx file containing replacements model (if it
        /// exists), a datastore, and all children of this model. Saves the
        /// file to disk and returns the absolute path to the file.
        /// </summary>
        private string GenerateApsimXFile()
        {
            Simulations rootNode       = FindAncestor <Simulations>();
            string      apsimxFileName = GetTempFileName($"apsimx_file_{id}", ".apsimx");

            Simulations sims = new Simulations();

            sims.Children.AddRange(Children.Select(c => Apsim.Clone(c)));
            sims.Children.RemoveAll(c => c is IDataStore);

            IModel replacements = this.FindInScope <Replacements>();

            if (replacements != null && !sims.Children.Any(c => c is Replacements))
            {
                sims.Children.Add(Apsim.Clone(replacements));
            }

            // Search for IDataStore, not DataStore - to allow for StorageViaSockets.
            IDataStore storage      = this.FindInScope <IDataStore>();
            IModel     newDataStore = new DataStore();

            if (storage != null && storage is IModel m)
            {
                newDataStore.Children.AddRange(m.Children.Select(c => Apsim.Clone(c)));
            }

            sims.Children.Add(newDataStore);
            sims.ParentAllDescendants();

            sims.Write(apsimxFileName);

            string originalFile = rootNode?.FileName;

            if (string.IsNullOrEmpty(originalFile))
            {
                originalFile = storage?.FileName;
            }

            // Copy files across.
            foreach (IReferenceExternalFiles fileReference in sims.FindAllDescendants <IReferenceExternalFiles>().Cast <IReferenceExternalFiles>())
            {
                foreach (string file in fileReference.GetReferencedFileNames())
                {
                    string absoluteFileName = PathUtilities.GetAbsolutePath(file, originalFile);
                    string fileName         = Path.GetFileName(absoluteFileName);
                    string newPath          = Path.GetDirectoryName(sims.FileName);
                    File.Copy(absoluteFileName, Path.Combine(newPath, fileName), true);
                }
            }

            return(apsimxFileName);
        }
Ejemplo n.º 4
0
        public void EnsureReplacementsNodeWorks()
        {
            var simulations = new Simulations()
            {
                Children = new List <IModel>()
                {
                    new Replacements()
                    {
                        Name     = "Replacements",
                        Children = new List <IModel>()
                        {
                            new MockWeather()
                            {
                                Name      = "Weather",
                                MaxT      = 2,
                                StartDate = DateTime.MinValue
                            }
                        }
                    },

                    new Simulation()
                    {
                        Name     = "BaseSimulation",
                        Children = new List <IModel>()
                        {
                            new MockWeather()
                            {
                                Name      = "Weather",
                                MaxT      = 1,
                                StartDate = DateTime.MinValue
                            },
                        }
                    }
                }
            };

            simulations.ParentAllDescendants();

            var sim = simulations.Children[1] as Simulation;
            var simulationDescription = new SimulationDescription(sim);

            var newSim  = simulationDescription.ToSimulation();
            var weather = newSim.Children[0] as MockWeather;

            Assert.AreEqual(weather.MaxT, 2);

            // Make sure any property overrides happens after a model replacement.
            simulationDescription.AddOverride(new PropertyReplacement("Weather.MaxT", 3));
            newSim  = simulationDescription.ToSimulation();
            weather = newSim.Children[0] as MockWeather;
            Assert.AreEqual(weather.MaxT, 3);
        }
Ejemplo n.º 5
0
        public void EnsureReplacementWithInvalidNameDoesntMatch()
        {
            var simulations = new Simulations()
            {
                Children = new List <IModel>()
                {
                    new Folder()
                    {
                        Name     = "Replacements",
                        Children = new List <IModel>()
                        {
                            new MockWeather()
                            {
                                Name      = "Dummy name",
                                MaxT      = 2,
                                StartDate = DateTime.MinValue
                            }
                        }
                    },

                    new Simulation()
                    {
                        Name     = "BaseSimulation",
                        Children = new List <IModel>()
                        {
                            new MockWeather()
                            {
                                Name      = "Weather",
                                MaxT      = 1,
                                StartDate = DateTime.MinValue
                            },
                        }
                    }
                }
            };

            simulations.ParentAllDescendants();

            var sim = simulations.Children[1] as Simulation;
            var simulationDescription = new SimulationDescription(sim);

            var newSim  = simulationDescription.ToSimulation();
            var weather = newSim.Children[0] as MockWeather;

            // Name ('Dummy name') didn't match so property should still be 1.
            Assert.AreEqual(weather.MaxT, 1);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Returns a lightweight skeleton simulation which can be run.
        /// </summary>
        public static Simulations GetRunnableSim()
        {
            Simulations sims = new Simulations()
            {
                FileName = Path.ChangeExtension(Path.GetTempFileName(), ".apsimx"),
                Children = new List <IModel>()
                {
                    new DataStore(),
                    new Simulation()
                    {
                        Children = new List <IModel>()
                        {
                            new Clock()
                            {
                                StartDate = new DateTime(2017, 1, 1),
                                EndDate   = new DateTime(2017, 1, 10) // January 10
                            },
                            new Summary(),
                            new Zone()
                            {
                                Area     = 1,
                                Children = new List <IModel>()
                                {
                                    new Models.Report()
                                    {
                                        VariableNames = new string[]
                                        {
                                            "[Clock].Today.DayOfYear as n"
                                        },
                                        EventNames = new string[]
                                        {
                                            "[Clock].DoReport"
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            };

            sims.ParentAllDescendants();
            sims.Write(sims.FileName);
            return(sims);
        }
Ejemplo n.º 7
0
        public void EnsureScopedPostSimulationToolsAreRun()
        {
            Simulation sim0 = new Simulation()
            {
                Name     = "s0",
                Children = new List <IModel>()
                {
                    new MockClock(),
                    new MockSummary(),
                    new PostSimToolWhichThrows()
                }
            };
            Simulation sim1 = sim0.Clone();

            sim1.Name = "s1";

            Simulations sims = new Simulations()
            {
                Children = new List <IModel>()
                {
                    new MockStorage()
                    {
                        Children = new List <IModel>()
                        {
                            new PostSimToolWhichThrows()
                        }
                    },
                    sim0,
                    sim1
                }
            };

            sims.ParentAllDescendants();

            Runner           runner = new Runner(sim1);
            List <Exception> errors = runner.Run();

            // We ran sim1 only. Therefore two post-simulation tools
            // should have been run (the one under the simulation and the
            // one under the datastore).
            Assert.AreEqual(2, errors.Count);
        }
Ejemplo n.º 8
0
        public void TestSimNameRegex()
        {
            string models = typeof(IModel).Assembly.Location;
            IModel sim1   = Utilities.GetRunnableSim().Children[1];

            sim1.Name = "sim1";

            IModel sim2 = Utilities.GetRunnableSim().Children[1];

            sim2.Name = "sim2";

            IModel sim3 = Utilities.GetRunnableSim().Children[1];

            sim3.Name = "simulation3";

            IModel sim4 = Utilities.GetRunnableSim().Children[1];

            sim4.Name = "Base";

            Simulations sims = Simulations.Create(new[] { sim1, sim2, sim3, sim4, new DataStore() });

            sims.ParentAllDescendants();

            string apsimxFileName = Path.ChangeExtension(Path.GetTempFileName(), ".apsimx");

            sims.Write(apsimxFileName);

            // Need to quote the regex on unix systems.
            string args;

            if (ProcessUtilities.CurrentOS.IsWindows)
            {
                args = $@"{apsimxFileName} /Verbose /SimulationNameRegexPattern:sim\d";
            }
            else
            {
                args = $@"{apsimxFileName} /Verbose '/SimulationNameRegexPattern:sim\d'";
            }

            ProcessUtilities.ProcessWithRedirectedOutput proc = new ProcessUtilities.ProcessWithRedirectedOutput();
            proc.Start(models, args, Directory.GetCurrentDirectory(), true);
            proc.WaitForExit();

            Assert.Null(proc.StdErr);
            Assert.True(proc.StdOut.Contains("sim1"));
            Assert.True(proc.StdOut.Contains("sim2"));
            Assert.False(proc.StdOut.Contains("simulation3"));
            Assert.False(proc.StdOut.Contains("Base"));

            args = $@"{apsimxFileName} /Verbose /SimulationNameRegexPattern:sim1";
            proc = new ProcessUtilities.ProcessWithRedirectedOutput();
            proc.Start(models, args, Directory.GetCurrentDirectory(), true);
            proc.WaitForExit();

            Assert.Null(proc.StdErr);
            Assert.True(proc.StdOut.Contains("sim1"));
            Assert.False(proc.StdOut.Contains("sim2"));
            Assert.False(proc.StdOut.Contains("simulation3"));
            Assert.False(proc.StdOut.Contains("Base"));

            args = $@"{apsimxFileName} /Verbose /SimulationNameRegexPattern:(simulation3)|(Base)";
            proc = new ProcessUtilities.ProcessWithRedirectedOutput();
            proc.Start(models, args, Directory.GetCurrentDirectory(), true);
            proc.WaitForExit();

            Assert.Null(proc.StdErr);
            Assert.False(proc.StdOut.Contains("sim1"));
            Assert.False(proc.StdOut.Contains("sim2"));
            Assert.True(proc.StdOut.Contains("simulation3"));
            Assert.True(proc.StdOut.Contains("Base"));
        }
Ejemplo n.º 9
0
        public void TestManagerParameterChanges()
        {
            Manager m = new Manager()
            {
                Name = "Manager",
                Code = "using System; namespace Models { using Core; [Serializable] public class Script : Models.Core.Model { [Description(\"x\")] public string X { get; set; } } }"
            };
            Simulations sims = new Simulations()
            {
                Children = new List <IModel>()
                {
                    new DataStore(),
                    new Experiment()
                    {
                        Name     = "expt",
                        Children = new List <IModel>()
                        {
                            new Factors()
                            {
                                Children = new List <IModel>()
                                {
                                    new Factor()
                                    {
                                        Name          = "x",
                                        Specification = "[Manager].Script.X = 1"
                                    }
                                }
                            },
                            new Simulation()
                            {
                                Name     = "sim",
                                Children = new List <IModel>()
                                {
                                    new Clock()
                                    {
                                        StartDate = new DateTime(2020, 1, 1),
                                        EndDate   = new DateTime(2020, 1, 2),
                                        Name      = "Clock"
                                    },
                                    new Summary(),
                                    m
                                }
                            }
                        }
                    }
                }
            };

            sims.ParentAllDescendants();
            m.OnCreated();
            Runner runner = new Runner(sims);
            string temp   = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());

            try
            {
                IEnumerable <string> files = GenerateApsimXFiles.Generate(runner, 1, temp, _ => {});
                Assert.AreEqual(1, files.Count());
                string file = files.First();
                sims = FileFormat.ReadFromFile <Simulations>(file, e => throw e, false);
                Assert.AreEqual("1", sims.FindByPath("[Manager].Script.X").Value);
            }
            finally
            {
                if (Directory.Exists(temp))
                {
                    Directory.Delete(temp, true);
                }
            }
        }