Esempio n. 1
0
        /// <summary>ResolveLinks in a model</summary>
        public static void ResolveLinks(IModel model)
        {
            Apsim.ParentAllChildren(model);
            var links = new Links();

            links.Resolve(model, true, true);
        }
Esempio n. 2
0
        public void EnsureServicesResolve()
        {
            var simulations = new Simulations()
            {
                Children = new List <Model>()
                {
                    new DataStore(),
                    new Simulation()
                    {
                        Children = new List <Model>()
                        {
                            new Clock(),
                            new MockSummary(),
                            new ModelWithServices()
                        }
                    }
                }
            };

            Apsim.ParentAllChildren(simulations);

            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);
        }
Esempio n. 3
0
        public void EnsureOldStyleLinkWorks()
        {
            var sim = new Simulation()
            {
                Children = new List <Model>()
                {
                    new Clock(),
                    new MockSummary(),
                    new Zone(),
                    new Zone(),
                    new ModelWithLinks()
                }
            };

            Apsim.ParentAllChildren(sim);

            var links = new Links();

            links.Resolve(sim, true);

            var modelWithLinks = sim.Children[4] as ModelWithLinks;

            Assert.AreEqual(modelWithLinks.zones.Length, 2);
            Assert.NotNull(modelWithLinks.zones[0]);
            Assert.NotNull(modelWithLinks.zones[1]);
        }
Esempio n. 4
0
        public void EnsureScopedLinkWorks()
        {
            var sim = new Simulation()
            {
                Children = new List <Model>()
                {
                    new Clock(),
                    new MockSummary(),
                    new Zone()
                    {
                        Name = "zone1"
                    },
                    new Zone()
                    {
                        Name = "zone2"
                    },
                    new ModelWithScopedLink()
                }
            };

            Apsim.ParentAllChildren(sim);

            Links linksAlgorithm = new Links();

            linksAlgorithm.Resolve(sim, allLinks: true);

            // Should find the closest match.
            var links = sim.Children[4] as ModelWithScopedLink;

            Assert.AreEqual(links.zone2.Name, "zone1");
        }
Esempio n. 5
0
        public void EnsureScopedLinkByNameWorks()
        {
            var sim = new Simulation()
            {
                Children = new List <Model>()
                {
                    new Clock(),
                    new MockSummary(),
                    new Zone()
                    {
                        Name = "zone1"
                    },
                    new Zone()
                    {
                        Name = "zone2"
                    },
                    new ModelWithScopedLinkByName()
                }
            };

            Apsim.ParentAllChildren(sim);

            var links = new Links();

            links.Resolve(sim, true);

            var model = sim.Children[4] as ModelWithScopedLinkByName;

            Assert.AreEqual(model.zone2.Name, "zone2");
        }
Esempio n. 6
0
        public void EnsureParentLinkWorks()
        {
            var sim = new Simulation()
            {
                Children = new List <Model>()
                {
                    new Clock(),
                    new MockSummary(),
                    new Zone()
                    {
                        Name     = "zone1",
                        Children = new List <Model>()
                        {
                            new ModelWithParentLink()
                        }
                    },
                    new Zone()
                    {
                        Name = "zone2"
                    }
                }
            };

            Apsim.ParentAllChildren(sim);

            var links = new Links();

            links.Resolve(sim, true);

            // Should find the closest match.
            var model = sim.Children[2].Children[0] as ModelWithParentLink;

            Assert.AreEqual(model.zone.Name, "zone1");
            Assert.AreEqual(model.sim.Name, "Simulation");
        }
Esempio n. 7
0
        /// <summary>Gets the next job to run</summary>
        public Simulation NextSimulationToRun(bool fullFactorial = true)
        {
            if (allCombinations.Count == 0)
            {
                return(null);
            }

            var combination = allCombinations[0];

            allCombinations.RemoveAt(0);
            string newSimulationName = Name;

            foreach (FactorValue value in combination)
            {
                newSimulationName += value.Name + value.Values[0];
            }

            Simulation newSimulation = Apsim.DeserialiseFromStream(serialisedBase) as Simulation;

            newSimulation.Name     = newSimulationName;
            newSimulation.Parent   = null;
            newSimulation.FileName = parentSimulations.FileName;
            Apsim.ParentAllChildren(newSimulation);

            // Make substitutions.
            parentSimulations.MakeSubsAndLoad(newSimulation);

            foreach (FactorValue value in combination)
            {
                value.ApplyToSimulation(newSimulation);
            }

            return(newSimulation);
        }
