Ejemplo n.º 1
0
        public void TestEnumReporting()
        {
            Simulations sims = Utilities.GetRunnableSim();

            IModel  paddock = sims.FindInScope <Zone>();
            Manager script  = new Manager();

            script.Name = "Manager";
            script.Code = @"using System;
using Models.Core;
using Models.PMF;

namespace Models
{
	[Serializable]
	public class Script : Model
	{
		public enum TestEnum
		{
			Red,
			Green,
			Blue
		};

		public TestEnum Value { get; set; }
    }
}";

            paddock.Children.Add(script);
            script.Parent = paddock;
            script.OnCreated();

            Report report = sims.FindInScope <Report>();

            report.VariableNames = new string[]
            {
                "[Manager].Script.Value as x"
            };
            Runner           runner = new Runner(sims);
            List <Exception> errors = runner.Run();

            if (errors != null && errors.Count > 0)
            {
                throw new Exception("Errors while running sims", errors[0]);
            }

            List <string> fieldNames = new List <string>()
            {
                "x"
            };
            IDataStore storage = sims.FindInScope <IDataStore>();
            DataTable  data    = storage.Reader.GetData("Report", fieldNames: fieldNames);

            string[] actual = DataTableUtilities.GetColumnAsStrings(data, "x");

            // The enum values should have been cast to strings before being reported.
            string[] expected = Enumerable.Repeat("Red", actual.Length).ToArray();
            Assert.AreEqual(expected, actual);
        }
Ejemplo n.º 2
0
        public void TestSoilWithNullProperties()
        {
            string      json = ReflectionUtilities.GetResourceAsString("UnitTests.Resources.NullSample.apsimx");
            Simulations file = FileFormat.ReadFromString <Simulations>(json, out List <Exception> fileErrors);

            if (fileErrors != null && fileErrors.Count > 0)
            {
                throw fileErrors[0];
            }

            // This simulation needs a weather node, but using a legit
            // met component will just slow down the test.
            IModel sim     = file.FindInScope <Simulation>();
            Model  weather = new MockWeather();

            sim.Children.Add(weather);
            weather.Parent = sim;

            // Run the file.
            var runner = new Runner(file);
            List <Exception> errors = runner.Run();

            if (errors != null && errors.Count > 0)
            {
                throw errors[0];
            }
        }
Ejemplo n.º 3
0
        public void TestEditingNullProperty()
        {
            ExplorerPresenter explorerPresenter = UITestUtilities.OpenResourceFileInTab(Assembly.GetExecutingAssembly(),
                                                                                        "UnitTests.ApsimNG.Resources.SampleFiles.NullSample.apsimx");

            GtkUtilities.WaitForGtkEvents();

            Simulations sims   = explorerPresenter.ApsimXFile;
            Soil        soil   = sims.FindInScope <Soil>();
            Sample      sample = soil.FindChild <Sample>();

            explorerPresenter.SelectNode(sample);
            GtkUtilities.WaitForGtkEvents();

            Assert.IsNull(sample.NO3);

            ProfileView view = explorerPresenter.CurrentRightHandView as ProfileView;
            GridView    grid = view.ProfileGrid as GridView;

            // Click on the first cell in the second column (the NO3N column) and type 1.1 and then hit enter.
            GtkUtilities.ClickOnGridCell(grid, 0, 1, Gdk.EventType.ButtonPress, Gdk.ModifierType.None, GtkUtilities.ButtonPressType.LeftClick);
            GtkUtilities.SendKeyPress(grid.Grid, '1');
            GtkUtilities.SendKeyPress(grid.Grid, '.');
            GtkUtilities.SendKeyPress(grid.Grid, '1');
            GtkUtilities.TypeKey(grid.Grid, Gdk.Key.Return, Gdk.ModifierType.None);

            // The sample's NO3N property should now be an array containing 1.1.
            Assert.NotNull(sample.NO3);
            Assert.AreEqual(new double[1] {
                1.1
            }, sample.NO3);
        }
