Esempio n. 1
0
        /// <summary>Adds a new model (as specified by the xml node) to the specified parent.</summary>
        /// <param name="parent">The parent to add the model to</param>
        /// <param name="node">The XML representing the new model</param>
        /// <returns>The newly created model.</returns>
        public static IModel Add(IModel parent, XmlNode node)
        {
            IModel modelToAdd = XmlUtilities.Deserialise(node, Assembly.GetExecutingAssembly()) as Model;

            // Get all child models
            List <IModel> modelsToNotify = Apsim.ChildrenRecursively(modelToAdd);

            // Call deserialised in all models.
            object[] args = new object[] { true };
            CallEventHandler(modelToAdd, "Deserialised", args);
            foreach (IModel modelToNotify in modelsToNotify)
            {
                CallEventHandler(modelToNotify, "Deserialised", args);
            }

            // Corrently parent all models.
            modelToAdd.Parent = parent;
            Apsim.ParentAllChildren(modelToAdd);
            parent.Children.Add(modelToAdd as Model);

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

            // Call OnLoaded
            Apsim.CallEventHandler(modelToAdd, "Loaded", null);
            foreach (IModel child in modelsToNotify)
            {
                Apsim.CallEventHandler(child, "Loaded", null);
            }

            Locator(parent).Clear();

            return(modelToAdd);
        }
Esempio n. 2
0
        /// <summary>
        /// Create a simulations model
        /// </summary>
        /// <param name="children">The child models</param>
        public static Simulations Create(IEnumerable <IModel> children)
        {
            Simulations newSimulations = new Core.Simulations();

            newSimulations.Children.AddRange(children.Cast <Model>());

            // Call the OnDeserialised method in each model.
            Events events = new Core.Events(newSimulations);

            object[] args = new object[] { true };
            events.Publish("Deserialised", args);

            // Parent all models.
            newSimulations.Parent = null;
            Apsim.ParentAllChildren(newSimulations);

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

            events.Publish("Loaded", new object[] { newSimulations, loadedArgs });
            if (loadedArgs.errors.Count > 0)
            {
                newSimulations.LoadErrors = new List <Exception>();
                newSimulations.LoadErrors.AddRange(loadedArgs.errors);
            }
            return(newSimulations);
        }
Esempio n. 3
0
        /// <summary>Create a simulations object by reading the specified filename</summary>
        /// <param name="FileName">Name of the file.</param>
        /// <returns></returns>
        /// <exception cref="System.Exception">Simulations.Read() failed. Invalid simulation file.\n</exception>
        public static Simulations Read(string FileName)
        {
            // Run the converter.
            ApsimFile.Converter.ConvertToLatestVersion(FileName);

            // Deserialise
            Simulations simulations = XmlUtilities.Deserialise(FileName, Assembly.GetExecutingAssembly()) as Simulations;

            if (simulations != null)
            {
                // Set the filename
                simulations.FileName = FileName;
                simulations.SetFileNameInAllSimulations();

                // Call the OnDeserialised method in each model.
                Events   events = new Core.Events(simulations);
                object[] args   = new object[] { true };
                events.Publish("Deserialised", args);

                // Parent all models.
                simulations.Parent = null;
                Apsim.ParentAllChildren(simulations);

                // Call OnLoaded in all models.
                LoadedEventArgs loadedArgs = new LoadedEventArgs();
                events.Publish("Loaded", new object[] { simulations, loadedArgs });
                if (loadedArgs.errors.Count > 0)
                {
                    simulations.LoadErrors = new List <Exception>();
                    simulations.LoadErrors.AddRange(loadedArgs.errors);
                }
            }

            return(simulations);
        }
Esempio n. 4
0
 /// <summary>Add the specified model to the parent.</summary>
 /// <param name="parent">The parent model</param>
 /// <param name="modelToAdd">The child model.</param>
 public static void Add(IModel parent, IModel modelToAdd)
 {
     modelToAdd.Parent = parent;
     Apsim.ParentAllChildren(modelToAdd);
     parent.Children.Add(modelToAdd as Model);
     Apsim.ClearCaches(modelToAdd);
 }
