Exemple #1
0
        /// <summary>Make model substitutions if necessary.</summary>
        /// <param name="model">The model to make substitutions in.</param>
        public void MakeSubstitutions(IModel model)
        {
            IModel replacements = Apsim.Child(this, "Replacements");

            if (replacements != null)
            {
                foreach (IModel replacement in replacements.Children)
                {
                    foreach (IModel match in Apsim.FindAll(model))
                    {
                        if (!(match is Simulation) && match.Name.Equals(replacement.Name, StringComparison.InvariantCultureIgnoreCase))
                        {
                            // Do replacement.
                            IModel newModel = Apsim.Clone(replacement);
                            int    index    = match.Parent.Children.IndexOf(match as Model);
                            match.Parent.Children.Insert(index, newModel as Model);
                            newModel.Parent = match.Parent;
                            match.Parent.Children.Remove(match as Model);
                            // If we're doing substitutions for an entire Simulation,
                            // the Loaded event will be issued later. Otherwise, issue one now
                            if (!(model is Simulation))
                            {
                                Events          events     = new Events(newModel);
                                LoadedEventArgs loadedArgs = new LoadedEventArgs();
                                events.Publish("Loaded", new object[] { newModel, loadedArgs });
                            }
                        }
                    }
                }
            }
        }
Exemple #2
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;
         }
     }
 }
Exemple #3
0
        /// <summary>Make model substitutions if necessary.</summary>
        /// <param name="simulations">The simulations to make substitutions in.</param>
        private void MakeSubstitutions(Simulation[] simulations)
        {
            IModel replacements = Apsim.Child(this, "Replacements");

            if (replacements != null)
            {
                foreach (IModel replacement in replacements.Children)
                {
                    foreach (Simulation simulation in simulations)
                    {
                        foreach (IModel match in Apsim.FindAll(simulation, replacement.GetType()))
                        {
                            if (match.Name.Equals(replacement.Name, StringComparison.InvariantCultureIgnoreCase))
                            {
                                // Do replacement.
                                IModel newModel = Apsim.Clone(replacement);
                                int    index    = match.Parent.Children.IndexOf(match as Model);
                                match.Parent.Children.Insert(index, newModel as Model);
                                newModel.Parent = match.Parent;
                                match.Parent.Children.Remove(match as Model);
                                CallOnLoaded(newModel);
                            }
                        }
                    }
                }
            }
        }
        private Model GetResourceModel()
        {
            if (string.IsNullOrEmpty(FullResourceName))
            {
                return(null);
            }

            string contents = ReflectionUtilities.GetResourceAsString(FullResourceName);

            if (string.IsNullOrEmpty(contents))
            {
                return(null);
            }

            Model modelFromResource = ApsimFile.FileFormat.ReadFromString <Model>(contents, out List <Exception> errors);

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

            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;
                }
            }

            return(modelFromResource);
        }
Exemple #5
0
        /// <summary>Make model substitutions if necessary.</summary>
        /// <param name="model">The model to make substitutions in.</param>
        public void MakeSubstitutions(IModel model)
        {
            IModel replacements = Apsim.Child(this, "Replacements");

            if (replacements != null)
            {
                foreach (IModel replacement in replacements.Children)
                {
                    foreach (IModel match in Apsim.FindAll(model))
                    {
                        if (!(match is Simulation) && match.Name.Equals(replacement.Name, StringComparison.InvariantCultureIgnoreCase))
                        {
                            // Do replacement.
                            IModel newModel = Apsim.Clone(replacement);
                            int    index    = match.Parent.Children.IndexOf(match as Model);
                            match.Parent.Children.Insert(index, newModel as Model);
                            newModel.Parent = match.Parent;
                            match.Parent.Children.Remove(match as Model);
                            Events events = new Events(newModel);
                            events.Publish("Loaded", null);
                        }
                    }
                }
            }
        }
Exemple #6
0
        /// <summary>Run all simulations.</summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void Run(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            this.ErrorMessage = null;

            // Get a reference to the JobManager so that we can add jobs to it.
            jobManager = e.Argument as JobManager;

            // Get a reference to our child DataStore.
            DataStore store = Apsim.Child(this, typeof(DataStore)) as DataStore;

            // Remove old simulation data.
            store.RemoveUnwantedSimulations(this);

            Simulation[] simulationsToRun;
            if (SimulationToRun == null)
            {
                // As we are going to run all simulations, we can delete all tables in the DataStore. This
                // will clean up order of columns in the tables and removed unused ones.
                store.DeleteAllTables();

                store.Disconnect();

                simulationsToRun = Simulations.FindAllSimulationsToRun(this);
            }
            else
            {
                simulationsToRun = Simulations.FindAllSimulationsToRun(SimulationToRun);
            }

            MakeSubstitutions(simulationsToRun);

            NumToRun     = simulationsToRun.Length;
            NumCompleted = 0;

            if (NumToRun == 1)
            {
                // Skip running in another thread.
                simulationsToRun[0].Commencing -= OnSimulationCommencing;
                simulationsToRun[0].Commencing += OnSimulationCommencing;
                simulationsToRun[0].Run(null, null);
            }
            else
            {
                foreach (Simulation simulation in simulationsToRun)
                {
                    simulation.Commencing -= OnSimulationCommencing;
                    simulation.Commencing += OnSimulationCommencing;
                    jobManager.AddJob(simulation);
                }
            }
        }