Ejemplo n.º 4
0
        public static void TestReportingOnModelEvents()
        {
            string      json = ReflectionUtilities.GetResourceAsString("UnitTests.Report.ReportOnEvents.apsimx");
            Simulations file = FileFormat.ReadFromString <Simulations>(json, out List <Exception> fileErrors);

            if (fileErrors != null && fileErrors.Count > 0)
            {
                throw fileErrors[0];
            }

            // This simulation needs a weather node, but using a legit
            // met component will just slow down the test.
            IModel sim     = file.FindInScope <Simulation>();
            Model  weather = new MockWeather();

            sim.Children.Add(weather);
            weather.Parent = sim;

            // Run the file.
            var Runner = new Runner(file);

            Runner.Run();

            // Check that the report reported on the correct dates.
            var           storage    = file.FindInScope <IDataStore>();
            List <string> fieldNames = new List <string>()
            {
                "doy"
            };

            DataTable data = storage.Reader.GetData("ReportOnFertilisation", fieldNames: fieldNames);

            double[] values   = DataTableUtilities.GetColumnAsDoubles(data, "doy");
            double[] expected = new double[] { 1, 32, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 364 };
            Assert.AreEqual(expected, values);

            data   = storage.Reader.GetData("ReportOnIrrigation", fieldNames: fieldNames);
            values = DataTableUtilities.GetColumnAsDoubles(data, "doy");
            // There is one less irrigation event, as the manager script doesn't irrigate.
            expected = new double[] { 1, 32, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 };
            Assert.AreEqual(expected, values);
        }
Ejemplo n.º 5
0
        public void RefreshCheckpointNames()
        {
            Simulations sims = Utilities.GetRunnableSim();

            sims.FileName = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".apsimx");
            sims.Write(sims.FileName);

            Simulation sim     = sims.FindInScope <Simulation>();
            IDataStore storage = sims.FindInScope <IDataStore>();

            // Record checkpoint names before and after running the simulation,
            // and ensure that they are not the same.
            string[] checkpointNamesBeforeRun = storage.Reader.CheckpointNames.ToArray();

            // Run the simulation
            var runner = new Runner(sims);

            runner.Run();
            string[] checkpointNamesAfterRun = storage.Reader.CheckpointNames.ToArray();

            Assert.AreNotEqual(checkpointNamesBeforeRun, checkpointNamesAfterRun, "Storage reader failed to update checkpoint names after simulation was run.");
        }
Ejemplo n.º 6
0
        public static void TestCommentsInEventNames()
        {
            Simulations file = Utilities.GetRunnableSim();

            Report report = file.FindInScope <Report>();

            report.Name          = "Report"; // Just to make sure
            report.VariableNames = new string[] { "[Clock].Today.DayOfYear as doy" };
            report.EventNames    = new string[]
            {
                "[Clock].StartOfWeek // works normally",
                "// Should be ignored",
                "//[Clock].EndOfWeek // entire line should be ignored"
            };

            Clock clock = file.FindInScope <Clock>();

            clock.StartDate = new DateTime(2017, 1, 1);
            clock.EndDate   = new DateTime(2017, 3, 1);

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

            if (errors != null && errors.Count > 0)
            {
                throw errors[0];
            }

            List <string> fieldNames = new List <string>()
            {
                "doy"
            };
            IDataStore storage = file.FindInScope <IDataStore>();
            DataTable  data    = storage.Reader.GetData("Report", fieldNames: fieldNames);

            double[] actual   = DataTableUtilities.GetColumnAsDoubles(data, "doy");
            double[] expected = new double[] { 1, 8, 15, 22, 29, 36, 43, 50, 57 };
            Assert.AreEqual(expected, actual);
        }
Ejemplo n.º 7
0
        public void TestCsvSwitch()
        {
            Simulations file = Utilities.GetRunnableSim();

            string reportName = "Report";

            Models.Report report = file.FindInScope <Models.Report>();
            report.VariableNames = new string[] { "[Clock].Today.DayOfYear as n", "2 * [Clock].Today.DayOfYear as 2n" };
            report.EventNames    = new string[] { "[Clock].DoReport" };
            report.Name          = reportName;

            Clock clock = file.FindInScope <Clock>();

            clock.StartDate = new DateTime(2019, 1, 1);
            clock.EndDate   = new DateTime(2019, 1, 10);

            string output = Utilities.RunModels(file, "/Csv");

            string csvFile = Path.ChangeExtension(file.FileName, ".Report.csv");

            Assert.True(File.Exists(csvFile), "Models.exe failed to create a csv file when passed the /Csv command line argument. Output of Models.exe: " + output);

            // Verify that the .csv file contains correct data.
            string csvData  = File.ReadAllText(csvFile);
            string expected = @"SimulationName,SimulationID,    2n,CheckpointID,CheckpointName, n,Zone
    Simulation,           1, 2.000,           1,       Current, 1,Zone
    Simulation,           1, 4.000,           1,       Current, 2,Zone
    Simulation,           1, 6.000,           1,       Current, 3,Zone
    Simulation,           1, 8.000,           1,       Current, 4,Zone
    Simulation,           1,10.000,           1,       Current, 5,Zone
    Simulation,           1,12.000,           1,       Current, 6,Zone
    Simulation,           1,14.000,           1,       Current, 7,Zone
    Simulation,           1,16.000,           1,       Current, 8,Zone
    Simulation,           1,18.000,           1,       Current, 9,Zone
    Simulation,           1,20.000,           1,       Current,10,Zone
";

            Assert.AreEqual(expected, csvData);
        }