Esempio n. 8
0
        /// <summary>
        /// Adds a model as a child to a parent model. Will throw if not allowed.
        /// </summary>
        /// <param name="modelToAdd">The model to add.</param>
        /// <param name="parent">The parent model to add it to.</param>
        public static IModel Add(IModel modelToAdd, IModel parent)
        {
            if (parent.ReadOnly)
            {
                throw new Exception(string.Format("Unable to modify {0} - it is read-only.", parent.Name));
            }

            if (modelToAdd is Simulations s && s.Children.Count == 1)
            {
                modelToAdd = s.Children[0];
            }

            modelToAdd.Parent = parent;
            Apsim.ParentAllChildren(modelToAdd);
            parent.Children.Add(modelToAdd as Model);

            // Ensure the model name is valid.
            EnsureNameIsUnique(modelToAdd);

            // Call OnCreated
            modelToAdd.OnCreated();
            Apsim.ChildrenRecursively(modelToAdd).ForEach(m => m.OnCreated());

            Apsim.ClearCaches(modelToAdd);
            return(modelToAdd);
        }
Esempio n. 9
0
        /// <summary>
        /// Convert the simulation decription to a simulation.
        /// path.
        /// </summary>
        /// <param name="simulations">The top level simulations model.</param>
        public Simulation ToSimulation(Simulations simulations = null)
        {
            AddReplacements(simulations);

            Simulation newSimulation;

            if (doClone)
            {
                newSimulation = Apsim.Clone(baseSimulation) as Simulation;
            }
            else
            {
                newSimulation = baseSimulation;
            }

            if (Name == null)
            {
                newSimulation.Name = baseSimulation.Name;
            }
            else
            {
                newSimulation.Name = Name;
            }
            newSimulation.Parent = null;
            Apsim.ParentAllChildren(newSimulation);
            replacementsToApply.ForEach(r => r.Replace(newSimulation));

            // Give the simulation the descriptors.
            newSimulation.Descriptors = Descriptors;

            return(newSimulation);
        }
Esempio n. 10
0
        /// <summary>Gets the next job to run</summary>
        public Simulation NextSimulationToRun(bool fullFactorial = true)
        {
            if (allCombinations.Count == 0)
            {
                return(null);
            }

            var combination = allCombinations[0];

            allCombinations.RemoveAt(0);

            Simulation newSimulation = Apsim.DeserialiseFromStream(serialisedBase) as Simulation;

            newSimulation.Name     = Name + "Simulation" + simulationNumber;
            newSimulation.Parent   = null;
            newSimulation.FileName = parentSimulations.FileName;
            Apsim.ParentAllChildren(newSimulation);

            // Make substitutions.
            parentSimulations.MakeSubsAndLoad(newSimulation);

            foreach (FactorValue value in combination)
            {
                value.ApplyToSimulation(newSimulation);
            }

            PushFactorsToReportModels(newSimulation, combination);

            simulationNumber++;
            return(newSimulation);
        }
        public void EnsurePropertyReplacementsWork()
        {
            var sim = new Simulation()
            {
                Name     = "BaseSimulation",
                Children = new List <Model>()
                {
                    new MockWeather()
                    {
                        Name      = "Weather",
                        MaxT      = 1,
                        StartDate = DateTime.MinValue
                    },
                }
            };

            Apsim.ParentAllChildren(sim);

            var simulationDescription = new SimulationDescription(sim, "CustomName");

            simulationDescription.AddOverride(new PropertyReplacement("Weather.MaxT", 2));

            var newSim = simulationDescription.ToSimulation();

            var weather = newSim.Children[0] as MockWeather;

            Assert.AreEqual(weather.MaxT, 2);
        }