Esempio n. 5
0
        /// <summary>Create a simulations object by reading the specified filename</summary>
        /// <param name="node">The node.</param>
        /// <returns></returns>
        /// <exception cref="System.Exception">Simulations.Read() failed. Invalid simulation file.\n</exception>
        public static Simulations Read(XmlNode node)
        {
            // Run the converter.
            APSIMFileConverter.ConvertToLatestVersion(node, null);

            // Deserialise
            Simulations simulations = XmlUtilities.Deserialise(node, Assembly.GetExecutingAssembly()) as Simulations;

            if (simulations != null)
            {
                // Set the filename
                simulations.SetFileNameInAllSimulations();

                // Call the OnSerialised method in each model.
                object[] args   = new object[] { true };
                Events   events = new Events(simulations);
                events.Publish("Deserialised", args);

                // Parent all models.
                simulations.Parent = null;
                Apsim.ParentAllChildren(simulations);

                events.Publish("Loaded", null);
            }
            else
            {
                throw new Exception("Simulations.Read() failed. Invalid simulation file.\n");
            }
            return(simulations);
        }
Esempio n. 6
0
 /// <summary>
 /// We have just been deserialised. If from XML then load our model
 /// from resource.
 /// </summary>
 public override void OnCreated()
 {
     // lookup the resource get the xml and then deserialise to a model.
     if (ResourceName != null && ResourceName != "")
     {
         string contents = Properties.Resources.ResourceManager.GetString(ResourceName);
         if (contents != null)
         {
             List <Exception> creationExceptions;
             Model            modelFromResource = ApsimFile.FileFormat.ReadFromString <Model>(contents, out creationExceptions);
             if (this.GetType() != modelFromResource.GetType())
             {
                 // Top-level model may be a simulations node. Search for a child of the correct type.
                 Model child = Apsim.Child(modelFromResource, this.GetType()) as Model;
                 if (child != null)
                 {
                     modelFromResource = child;
                 }
             }
             modelFromResource.Enabled = Enabled;
             Children.Clear();
             Children.AddRange(modelFromResource.Children);
             CopyPropertiesFrom(modelFromResource);
             SetNotVisible(modelFromResource);
             Apsim.ParentAllChildren(this);
             DoSerialiseChildren = false;
         }
     }
 }
Esempio n. 7
0
        /// <summary>Create a simulations object by reading the specified filename</summary>
        /// <param name="node">The node.</param>
        /// <returns></returns>
        /// <exception cref="System.Exception">Simulations.Read() failed. Invalid simulation file.\n</exception>
        public static Simulations Read(XmlNode node)
        {
            // Run the converter.
            Converter.ConvertToLatestVersion(node);

            // Deserialise
            Simulations simulations = XmlUtilities.Deserialise(node, Assembly.GetExecutingAssembly()) as Simulations;

            if (simulations != null)
            {
                // Set the filename
                simulations.SetFileNameInAllSimulations();

                // Call the OnSerialised method in each model.
                object[] args = new object[] { true };
                foreach (Model model in Apsim.ChildrenRecursively(simulations))
                {
                    Apsim.CallEventHandler(model, "Deserialised", args);
                }

                // Parent all models.
                simulations.Parent = null;
                Apsim.ParentAllChildren(simulations);

                CallOnLoaded(simulations);
            }
            else
            {
                throw new Exception("Simulations.Read() failed. Invalid simulation file.\n");
            }
            return(simulations);
        }
Esempio n. 8
0
        /// <summary>Run a simulation</summary>
        /// <param name="simulation">The simulation to run</param>
        /// <param name="doClone">Clone the simulation before running?</param>
        public void Run(Simulation simulation, bool doClone)
        {
            Apsim.ParentAllChildren(simulation);
            RunSimulation simulationRunner = new RunSimulation(this, simulation, doClone);

            Links.Resolve(simulationRunner);
            simulationRunner.Run(new System.Threading.CancellationTokenSource());
        }
Esempio n. 9
0
        /// <summary>Create a simulations object by reading the specified filename</summary>
        /// <param name="FileName">Name of the file.</param>
        /// <returns></returns>
        /// <exception cref="System.Exception">Simulations.Read() failed. Invalid simulation file.\n</exception>
        public static Simulations Read(string FileName)
        {
            // Run the converter.
            Converter.ConvertToLatestVersion(FileName);

            // Deserialise
            Simulations simulations = XmlUtilities.Deserialise(FileName, Assembly.GetExecutingAssembly()) as Simulations;

            if (simulations != null)
            {
                // Set the filename
                simulations.FileName = FileName;
                simulations.SetFileNameInAllSimulations();

                // Call the OnDeserialised method in each model.
                object[] args = new object[] { true };
                foreach (Model model in Apsim.ChildrenRecursively(simulations))
                {
                    Apsim.CallEventHandler(model, "Deserialised", args);
                }

                // Parent all models.
                simulations.Parent = null;
                Apsim.ParentAllChildren(simulations);

                // Call OnLoaded in all models.
                simulations.LoadErrors = new List <Exception>();
                foreach (Model child in Apsim.ChildrenRecursively(simulations))
                {
                    try
                    {
                        Apsim.CallEventHandler(child, "Loaded", null);
                    }
                    catch (ApsimXException err)
                    {
                        simulations.LoadErrors.Add(err);
                    }
                    catch (Exception err)
                    {
                        err.Source = child.Name;
                        simulations.LoadErrors.Add(err);
                    }
                }
            }
            else
            {
                throw new Exception("Simulations.Read() failed. Invalid simulation file.\n");
            }
            return(simulations);
        }