Ejemplo n.º 8
0
        public void TestDisabledSummary()
        {
            Simulations sims    = Utilities.GetRunnableSim();
            Summary     summary = sims.FindInScope <Summary>();

            summary.Verbosity = MessageType.Error;

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

            if (errors != null && errors.Count > 0)
            {
                throw new Exception("Disabling summary output causes simulation to fail.");
            }
        }
Ejemplo n.º 9
0
        public void TestDisabledSummary()
        {
            Simulations sims    = Utilities.GetRunnableSim();
            Summary     summary = sims.FindInScope <Summary>();

            summary.CaptureErrors      = false;
            summary.CaptureWarnings    = false;
            summary.CaptureSummaryText = false;

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

            if (errors != null && errors.Count > 0)
            {
                throw new Exception("Disabling summary output causes simulation to fail.");
            }
        }
Ejemplo n.º 10
0
        public void TestFileNameChange()
        {
            Simulations sims    = Utilities.GetRunnableSim();
            IDataStore  storage = sims.FindInScope <IDataStore>();

            // Write the simulations to disk.
            sims.Write(sims.FileName);

            // Record the database's filename.
            string oldDbFileName = storage.FileName;

            // Write the simulations to disk under a new filename.
            sims.Write(Path.ChangeExtension(Path.GetTempFileName(), ".apsimx"));

            // Record the database's new filename.
            string newDbFileName = storage.FileName;

            // The new file name should not be the same as the old one.
            Assert.AreNotEqual(oldDbFileName, newDbFileName);
        }