Exemple #7
0
        /// <summary>Writes documentation for this function by adding to the list of documentation tags.</summary>
        /// <param name="tags">The list of tags to add to.</param>
        /// <param name="headingLevel">The level (e.g. H2) of the headings.</param>
        /// <param name="indent">The level of indentation 1, 2, 3 etc.</param>
        public override void Document(List <AutoDocumentation.ITag> tags, int headingLevel, int indent)
        {
            if (IncludeInDocumentation)
            {
                // add a heading.
                tags.Add(new AutoDocumentation.Heading(Name, headingLevel));

                if (ShowPageOfGraphs)
                {
                    foreach (Memo memo in Apsim.Children(this, typeof(Memo)))
                    {
                        memo.Document(tags, headingLevel, indent);
                    }

                    if (Apsim.Children(this, typeof(Experiment)).Count > 0)
                    {
                        // Write Phase Table
                        tags.Add(new AutoDocumentation.Paragraph("**List of experiments.**", indent));
                        DataTable tableData = new DataTable();
                        tableData.Columns.Add("Experiment Name", typeof(string));
                        tableData.Columns.Add("Design (Number of Treatments)", typeof(string));

                        foreach (IModel child in Apsim.Children(this, typeof(Experiment)))
                        {
                            IModel Factors = Apsim.Child(child, typeof(Factors));
                            string Design  = "";
                            foreach (IModel factor in Apsim.Children(Factors, typeof(Factor)))
                            {
                                if (Design != "")
                                {
                                    Design += " x ";
                                }
                                Design += factor.Name;
                            }
                            Design += " (" + (child as Experiment).GetSimulationNames().ToArray().Length + ")";

                            DataRow row = tableData.NewRow();
                            row[0] = child.Name;
                            row[1] = Design;
                            tableData.Rows.Add(row);
                        }
                        tags.Add(new AutoDocumentation.Table(tableData, indent));
                    }
                    int           pageNumber = 1;
                    int           i          = 0;
                    List <IModel> children   = Apsim.Children(this, typeof(Graph.Graph));
                    while (i < children.Count)
                    {
                        GraphPage page = new GraphPage();
                        page.name = Name + pageNumber;
                        for (int j = i; j < i + 6 && j < children.Count; j++)
                        {
                            if (children[j].IncludeInDocumentation)
                            {
                                page.graphs.Add(children[j] as Graph.Graph);
                            }
                        }
                        if (page.graphs.Count > 0)
                        {
                            tags.Add(page);
                        }
                        i += 6;
                        pageNumber++;
                    }

                    // Document everything else other than graphs
                    foreach (IModel model in Children)
                    {
                        if (!(model is Graph.Graph) && !(model is Memo))
                        {
                            model.Document(tags, headingLevel + 1, indent);
                        }
                    }
                }
                else
                {
                    foreach (IModel model in Children)
                    {
                        model.Document(tags, headingLevel + 1, indent);
                    }
                }
            }
        }
Exemple #8
0
            /// <summary>Run the jobs.</summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            public void Run(object sender, System.ComponentModel.DoWorkEventArgs e)
            {
                JobManager jobManager = e.Argument as JobManager;

                List <JobManager.IRunnable> jobs = new List <JobManager.IRunnable>();

                DataStore store = Apsim.Child(simulations, typeof(DataStore)) as DataStore;

                Simulation[] simulationsToRun;
                if (model is Simulations)
                {
                    // As we are going to run all simulations, we can delete all tables in the DataStore. This
                    // will clean up order of columns in the tables and removed unused ones.
                    store.DeleteAllTables();
                    simulationsToRun = Simulations.FindAllSimulationsToRun(simulations);
                }
                else
                {
                    store.RemoveUnwantedSimulations(simulations);

                    if (model is Simulation)
                    {
                        if (model.Parent == null)
                        {
                            // model is already a cloned simulation, probably from user running a single
                            // simulation from an experiment.
                            simulationsToRun = new Simulation[1] {
                                model as Simulation
                            };
                        }
                        else
                        {
                            simulationsToRun = new Simulation[1] {
                                Apsim.Clone(model as Simulation) as Simulation
                            };
                            Simulations.CallOnLoaded(simulationsToRun[0]);
                        }
                    }
                    else
                    {
                        simulationsToRun = Simulations.FindAllSimulationsToRun(model);
                    }
                }

                store.Disconnect();

                simulations.MakeSubstitutions(simulationsToRun);

                foreach (Simulation simulation in simulationsToRun)
                {
                    jobs.Add(simulation);
                    jobManager.AddJob(simulation);
                }

                // Wait until all our jobs are all finished.
                while (AreSomeJobsRunning(jobs))
                {
                    Thread.Sleep(200);
                }

                // Collect all error messages.
                foreach (Simulation job in simulationsToRun)
                {
                    if (job.ErrorMessage != null)
                    {
                        ErrorMessage += job.ErrorMessage + Environment.NewLine;
                    }
                }

                // <summary>Call the all completed event in all models.</summary>
                object[] args = new object[] { this, new EventArgs() };
                foreach (Model childModel in Apsim.ChildrenRecursively(simulations))
                {
                    try
                    {
                        Apsim.CallEventHandler(childModel, "AllCompleted", args);
                    }
                    catch (Exception err)
                    {
                        ErrorMessage += "Error in file: " + simulations.FileName + Environment.NewLine;
                        ErrorMessage += err.ToString() + Environment.NewLine + Environment.NewLine;
                    }
                }

                if (ErrorMessage != null)
                {
                    throw new Exception(ErrorMessage);
                }
            }