Esempio n. 12
0
        public void HoldFunctionHandlesExceptions()
        {
            var f = new HoldFunction()
            {
                WhenToHold = "B",

                Children = new List <IModel>()
                {
                    new MockFunctionThatThrows()
                    {
                        Name = "ValueToHold"
                    },
                    new Phenology()
                    {
                        Children = new List <IModel>()
                        {
                            new Zone(),
                            new Clock(),
                            new MockSummary(),
                            new Plant(),
                            new MockFunctionThatThrows()
                            {
                                Name = "ThermalTime"
                            },
                            new MockPhase()
                            {
                                Name  = "Phase1",
                                Start = "A",
                                End   = "B"
                            },
                            new MockPhase()
                            {
                                Name  = "Phase2",
                                Start = "B",
                                End   = "C"
                            }
                        }
                    }
                }
            };

            Apsim.ParentAllChildren(f);


            var links = new Links();

            links.Resolve(f, true);

            Utilities.CallEvent(f.Children[1], "Commencing", new object[] { this, new EventArgs() });

            (f.Children[0] as MockFunctionThatThrows).DoThrow = true;
            Utilities.CallEvent(f, "Commencing", new object[] { this, new EventArgs() });
            Assert.AreEqual(f.Value(), 0);

            (f.Children[0] as MockFunctionThatThrows).DoThrow = false;
            Utilities.CallEvent(f, "DoUpdate", new object[] { this, new EventArgs() });
            Assert.AreEqual(f.Value(), 1);
        }
Esempio n. 13
0
        public void EnsurePropertyRangeWork()
        {
            var experiment = new Experiment()
            {
                Name     = "Exp1",
                Children = new List <IModel>()
                {
                    new Simulation()
                    {
                        Name     = "BaseSimulation",
                        Children = new List <IModel>()
                        {
                            new MockWeather()
                            {
                                Name      = "Weather",
                                MaxT      = 1,
                                StartDate = DateTime.MinValue
                            },
                        }
                    },
                    new Factors()
                    {
                        Children = new List <IModel>()
                        {
                            new Factor()
                            {
                                Name          = "MaxT",
                                Specification = "[Weather].MaxT = 10 to 20 step 5"
                            }
                        }
                    }
                }
            };

            Apsim.ParentAllChildren(experiment);

            var sims = experiment.GenerateSimulationDescriptions();

            Assert.AreEqual(sims[0].Descriptors.Find(d => d.Name == "Experiment").Value, "Exp1");
            Assert.AreEqual(sims[0].Descriptors.Find(d => d.Name == "MaxT").Value, "10");
            var weather = sims[0].ToSimulation().Children[0] as MockWeather;

            Assert.AreEqual(weather.MaxT, 10);

            Assert.AreEqual(sims[1].Descriptors.Find(d => d.Name == "Experiment").Value, "Exp1");
            Assert.AreEqual(sims[1].Descriptors.Find(d => d.Name == "MaxT").Value, "15");
            weather = sims[1].ToSimulation().Children[0] as MockWeather;
            Assert.AreEqual(weather.MaxT, 15);

            Assert.AreEqual(sims[2].Descriptors.Find(d => d.Name == "Experiment").Value, "Exp1");
            Assert.AreEqual(sims[2].Descriptors.Find(d => d.Name == "MaxT").Value, "20");
            weather = sims[2].ToSimulation().Children[0] as MockWeather;
            Assert.AreEqual(weather.MaxT, 20);

            Assert.AreEqual(sims.Count, 3);
        }