Ejemplo n.º 11
0
        public void CreateGraphs()
        {
            Simulations sims = CreateTemplate();

            sims.FileName = Path.ChangeExtension(Path.GetTempFileName(), ".apsimx");

            DataStore storage = sims.FindInScope <DataStore>();

            storage.FileName = Path.ChangeExtension(sims.FileName, ".db");

            // Run the file to populate the datastore.
            Runner           runner = new Runner(sims);
            List <Exception> errors = runner.Run();

            if (errors != null && errors.Count > 0)
            {
                throw errors[0];
            }

            // Open the .apsimx file in the GUI.
            sims.Write(sims.FileName);
            ExplorerPresenter explorer = UITestsMain.MasterPresenter.OpenApsimXFileInTab(sims.FileName, true);

            GtkUtilities.WaitForGtkEvents();
            sims = explorer.ApsimXFile;

            // Create a graphs folder under the zone.
            IModel paddock = sims.FindInScope <Zone>();
            Folder graphs  = new Folder();

            graphs.Name = "Graphs";

            var command = new AddModelCommand(paddock, graphs);

            explorer.CommandHistory.Add(command, true);

            // Add an empty graph to the folder.
            Models.Graph graph = new Models.Graph();
            graph.Name = "Graph";
            command    = new AddModelCommand(graphs, graph);
            explorer.CommandHistory.Add(command, true);

            // Add an empty series to the graph.
            Models.Series series = new Models.Series();
            series.Name = "Series";
            command     = new AddModelCommand(graph, series);
            explorer.CommandHistory.Add(command, true);
            explorer.Refresh();

            // click on the series node.
            explorer.SelectNode(series.FullPath);
            GtkUtilities.WaitForGtkEvents();

            // Get a reference to the OxyPlot PlotView via reflection.
            SeriesView seriesView = explorer.CurrentRightHandView as SeriesView;
            GraphView  view       = seriesView?.GraphView as GraphView;

            Assert.NotNull(view);

            PlotView plot = ReflectionUtilities.GetValueOfFieldOrProperty("plot1", view) as PlotView;

            Assert.NotNull(plot);

            // Series has no table name or x/y series names yet, so there should
            // be nothing shown on the graph.
            Assert.AreEqual(0, plot.Model.Series.Count);

            // Now draw some data on the graph.
            seriesView.DataSource.SelectedValue = "Report";
            seriesView.X.SelectedValue          = "n";
            seriesView.Y.SelectedValue          = "n2";
            seriesView.SeriesType.SelectedValue = "Scatter";

            GtkUtilities.WaitForGtkEvents();

            // There should now be one series showing.
            Assert.AreEqual(1, plot.Model.Series.Count);

            // It should be a line series.
            Assert.True(plot.Model.Series[0] is LineSeries, "Graph series type is set to scatter, but the series object is not a LineSeries.");

            // Series colour should not be white, and should not be the same as the background colour.
            LineSeries line = plot.Model.Series[0] as LineSeries;

            OxyPlot.OxyColor empty = OxyPlot.OxyColor.FromArgb(0, 0, 0, 0);
            OxyPlot.OxyColor white = OxyPlot.OxyColor.FromArgb(0, 255, 255, 255);
            Assert.AreNotEqual(empty, line.Color, "Graph line series default colour is white on white.");
            Assert.AreNotEqual(white, line.Color, "Graph line series default colour is white on white.");

            // Legend should be visible but empty by default.
            Assert.True(plot.Model.IsLegendVisible);
            // todo - ensure legend is empty

            // Next, we want to change the legend position and ensure that the legend actually moves.

            // Click on the 'show in legend' checkbox.
            seriesView.ShowInLegend.Checked = true;
            GtkUtilities.WaitForGtkEvents();

            // Double click on the middle of the legend.
            Cairo.Rectangle legendRect = plot.Model.LegendArea.ToRect(true);
            double          x          = (legendRect.X + (legendRect.X + legendRect.Width)) / 2;
            double          y          = (legendRect.Y + (legendRect.Y + legendRect.Height)) / 2;

            GtkUtilities.DoubleClick(plot, x, y, wait: true);

            // Default legend position should be top-left.
            Assert.AreEqual(plot.Model.LegendPosition, OxyPlot.LegendPosition.TopLeft);

            // Now we want to change the legend position. First, get a reference to the legend view
            // via the legend presenter, via the graph presenter, via the series presenter, via the explorer presenter.
            Assert.True(explorer.CurrentPresenter is SeriesPresenter);
            SeriesPresenter seriesPresenter = explorer.CurrentPresenter as SeriesPresenter;
            LegendPresenter legendPresenter = seriesPresenter.GraphPresenter.CurrentPresenter as LegendPresenter;

            // todo: should we add something like a GetView() method to the IPresenter interface?
            // It might be a bit of work to set up but would save us having to use reflection
            LegendView legendView = ReflectionUtilities.GetValueOfFieldOrProperty("view", legendPresenter) as LegendView;

            // The legend options are inside a Gtk expander.
            Assert.IsTrue(legendView.MainWidget.Parent is Expander);
            Expander expander = legendView.MainWidget.Parent as Expander;

            // The expander should be expanded and the options visible.
            Assert.IsTrue(expander.Expanded);
            Assert.IsTrue(legendView.MainWidget.Visible);

            // The legend view contains a combo box with the legend position options (top-right, bottom-left, etc).
            // This should really be refactored to use a public IDropDownView, which is much more convenient to use.
            // First, get a reference to the combo box via reflection.
            ComboBox combo = ReflectionUtilities.GetValueOfFieldOrProperty("combobox1", legendView) as ComboBox;

            // fixme - we should support all valid OxyPlot legend position types.
            foreach (Models.Graph.LegendPositionType legendPosition in Enum.GetValues(typeof(Models.Graph.LegendPositionType)))
            {
                string name = legendPosition.ToString();
                GtkUtilities.SelectComboBoxItem(combo, name, wait: true);

                OxyPlot.LegendPosition oxyPlotEquivalent = (OxyPlot.LegendPosition)Enum.Parse(typeof(OxyPlot.LegendPosition), name);
                Assert.AreEqual(plot.Model.LegendPosition, oxyPlotEquivalent);
            }

            // If we change the graph to a box plot then the several unused properties should be disabled.
            // These are x variable dropdown, x cumulative, x on top, marker size/type checkboxes.

            // First, make sure that these options are sensitive to input and can be changed.
            Assert.IsTrue(seriesView.X.IsSensitive);
            Assert.IsTrue(seriesView.XCumulative.IsSensitive);
            Assert.IsTrue(seriesView.XOnTop.IsSensitive);
            Assert.IsTrue(seriesView.MarkerSize.IsSensitive);
            Assert.IsTrue(seriesView.MarkerType.IsSensitive);

            // Now change series type to box plot.
            GtkUtilities.SelectComboBoxItem(seriesView.SeriesType, "Box", wait: true);
            Assert.AreEqual(SeriesType.Box, series.Type);

            // Ensure the box plot is not white in light theme.
            plot = ReflectionUtilities.GetValueOfFieldOrProperty("plot1", view) as PlotView;
            Assert.NotNull(plot);
            BoxPlotSeries boxPlot = plot.Model.Series.OfType <BoxPlotSeries>().FirstOrDefault();

            Assert.NotNull(boxPlot);

            Assert.AreNotEqual(empty, boxPlot.Fill);
            Assert.AreNotEqual(white, boxPlot.Fill);
            Assert.AreNotEqual(empty, boxPlot.Stroke);
            Assert.AreNotEqual(white, boxPlot.Stroke);

            // The controls should no longer be sensitive.
            Assert.IsFalse(seriesView.XCumulative.IsSensitive);
            Assert.IsFalse(seriesView.XOnTop.IsSensitive);
            Assert.IsFalse(seriesView.MarkerSize.IsSensitive);
            Assert.IsFalse(seriesView.MarkerType.IsSensitive);

            // Change the series type back to scatter.
            GtkUtilities.SelectComboBoxItem(seriesView.SeriesType, "Scatter", wait: true);

            // The controls should be sensitive once more.
            Assert.IsTrue(seriesView.X.IsSensitive);
            Assert.IsTrue(seriesView.XCumulative.IsSensitive);
            Assert.IsTrue(seriesView.XOnTop.IsSensitive);
            Assert.IsTrue(seriesView.MarkerSize.IsSensitive);
            Assert.IsTrue(seriesView.MarkerType.IsSensitive);
        }