Esempio n. 10
0
        /// <summary>
        /// Create a simulations model
        /// </summary>
        /// <param name="children">The child models</param>
        public static Simulations Create(IEnumerable <IModel> children)
        {
            Simulations newSimulations = new Core.Simulations();

            newSimulations.Children.AddRange(children.Cast <Model>());

            // Parent all models.
            newSimulations.Parent = null;
            Apsim.ParentAllChildren(newSimulations);

            // Call OnCreated in all models.
            Apsim.ChildrenRecursively(newSimulations).ForEach(m => m.OnCreated());

            return(newSimulations);
        }
Esempio n. 11
0
        /// <summary>Create a simulations object by reading the specified filename</summary>
        /// <param name="FileName">Name of the file.</param>
        /// <returns></returns>
        /// <exception cref="System.Exception">Simulations.Read() failed. Invalid simulation file.\n</exception>
        public static Simulations Read(string FileName)
        {
            if (!File.Exists(FileName))
            {
                throw new Exception("Cannot read file: " + FileName + ". File does not exist.");
            }

            // Run the converter.
            Stream inStream = ApsimFile.Converter.ConvertToLatestVersion(FileName);

            // Deserialise
            Simulations simulations = XmlUtilities.Deserialise(inStream, Assembly.GetExecutingAssembly()) as Simulations;

            if (simulations.Version > ApsimFile.Converter.LatestVersion)
            {
                throw new Exception("This file has previously been opened with a more recent version of Apsim. Please upgrade to a newer version to open this file.");
            }
            inStream.Close();

            if (simulations != null)
            {
                // Set the filename
                simulations.FileName = FileName;
                simulations.SetFileNameInAllSimulations();

                // Call the OnDeserialised method in each model.
                Events   events = new Core.Events(simulations);
                object[] args   = new object[] { true };
                events.Publish("Deserialised", args);

                // Parent all models.
                simulations.Parent = null;
                Apsim.ParentAllChildren(simulations);

                // Call OnLoaded in all models.
                LoadedEventArgs loadedArgs = new LoadedEventArgs();
                events.Publish("Loaded", new object[] { simulations, loadedArgs });
                if (loadedArgs.errors.Count > 0)
                {
                    simulations.LoadErrors = new List <Exception>();
                    simulations.LoadErrors.AddRange(loadedArgs.errors);
                }
            }

            return(simulations);
        }
Esempio n. 12
0
 /// <summary>
 /// We have just been deserialised. If from XML then load our model
 /// from resource.
 /// </summary>
 public override void OnCreated()
 {
     // lookup the resource get the xml and then deserialise to a model.
     if (ResourceName != null && ResourceName != "")
     {
         string contents = Properties.Resources.ResourceManager.GetString(ResourceName);
         if (contents != null)
         {
             List <Exception> creationExceptions;
             Model            ModelFromResource = ApsimFile.FileFormat.ReadFromString <Model>(contents, out creationExceptions);
             Children.Clear();
             Children.AddRange(ModelFromResource.Children);
             CopyPropertiesFrom(ModelFromResource);
             SetNotVisible(ModelFromResource);
             Apsim.ParentAllChildren(this);
             DoSerialiseChildren = false;
         }
     }
 }
Esempio n. 13
0
        /// <summary>
        /// Create a simulations model
        /// </summary>
        /// <param name="children">The child models</param>
        public static Simulations Create(IEnumerable <Model> children)
        {
            Simulations newSimulations = new Core.Simulations();

            newSimulations.Children.AddRange(children);

            // Call the OnDeserialised method in each model.
            Events events = new Core.Events(newSimulations);

            object[] args = new object[] { true };
            events.Publish("Deserialised", args);

            // Parent all models.
            newSimulations.Parent = null;
            Apsim.ParentAllChildren(newSimulations);

            // Call OnLoaded in all models.
            newSimulations.LoadErrors = events.Publish("Loaded", null);
            return(newSimulations);
        }