Esempio n. 14
0
        /// <summary>
        /// Convert the simulation decription to a simulation.
        /// path.
        /// </summary>
        public Simulation ToSimulation()
        {
            try
            {
                AddReplacements();

                Simulation newSimulation;
                if (doClone)
                {
                    newSimulation = Apsim.Clone(baseSimulation) as Simulation;

                    // After a binary clone, we need to force all managers to
                    // recompile their scripts. This is to work around an issue
                    // where scripts will change during deserialization. See issue
                    // #4463 and the TestMultipleChildren test inside ReportTests.
                    Apsim.ChildrenRecursively(newSimulation, typeof(Manager)).ForEach(m => m.OnCreated());
                }
                else
                {
                    newSimulation = baseSimulation;
                }

                if (string.IsNullOrWhiteSpace(Name))
                {
                    newSimulation.Name = baseSimulation.Name;
                }
                else
                {
                    newSimulation.Name = Name;
                }

                newSimulation.Parent = null;
                Apsim.ParentAllChildren(newSimulation);
                replacementsToApply.ForEach(r => r.Replace(newSimulation));

                // Give the simulation the descriptors.
                newSimulation.Descriptors = Descriptors;
                newSimulation.Services    = GetServices();

                // Standardise the soil.
                var soils = Apsim.ChildrenRecursively(newSimulation, typeof(Soils.Soil));
                foreach (Soils.Soil soil in soils)
                {
                    SoilStandardiser.Standardise(soil);
                }

                newSimulation.ClearCaches();
                return(newSimulation);
            }
            catch (Exception err)
            {
                var message = "Error in file: " + baseSimulation.FileName + " Simulation: " + Name;
                throw new Exception(message, err);
            }
        }
        public void EnsureReplacementsNodeWorks()
        {
            var simulations = new Simulations()
            {
                Children = new List <Model>()
                {
                    new Folder()
                    {
                        Name     = "Replacements",
                        Children = new List <Model>()
                        {
                            new MockWeather()
                            {
                                Name      = "Weather",
                                MaxT      = 2,
                                StartDate = DateTime.MinValue
                            }
                        }
                    },

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

            Apsim.ParentAllChildren(simulations);

            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);
        }
Esempio n. 16
0
        public void TestMultipleChildren()
        {
            var m1 = new Manager()
            {
                Name = "Manager1",
                Code = "using System;\r\nusing Models.Core;\r\nnamespace Models\r\n{\r\n[Serializable]\r\n" +
                       "public class Script1 : Model\r\n {\r\n " +
                       "public double A { get { return (1); } set { } }\r\n" +
                       "public double B { get { return (2); } set { } }\r\n }\r\n}\r\n"
            };
            var m2 = new Manager()
            {
                Name = "Manager2",
                Code = "using System;\r\nusing Models.Core;\r\nnamespace Models\r\n{\r\n[Serializable]\r\n" + "" +
                       "    public class Script2 : Model\r\n {\r\n" +
                       " public double A { get { return (3); } set { } }\r\n" +
                       " public double B { get { return (4); } set { } }\r\n }\r\n}\r\n"
            };

            report.VariableNames = new[]
            {
                "[Manager1].Script1.A as M1A",
                "[Manager2].Script2.A as M2A"
            };
            report.EventNames = new[]
            {
                "[Clock].DoReport"
            };
            simulation.Children.AddRange(new[] { m1, m2 });
            Apsim.ParentAllChildren(simulation);
            m1.OnCreated();
            m2.OnCreated();

            var runners = new[]
            {
                new Runner(simulation, runType: Runner.RunTypeEnum.MultiThreaded),
                new Runner(simulation, runType: Runner.RunTypeEnum.MultiProcess)
            };

            foreach (Runner runner in runners)
            {
                List <Exception> errors = runner.Run();
                if (errors != null && errors.Count > 0)
                {
                    throw errors[0];
                }

                double[] actual   = storage.Get <double>("M1A");
                double[] expected = storage.Get <double>("M2A");
                Assert.AreNotEqual(expected, actual);
            }
        }
Esempio n. 17
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       = (Apsim.Parent(this, typeof(Simulations)) as 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 = Apsim.Find(this, typeof(Replacements));

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

            IModel storage      = Apsim.Find(this, typeof(IDataStore));
            IModel newDataStore = new DataStore();

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

            sims.Children.Add(newDataStore);
            Apsim.ParentAllChildren(sims);

            sims.Write(apsimxFileName);

            string originalFile = rootNode?.FileName;

            if (string.IsNullOrEmpty(originalFile))
            {
                originalFile = (storage as IDataStore)?.FileName;
            }
            // Copy files across.
            foreach (IReferenceExternalFiles fileReference in Apsim.ChildrenRecursively(sims, typeof(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);
        }
Esempio n. 18
0
        /// <summary>Gets the next job to run</summary>
        public Simulation NextSimulationToRun()
        {
            if (allCombinations == null || allCombinations.Count == 0)
            {
                return(null);
            }

            if (serialisedBase == null)
            {
                allCombinations   = AllCombinations();
                parentSimulations = Apsim.Parent(this, typeof(Simulations)) as Simulations;
                Simulation baseSimulation = Apsim.Child(this, typeof(Simulation)) as Simulation;
                serialisedBase = Apsim.SerialiseToStream(baseSimulation) as Stream;
            }

            var combination = allCombinations[0];

            allCombinations.RemoveAt(0);
            string newSimulationName = Name;

            foreach (FactorValue value in combination)
            {
                newSimulationName += value.Name;
            }

            Simulation newSimulation = Apsim.DeserialiseFromStream(serialisedBase) as Simulation;

            newSimulation.Name     = newSimulationName;
            newSimulation.Parent   = null;
            newSimulation.FileName = parentSimulations.FileName;
            Apsim.ParentAllChildren(newSimulation);

            // Make substitutions.
            parentSimulations.MakeSubstitutions(newSimulation);

            // Call OnLoaded in all models.
            Events          events     = new Events(newSimulation);
            LoadedEventArgs loadedArgs = new LoadedEventArgs();

            events.Publish("Loaded", new object[] { newSimulation, loadedArgs });

            foreach (FactorValue value in combination)
            {
                value.ApplyToSimulation(newSimulation);
            }

            PushFactorsToReportModels(newSimulation, combination);
            StoreFactorsInDataStore(newSimulation, combination);
            return(newSimulation);
        }
Esempio n. 19
0
        /// <summary>
        /// Convert the simulation decription to a simulation.
        /// path.
        /// </summary>
        public Simulation ToSimulation()
        {
            try
            {
                AddReplacements();

                Simulation newSimulation;
                if (doClone)
                {
                    newSimulation = Apsim.Clone(baseSimulation) as Simulation;
                }
                else
                {
                    newSimulation = baseSimulation;
                }

                if (string.IsNullOrWhiteSpace(Name))
                {
                    newSimulation.Name = baseSimulation.Name;
                }
                else
                {
                    newSimulation.Name = Name;
                }

                newSimulation.Parent = null;
                Apsim.ParentAllChildren(newSimulation);
                replacementsToApply.ForEach(r => r.Replace(newSimulation));

                // Give the simulation the descriptors.
                newSimulation.Descriptors = Descriptors;
                newSimulation.Services    = GetServices();

                // Standardise the soil.
                var soils = Apsim.ChildrenRecursively(newSimulation, typeof(Soils.Soil));
                foreach (Soils.Soil soil in soils)
                {
                    SoilStandardiser.Standardise(soil);
                }

                newSimulation.ClearCaches();
                return(newSimulation);
            }
            catch (Exception err)
            {
                var message = "Error in file: " + baseSimulation.FileName + " Simulation: " + Name;
                throw new Exception(message, err);
            }
        }
Esempio n. 20
0
        public static Models.Graph.Graph CreateGraphFromResource(string resourceName)
        {
            string graphXmL = UserInterface.Properties.Resources.ResourceManager.GetString(resourceName);

            if (graphXmL != null)
            {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(graphXmL);

                Models.Graph.Graph graph = XmlUtilities.Deserialise(doc.DocumentElement, Assembly.GetExecutingAssembly()) as Models.Graph.Graph;
                Apsim.ParentAllChildren(graph);
                return(graph);
            }
            return(null);
        }
        public void EnsureReplacementWithInvalidNameDoesntMatch()
        {
            var simulations = new Simulations()
            {
                Children = new List <Model>()
                {
                    new Folder()
                    {
                        Name     = "Replacements",
                        Children = new List <Model>()
                        {
                            new MockWeather()
                            {
                                Name      = "Dummy name",
                                MaxT      = 2,
                                StartDate = DateTime.MinValue
                            }
                        }
                    },

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

            Apsim.ParentAllChildren(simulations);

            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);
        }
Esempio n. 22
0
        public static Models.Graph CreateGraphFromResource(string resourceName)
        {
            string graphXmL = ApsimNG.Properties.Resources.ResourceManager.GetString(resourceName);

            if (graphXmL != null)
            {
                List <Exception> errors = null;
                Models.Graph     graph  = Models.Core.ApsimFile.FileFormat.ReadFromString <Models.Graph>(graphXmL, out errors);
                if (errors != null && errors.Any())
                {
                    throw errors.First();
                }
                Apsim.ParentAllChildren(graph);
                return(graph);
            }
            return(null);
        }
Esempio n. 23
0
        public void EnsureLinkByPathWorks()
        {
            var sim = new Simulation()
            {
                Children = new List <Model>()
                {
                    new Clock(),
                    new MockSummary(),
                    new Zone()
                    {
                        Name     = "zone1",
                        Children = new List <Model>()
                        {
                            new ModelWithLinkByPath()
                        }
                    },
                    new Zone()
                    {
                        Name     = "zone2",
                        Children = new List <Model>()
                        {
                            new MockIrrigation()
                            {
                                Name = "irrig1"
                            },
                            new MockIrrigation()
                            {
                                Name = "irrig2"
                            }
                        }
                    },
                }
            };

            Apsim.ParentAllChildren(sim);

            var links = new Links();

            links.Resolve(sim, true);

            var model = sim.Children[2].Children[0] as ModelWithLinkByPath;
            var zone2 = sim.Children[3];

            Assert.AreEqual(model.irrigation1, zone2.Children[0]);
            Assert.AreEqual(model.irrigation2, zone2.Children[1]);
        }
Esempio n. 24
0
        public void EnsureIFunctionLinksCorrectly()
        {
            var sim = new Simulation()
            {
                Children = new List <Model>()
                {
                    new Clock(),
                    new MockSummary(),
                    new Zone(),
                    new Zone(),
                    new ModelWithIFunctions()
                    {
                        Children = new List <Model>()
                        {
                            new IFunctionProxy()
                            {
                                value = 1,
                                Name  = "model1"
                            },
                            new IFunctionProxy()
                            {
                                value = 2,
                                Name  = "model2"
                            },
                            new IFunctionProxy()
                            {
                                value = 3,
                                Name  = "model3"
                            }
                        }
                    }
                }
            };

            Apsim.ParentAllChildren(sim);


            Links linksAlgorithm = new Links();

            linksAlgorithm.Resolve(sim, allLinks: true);

            var links = sim.Children[4] as ModelWithIFunctions;

            Assert.AreEqual(links.model2.Value(), 2);
        }
Esempio n. 25
0
        /// <summary>
        /// Create a specific simulation.
        /// </summary>
        public Simulation CreateSpecificSimulation(string name)
        {
            List <List <FactorValue> > allCombinations = AllCombinations();
            Simulation  baseSimulation    = Apsim.Child(this, typeof(Simulation)) as Simulation;
            Simulations parentSimulations = Apsim.Parent(this, typeof(Simulations)) as Simulations;

            foreach (List <FactorValue> combination in allCombinations)
            {
                string newSimulationName = Name;
                foreach (FactorValue value in combination)
                {
                    newSimulationName += value.Name;
                }

                if (newSimulationName == name)
                {
                    Simulation newSimulation = Apsim.Clone(baseSimulation) as Simulation;
                    newSimulation.Name     = newSimulationName;
                    newSimulation.Parent   = null;
                    newSimulation.FileName = parentSimulations.FileName;
                    Apsim.ParentAllChildren(newSimulation);

                    // Make substitutions.
                    Simulations.MakeSubstitutions(parentSimulations, new List <Simulation> {
                        newSimulation
                    });

                    // Connect events and links in our new  simulation.
                    Events events = new Events();
                    events.AddModelEvents(newSimulation);
                    events.CallEventHandler(newSimulation, "Loaded", null);

                    foreach (FactorValue value in combination)
                    {
                        value.ApplyToSimulation(newSimulation);
                    }

                    PushFactorsToReportModels(newSimulation, combination);

                    return(newSimulation);
                }
            }

            return(null);
        }
Esempio n. 26
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"
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            };

            Apsim.ParentAllChildren(sims);
            sims.Write(sims.FileName);
            return(sims);
        }
Esempio n. 27
0
        /// <summary>
        /// Adds a model as a child to a parent model. Will throw if not allowed.
        /// </summary>
        /// <param name="modelToAdd">The model to add.</param>
        /// <param name="parent">The parent model to add it to.</param>
        public static void Add(IModel modelToAdd, IModel parent)
        {
            if (parent.ReadOnly)
            {
                throw new Exception(string.Format("Unable to modify {0} - it is read-only.", parent.Name));
            }

            modelToAdd.Parent = parent;
            Apsim.ParentAllChildren(modelToAdd);
            parent.Children.Add(modelToAdd as Model);

            // Ensure the model name is valid.
            EnsureNameIsUnique(modelToAdd);

            // Call OnCreated
            modelToAdd.OnCreated();
            Apsim.ChildrenRecursively(modelToAdd).ForEach(m => m.OnCreated());
        }
Esempio n. 28
0
        /// <summary>Called to start the job.</summary>
        /// <param name="jobManager">The job manager running this job.</param>
        /// <param name="workerThread">The thread this job is running on.</param>
        public void Run(JobManager jobManager, BackgroundWorker workerThread)
        {
            List <List <FactorValue> > allCombinations = AllCombinations();
            Simulation  baseSimulation    = Apsim.Child(this, typeof(Simulation)) as Simulation;
            Simulations parentSimulations = Apsim.Parent(this, typeof(Simulations)) as Simulations;

            Stream serialisedBase = Apsim.SerialiseToStream(baseSimulation) as Stream;

            List <Simulation> simulations = new List <Simulation>();

            foreach (List <FactorValue> combination in allCombinations)
            {
                string newSimulationName = Name;
                foreach (FactorValue value in combination)
                {
                    newSimulationName += value.Name;
                }

                Simulation newSimulation = Apsim.DeserialiseFromStream(serialisedBase) as Simulation;
                newSimulation.Name     = newSimulationName;
                newSimulation.Parent   = null;
                newSimulation.FileName = parentSimulations.FileName;
                Apsim.ParentAllChildren(newSimulation);

                // Make substitutions.
                Simulations.MakeSubstitutions(parentSimulations, new List <Simulation> {
                    newSimulation
                });

                // Call OnLoaded in all models.
                Events events = new Events();
                events.AddModelEvents(newSimulation);
                events.CallEventHandler(newSimulation, "Loaded", null);

                foreach (FactorValue value in combination)
                {
                    value.ApplyToSimulation(newSimulation);
                }

                PushFactorsToReportModels(newSimulation, combination);
                StoreFactorsInDataStore(newSimulation, combination);
                jobManager.AddChildJob(this, newSimulation);
            }
        }
Esempio n. 29
0
        /// <summary>
        /// Run all simulations.
        /// </summary>
        /// <param name="runType">How should the simulations be run?</param>
        /// <param name="wait">Wait until all simulations are complete?</param>
        /// <param name="verbose">Produce verbose output?</param>
        /// <param name="numberOfProcessors">Number of CPU processes to use. -1 indicates all processes.</param>
        /// <param name="runTests">Run all test models?</param>
        /// <returns>A list of exception or null if no exceptions thrown.</returns>
        public List <Exception> Run(RunTypeEnum runType, bool wait = true, bool verbose = false, int numberOfProcessors = -1, bool runTests = false)
        {
            errors.Clear();

            Apsim.ParentAllChildren(rootModel);
            Apsim.ChildrenRecursively(rootModel).ForEach(m => m.OnCreated());
            IJobManager jobManager = Models.Core.Runners.Runner.ForSimulations(rootModel, relativeTo, false);
            IJobRunner  jobRunner  = new JobRunnerSync();

            jobRunner.JobCompleted += OnJobCompleded;
            jobRunner.Run(jobManager, wait: true);
            jobRunner.JobCompleted -= OnJobCompleded;

            var storage = Apsim.Find(rootModel, typeof(IDataStore)) as IDataStore;

            storage.Writer.Stop();

            return(errors);
        }
Esempio n. 30
0
        public void EnsureChildLinkWorks()
        {
            var sim = new Simulation()
            {
                Children = new List <Model>()
                {
                    new Clock(),
                    new MockSummary(),
                    new ModelWithChildLink()
                    {
                        Children = new List <Model>()
                        {
                            new Zone()
                            {
                                Name = "zone1"
                            },
                        }
                    },
                }
            };

            Apsim.ParentAllChildren(sim);

            var links = new Links();

            links.Resolve(sim, true);

            // Should find zone1 as a match i.e. not use the zones name when doing a match.
            var model = sim.Children[2] as ModelWithChildLink;

            Assert.AreEqual(model.zone2.Name, "zone1");

            // If we now add another child, resolve should fail as there are two matches.
            model.Children.Add(new Zone()
            {
                Name = "zone2"
            });                                                // added to modelWithChildLink
            Apsim.ParentAllChildren(sim);
            Assert.Throws <Exception>(() =>
            {
                links.Resolve(sim, true);
            });
        }