Ejemplo n.º 12
0
        public void TestEditOption()
        {
            string[] changes = new string[]
            {
                "[Clock].StartDate = 2019-1-20",
                ".Simulations.Sim1.Clock.EndDate = 3/20/2019",
                ".Simulations.Sim2.Enabled = false",
                ".Simulations.Sim1.Field.Soil.Thickness[1] = 500",
                ".Simulations.Sim1.Field.Soil.Thickness[2] = 2500",
                ".Simulations.Sim2.Name = SimulationVariant35",
            };
            string configFileName = Path.GetTempFileName();

            File.WriteAllLines(configFileName, changes);

            string apsimxFileName = Path.ChangeExtension(Path.GetTempFileName(), ".apsimx");
            string text           = ReflectionUtilities.GetResourceAsString("UnitTests.BasicFile.apsimx");

            // Check property values at this point.
            Simulations sims = FileFormat.ReadFromString <Simulations>(text, out List <Exception> errors);

            if (errors != null && errors.Count > 0)
            {
                throw errors[0];
            }

            Clock      clock = sims.FindInScope <Clock>();
            Simulation sim1  = sims.FindInScope <Simulation>();
            Simulation sim2  = sims.FindInScope("Sim2") as Simulation;
            Soil       soil  = sims.FindByPath(".Simulations.Sim1.Field.Soil")?.Value as Soil;

            // Check property values - they should be unchanged at this point.
            DateTime start = new DateTime(2003, 11, 15);

            Assert.AreEqual(start.Year, clock.StartDate.Year);
            Assert.AreEqual(start.DayOfYear, clock.StartDate.DayOfYear);

            Assert.AreEqual(sim1.Name, "Sim1");
            Assert.AreEqual(sim2.Enabled, true);
            Assert.AreEqual(soil.Thickness[0], 150);
            Assert.AreEqual(soil.Thickness[1], 150);

            // Run Models.exe with /Edit command.
            sims.Write(apsimxFileName);
            Utilities.RunModels($"{apsimxFileName} /Edit {configFileName}");
            sims = FileFormat.ReadFromFile <Simulations>(apsimxFileName, out errors);
            if (errors != null && errors.Count > 0)
            {
                throw errors[0];
            }

            // Get references to the changed models.
            clock = sims.FindInScope <Clock>();
            Clock clock2 = sims.FindByPath(".Simulations.SimulationVariant35.Clock")?.Value as Clock;

            // Sims should have at least 3 children - data store and the 2 sims.
            Assert.That(sims.Children.Count > 2);
            sim1 = sims.Children.OfType <Simulation>().First();
            sim2 = sims.Children.OfType <Simulation>().Last();
            soil = sims.FindByPath(".Simulations.Sim1.Field.Soil")?.Value as Soil;

            start = new DateTime(2019, 1, 20);
            DateTime end = new DateTime(2019, 3, 20);

            // Check clock.
            Assert.AreEqual(clock.StartDate.Year, start.Year);
            Assert.AreEqual(clock.StartDate.DayOfYear, start.DayOfYear);
            Assert.AreEqual(clock.EndDate.Year, end.Year);
            Assert.AreEqual(clock.EndDate.DayOfYear, end.DayOfYear);

            // These changes should not affect the clock in simulation 2.
            start = new DateTime(2003, 11, 15);
            end   = new DateTime(2003, 11, 15);
            Assert.AreEqual(clock2.StartDate.Year, start.Year);
            Assert.AreEqual(clock2.StartDate.DayOfYear, start.DayOfYear);
            Assert.AreEqual(clock2.EndDate.Year, end.Year);
            Assert.AreEqual(clock2.EndDate.DayOfYear, end.DayOfYear);

            // Sim2 should have been renamed to SimulationVariant35
            Assert.AreEqual(sim2.Name, "SimulationVariant35");

            // Sim1's name should be unchanged.
            Assert.AreEqual(sim1.Name, "Sim1");

            // Sim2 should have been disabled. This should not affect sim1.
            Assert.That(sim1.Enabled);
            Assert.That(!sim2.Enabled);

            // First 2 soil thicknesses have been changed to 500 and 2500 respectively.
            Assert.AreEqual(soil.Thickness[0], 500, 1e-8);
            Assert.AreEqual(soil.Thickness[1], 2500, 1e-8);
        }