Esempio n. 14
0
        /// <summary>
        /// We have just been deserialised. If from XML then load our model
        /// from resource.
        /// </summary>
        public override void OnCreated()
        {
            // lookup the resource get the xml and then deserialise to a model.
            if (!string.IsNullOrEmpty(ResourceName))
            {
                string contents = ReflectionUtilities.GetResourceAsString("Models.Resources." + ResourceName + ".json");
                if (contents != null)
                {
                    Model modelFromResource = GetResourceModel();
                    modelFromResource.Enabled = Enabled;

                    Children.RemoveAll(c => modelFromResource.Children.Contains(c, new ModelComparer()));
                    Children.InsertRange(0, modelFromResource.Children);

                    CopyPropertiesFrom(modelFromResource);
                    SetNotVisible(modelFromResource);
                    Apsim.ParentAllChildren(this);
                }
            }
        }
        /// <summary>
        /// We have just been deserialised. If from XML then load our model
        /// from resource.
        /// </summary>
        public override void OnCreated()
        {
            // lookup the resource get the xml and then deserialise to a model.
            if (!string.IsNullOrEmpty(ResourceName))
            {
                var contents = ReflectionUtilities.GetResourceAsString(FullResourceName);
                if (contents != null)
                {
                    Model modelFromResource = GetResourceModel();
                    modelFromResource.Enabled = Enabled;

                    Children.RemoveAll(c => modelFromResource.Children.Contains(c, new ModelComparer()));
                    Children.InsertRange(0, modelFromResource.Children);

                    CopyPropertiesFrom(modelFromResource);

                    // Make the model readonly if it's not under replacements.
                    SetNotVisible(modelFromResource, Apsim.Ancestor <Replacements>(this) == null);
                    Apsim.ParentAllChildren(this);
                }
            }
        }
Esempio n. 16
0
        /// <summary>
        /// Runs the simulation on the current thread and waits for the simulation
        /// to complete before returning to caller. Simulation is NOT cloned before
        /// running. Use instance of Runner to get more options for running a
        /// simulation or groups of simulations.
        /// </summary>
        /// <param name="cancelToken">Is cancellation pending?</param>
        public void Run(CancellationTokenSource cancelToken = null)
        {
            // If the cancelToken is null then give it a default one. This can happen
            // when called from the unit tests.
            if (cancelToken == null)
            {
                cancelToken = new CancellationTokenSource();
            }

            // Remove disabled models.
            RemoveDisabledModels(this);

            // If this simulation was not created from deserialisation then we need
            // to parent all child models correctly and call OnCreated for each model.
            bool hasBeenDeserialised = Children.Count > 0 && Children[0].Parent == this;

            if (!hasBeenDeserialised)
            {
                // Parent all models.
                Apsim.ParentAllChildren(this);

                // Call OnCreated in all models.
                Apsim.ChildrenRecursively(this).ForEach(m => m.OnCreated());
            }

            if (Services == null || Services.Count < 1)
            {
                Services = new List <object>();
                IDataStore storage = Apsim.Find(this, typeof(IDataStore)) as IDataStore;
                if (storage != null)
                {
                    Services.Add(Apsim.Find(this, typeof(IDataStore)));
                }
            }

            var links  = new Links(Services);
            var events = new Events(this);

            try
            {
                // Connect all events.
                events.ConnectEvents();

                // Resolve all links
                links.Resolve(this, true);

                // Invoke our commencing event to let all models know we're about to start.
                Commencing?.Invoke(this, new EventArgs());

                // Begin running the simulation.
                DoCommence?.Invoke(this, new CommenceArgs()
                {
                    CancelToken = cancelToken
                });
            }
            catch (Exception err)
            {
                // Exception occurred. Write error to summary.
                string errorMessage = "ERROR in file: " + FileName + Environment.NewLine +
                                      "Simulation name: " + Name + Environment.NewLine;
                errorMessage += err.ToString();

                summary?.WriteError(this, errorMessage);

                // Rethrow exception
                throw new Exception(errorMessage, err);
            }
            finally
            {
                // Signal that the simulation is complete.
                Completed?.Invoke(this, new EventArgs());

                // Disconnect our events.
                events.DisconnectEvents();

                // Unresolve all links.
                links.Unresolve(this, true);
            }
        }