Ejemplo n.º 13
0
        public void Initialise()
        {
            Simulations basicFile = Utilities.GetRunnableSim();

            IModel simulation = basicFile.FindInScope <Simulation>();
            IModel paddock    = basicFile.FindInScope <Zone>();

            // Add a weather component.
            Models.Climate.Weather weather = new Models.Climate.Weather();
            weather.Name     = "Weather";
            weather.FileName = "asdf.met";
            Structure.Add(weather, simulation);

            // Add a second weather component.
            Models.Climate.Weather weather2 = new Models.Climate.Weather();
            weather2.FileName = "asdf.met";
            weather2.Name     = "Weather2";
            Structure.Add(weather2, simulation);

            // Add a third weather component.
            Models.Climate.Weather weather3 = new Models.Climate.Weather();
            weather3.FileName = "asdf.met";
            weather3.Name     = "Weather3";
            Structure.Add(weather3, simulation);

            // Add a third weather component.
            Models.Climate.Weather weather4 = new Models.Climate.Weather();
            weather4.FileName = "asdf.met";
            weather4.Name     = "Weather4";
            Structure.Add(weather4, simulation);

            // Add a report.
            Models.Report report = new Models.Report();
            report.Name = "Report";
            Structure.Add(report, paddock);

            // Add the wheat model.
            string json  = ReflectionUtilities.GetResourceAsString(typeof(IModel).Assembly, "Models.Resources.Wheat.json");
            Plant  wheat = FileFormat.ReadFromString <IModel>(json, e => throw e, false).Children[0] as Plant;

            wheat.ResourceName = "Wheat";
            Structure.Add(wheat, paddock);

            Manager manager = new Manager();

            manager.Code = @"using Models.PMF;
using Models.Core;
using System;
namespace Models
{
    [Serializable]
    public class Script : Model
    {
        [Description(""an amount"")]
        public double Amount { get; set; }
    }
}";
            Structure.Add(manager, paddock);

            Physical physical = new Physical();

            physical.BD     = new double[5];
            physical.AirDry = new double[5];
            physical.LL15   = new double[5];
            Structure.Add(physical, paddock);
            Structure.Add(new WaterBalance(), paddock);
            Structure.Add(new SurfaceOrganicMatter(), paddock);

            ListClass <string> stringList = new ListClass <string>("StringList", 5);

            Structure.Add(stringList, simulation);

            ListClass <double> doubleList = new ListClass <double>("DoubleList", 5);

            Structure.Add(doubleList, simulation);

            basicFile.Write(basicFile.FileName);
            fileName = basicFile.FileName;

            // Create a new .apsimx file containing two weather nodes.
            Simulations test = Utilities.GetRunnableSim();
            IModel      sim  = test.FindInScope <Simulation>();

            Models.Climate.Weather w1 = new Models.Climate.Weather();
            w1.FileName = "w1.met";
            w1.Name     = "w1";
            Structure.Add(w1, sim);

            Models.Climate.Weather w2 = new Models.Climate.Weather();
            w2.Name     = "w2";
            w2.FileName = "w2.met";
            Structure.Add(w2, sim);

            extFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".apsimx");
            test.Write(extFile);
        }
Ejemplo n.º 14
0
        public void TestEditing()
        {
            string configFile = Path.GetTempFileName();

            File.WriteAllLines(configFile, new[]
            {
                // Modify an array
                "[Report].VariableNames = x,y,z",

                // Modify a date - try a few different formats.
                "[Clock].StartDate = 2000-01-01",
                "[Clock].EndDate = 2000-01-10T00:00:00",

                // Modify a string
                "[Weather].FileName = fdsa.met",
                @"[Weather2].FullFileName = jkl.met",

                // Replace a model with a model from another file.
                $"[Weather3] = {extFile}",
                $"[Weather4] = {extFile};[w2]",

                // Change a property of a resource model.
                "[Wheat].Leaf.Photosynthesis.RUE.FixedValue = 0.4",

                // Change a property of a manager script.
                "[Manager].Script.Amount = 1234",

                // Set an entire array.
                "[Physical].BD = 1, 2, 3, 4, 5",

                // Modify a single element of an array.
                "[Physical].AirDry[2] = 6",

                // Modify multiple elements of an array.
                "[Physical].LL15[3:4] = 7",
            });

            Simulations file = EditFile.Do(fileName, configFile);

            var report = file.FindInScope <Models.Report>();

            string[] variableNames = new[] { "x", "y", "z" };
            Assert.AreEqual(variableNames, report.VariableNames);

            IModel sim = file.FindChild <Simulation>();

            // Use an index-based lookup to locate child models.
            // When we replace an entire model, we want to ensure
            // that the replacement is inserted at the correct index.

            Clock clock = sim.Children[0] as Clock;

            Assert.AreEqual(new DateTime(2000, 1, 1), clock.StartDate);
            Assert.AreEqual(new DateTime(2000, 1, 10), clock.EndDate);

            var weather = sim.Children[3] as Models.Climate.Weather;

            Assert.NotNull(weather);
            Assert.AreEqual("Weather", weather.Name);
            Assert.AreEqual("fdsa.met", weather.FileName);

            var weather2 = sim.Children[4] as Models.Climate.Weather;

            Assert.NotNull(weather2);
            Assert.AreEqual("Weather2", weather2.Name);
            Assert.AreEqual(@"jkl.met", weather2.FileName);

            // Weather3 and Weather4 should have been
            // renamed to w1 and w2, respectively.
            var weather3 = sim.Children[5] as Models.Climate.Weather;

            Assert.NotNull(weather3);
            Assert.AreEqual("w1", weather3.Name);
            Assert.AreEqual("w1.met", weather3.FileName);

            var weather4 = sim.Children[6] as Models.Climate.Weather;

            Assert.NotNull(weather4);
            Assert.AreEqual("w2", weather4.Name);
            Assert.AreEqual("w2.met", weather4.FileName);

            // The edit file operation should have changed RUE value to 0.4.
            var wheat = sim.Children[2].Children[2] as Plant;
            var rue   = wheat.Children[6].Children[4].Children[0] as Constant;

            Assert.AreEqual(0.4, rue.FixedValue);

            double amount = (double)sim.FindByPath("[Manager].Script.Amount")?.Value;

            Assert.AreEqual(1234, amount);

            Physical physical = sim.Children[2].Children[4] as Physical;

            Assert.AreEqual(new double[5] {
                1, 2, 3, 4, 5
            }, physical.BD);
            Assert.AreEqual(new double[5] {
                0, 6, 0, 0, 0
            }, physical.AirDry);
            Assert.AreEqual(new double[5] {
                0, 0, 7, 7, 0
            }, physical.LL15);
        }
Ejemplo n.º 15
0
        public void TestEditing()
        {
            string configFile = Path.GetTempFileName();

            File.WriteAllLines(configFile, new[]
            {
                // Modify an array
                "[Report].VariableNames = x,y,z",

                // Modify a date - try a few different formats.
                "[Clock].StartDate = 2000-01-01",
                "[Clock].EndDate = 2000-01-10T00:00:00",

                // Modify a string
                "[Weather].FileName = fdsa.met",
                @"[Weather2].FullFileName = jkl.met",

                // Replace a model with a model from another file.
                $"[Weather3] = {extFile}",
                $"[Weather4] = {extFile};[w2]",

                // Change a property of a resource model.
                "[Wheat].Leaf.Photosynthesis.RUE.FixedValue = 0.4",

                // Change a property of a manager script.
                "[Manager].Script.Amount = 1234",

                // Set an entire array.
                "[Physical].BD = 1, 2, 3, 4, 5",

                // Modify a single element of an array.
                "[Physical].AirDry[2] = 6",

                // Modify multiple elements of an array.
                "[Physical].LL15[3:4] = 7",
            });

            string models = typeof(IModel).Assembly.Location;
            string args   = $"{fileName} /Edit {configFile}";

            var proc = new ProcessUtilities.ProcessWithRedirectedOutput();

            proc.Start(models, args, Path.GetTempPath(), true, writeToConsole: true);
            proc.WaitForExit();

            // Children of simulation are, in order:
            // Clock, summary, zone, Weather, Weather2, w1, w2
            Assert.AreEqual(null, proc.StdOut);
            Assert.AreEqual(null, proc.StdErr);

            Simulations file = FileFormat.ReadFromFile <Simulations>(fileName, out List <Exception> errors);

            if (errors != null && errors.Count > 0)
            {
                throw errors[0];
            }

            var report = file.FindInScope <Models.Report>();

            string[] variableNames = new[] { "x", "y", "z" };
            Assert.AreEqual(variableNames, report.VariableNames);

            IModel sim = file.FindChild <Simulation>();

            // Use an index-based lookup to locate child models.
            // When we replace an entire model, we want to ensure
            // that the replacement is inserted at the correct index.

            Clock clock = sim.Children[0] as Clock;

            Assert.AreEqual(new DateTime(2000, 1, 1), clock.StartDate);
            Assert.AreEqual(new DateTime(2000, 1, 10), clock.EndDate);

            var weather = sim.Children[3] as Models.Climate.Weather;

            Assert.NotNull(weather);
            Assert.AreEqual("Weather", weather.Name);
            Assert.AreEqual("fdsa.met", weather.FileName);

            var weather2 = sim.Children[4] as Models.Climate.Weather;

            Assert.NotNull(weather2);
            Assert.AreEqual("Weather2", weather2.Name);
            Assert.AreEqual(@"jkl.met", weather2.FileName);

            // Weather3 and Weather4 should have been
            // renamed to w1 and w2, respectively.
            var weather3 = sim.Children[5] as Models.Climate.Weather;

            Assert.NotNull(weather3);
            Assert.AreEqual("w1", weather3.Name);
            Assert.AreEqual("w1.met", weather3.FileName);

            var weather4 = sim.Children[6] as Models.Climate.Weather;

            Assert.NotNull(weather4);
            Assert.AreEqual("w2", weather4.Name);
            Assert.AreEqual("w2.met", weather4.FileName);

            // The edit file operation should have changed RUE value to 0.4.
            var wheat = sim.Children[2].Children[2] as Plant;
            var rue   = wheat.Children[6].Children[4].Children[0] as Constant;

            Assert.AreEqual(0.4, rue.FixedValue);

            double amount = (double)sim.FindByPath("[Manager].Script.Amount")?.Value;

            Assert.AreEqual(1234, amount);

            Physical physical = sim.Children[2].Children[4] as Physical;

            Assert.AreEqual(new double[5] {
                1, 2, 3, 4, 5
            }, physical.BD);
            Assert.AreEqual(new double[5] {
                0, 6, 0, 0, 0
            }, physical.AirDry);
            Assert.AreEqual(new double[5] {
                0, 0, 7, 7, 0
            }, physical.LL15);
        }