示例#1
0
        /// <summary>
        /// Apply this FactorValue to the specified simulation
        /// </summary>
        public void ApplyToSimulation(Simulation newSimulation)
        {
            if (paths.Count > 1 && paths.Count != values.Count)
                throw new Exception("The number of factor paths does not match the number of factor values");

            // Multiple child factor values specified - apply each one.
            for (int i = 0; i != paths.Count; i++)
            {
                if (values[i] is string)
                    ApplyStringAsValue(newSimulation, paths[i], values[i].ToString());
                else
                    ApplyModelReplacement(newSimulation, paths[i], values[i] as IModel);

            }

            string newSimulationName = newSimulation.Name;
            newSimulation.Name = newSimulationName;
        }
示例#2
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ExportNodeCommand"/> class.
 /// </summary>
 /// <param name="explorerPresenter">The explorer presenter</param>
 /// <param name="simulation">The simulation to document</param>
 public WriteDebugDoc(ExplorerPresenter explorerPresenter, Simulation simulation)
 {
     this.explorerPresenter = explorerPresenter;
     this.simulation = simulation;
 }
示例#3
0
文件: Summary.cs 项目: hol353/ApsimX
        /// <summary>
        /// Create an initial conditions table in the DataStore.
        /// </summary>
        /// <param name="simulation">The simulation to create an table for</param>
        private static void CreateInitialConditionsTable(Simulation simulation)
        {
            // Create our initial conditions table.
            DataTable initialConditionsTable = new DataTable("InitialConditions");
            initialConditionsTable.Columns.Add("ModelPath", typeof(string));
            initialConditionsTable.Columns.Add("Name", typeof(string));
            initialConditionsTable.Columns.Add("Description", typeof(string));
            initialConditionsTable.Columns.Add("DataType", typeof(string));
            initialConditionsTable.Columns.Add("Units", typeof(string));
            initialConditionsTable.Columns.Add("DisplayFormat", typeof(string));
            initialConditionsTable.Columns.Add("Total", typeof(int));
            initialConditionsTable.Columns.Add("Value", typeof(string));

            initialConditionsTable.Rows.Add(
                new object[] { Apsim.FullPath(simulation), "Simulation name", "Simulation name", "String", string.Empty, string.Empty, false, simulation.Name });
            initialConditionsTable.Rows.Add(
                new object[] { Apsim.FullPath(simulation), "APSIM version", "APSIM version", "String", string.Empty, string.Empty, false, simulation.ApsimVersion });
            initialConditionsTable.Rows.Add(
                new object[] { Apsim.FullPath(simulation), "Run on", "Run on", "String", string.Empty, string.Empty, false, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") });

            // Get all model properties and store in 'initialConditionsTable'
            foreach (Model model in Apsim.FindAll(simulation))
            {
                string relativeModelPath = Apsim.FullPath(model).Replace(Apsim.FullPath(simulation) + ".", string.Empty);
                List<VariableProperty> properties = new List<VariableProperty>();

                FindAllProperties(model, properties);

                foreach (VariableProperty property in properties)
                {
                    string value = property.ValueWithArrayHandling.ToString();
                    if (value != string.Empty)
                    {
                        if (value != null && property.DataType == typeof(DateTime))
                        {
                            value = ((DateTime)property.Value).ToString("yyyy-MM-dd HH:mm:ss");
                        }

                        bool showTotal = !double.IsNaN(property.Total);

                        initialConditionsTable.Rows.Add(new object[]
                          {
                              relativeModelPath,
                              property.Name,
                              property.Description,
                              property.DataType.Name,
                              property.Units,
                              property.Format,
                              showTotal,
                              value
                          });
                    }
                }
            }

            // Write to data store.
            DataStore dataStore = new DataStore(simulation);
            dataStore.DeleteOldContentInTable(simulation.Name, "InitialConditions");
            dataStore.WriteTable(simulation.Name, "InitialConditions", initialConditionsTable);
            dataStore.Disconnect();
        }
示例#4
0
文件: Clock.cs 项目: hol353/ApsimX
        private void OnDoCommence(object sender, Simulation.CommenceArgs e)
        {
            if (DoInitialSummary != null)
                DoInitialSummary.Invoke(this, args);

            if (StartOfSimulation != null)
                StartOfSimulation.Invoke(this, args);

            while (Today <= EndDate)
            {
                // If this is being run on a background worker thread then check for cancellation
                if (e.workerThread.CancellationPending)
                {
                    Summary.WriteMessage(this, "Simulation cancelled");
                    return;
                }

                if (DoWeather != null)
                    DoWeather.Invoke(this, args);

                if (DoDailyInitialisation != null)
                    DoDailyInitialisation.Invoke(this, args);

                if (StartOfDay != null)
                    StartOfDay.Invoke(this, args);

                if (Today.Day == 1 && StartOfMonth != null)
                {
                    StartOfMonth.Invoke(this, args);

                    if (WFRequestResources != null)
                        WFRequestResources.Invoke(this, args);
                    if (WFDoResourceAllocation != null)
                        WFDoResourceAllocation.Invoke(this, args);
                    if (WFResourcesAllocated != null)
                        WFResourcesAllocated.Invoke(this, args);
                    if (WFRuminantGraze != null)
                        WFRuminantGraze.Invoke(this, args);
                    if (WFAnimalFeed != null)
                        WFAnimalFeed.Invoke(this, args);
                    if (WFAnimalGrowth != null)
                        WFAnimalGrowth.Invoke(this, args);
                    if (WFAnimalBreed != null)
                        WFAnimalBreed.Invoke(this, args);
                    if (WFAnimalManageHerd != null)
                        WFAnimalManageHerd.Invoke(this, args);
                    if (WFAnimalTrade != null)
                        WFAnimalTrade.Invoke(this, args);
                    if (WFAgeResources != null)
                        WFAgeResources.Invoke(this, args);
                }

                if (Today.DayOfYear == 1 && StartOfYear != null)
                    StartOfYear.Invoke(this, args);

                if (Today.DayOfWeek == DayOfWeek.Sunday && StartOfWeek != null)
                    StartOfWeek.Invoke(this, args);

                if (Today.DayOfWeek == DayOfWeek.Saturday && EndOfWeek != null)
                    EndOfWeek.Invoke(this, args);

                if (DoManagement != null)
                    DoManagement.Invoke(this, args);

                if (DoEnergyArbitration != null)
                    DoEnergyArbitration.Invoke(this, args);

                if (DoSoilWaterMovement != null)
                    DoSoilWaterMovement.Invoke(this, args);

                if (DoSoilOrganicMatter != null)
                    DoSoilOrganicMatter.Invoke(this, args);

                if (DoSurfaceOrganicMatterDecomposition != null)
                    DoSurfaceOrganicMatterDecomposition.Invoke(this, args);
                if (Today.DayOfYear == 16)
                { }
                if (DoWaterArbitration != null)
                    DoWaterArbitration.Invoke(this, args);

                if (DoPhenology != null)
                    DoPhenology.Invoke(this, args);

                if (DoPotentialPlantGrowth != null)
                    DoPotentialPlantGrowth.Invoke(this, args);

                if (DoPotentialPlantPartioning != null)
                    DoPotentialPlantPartioning.Invoke(this, args);

                if (DoNutrientArbitration != null)
                    DoNutrientArbitration.Invoke(this, args);

                if (DoActualPlantPartioning != null)
                    DoActualPlantPartioning.Invoke(this, args);

                if (DoActualPlantGrowth != null)
                    DoActualPlantGrowth.Invoke(this, args);

                if (DoPlantGrowth != null)
                    DoPlantGrowth.Invoke(this, args);

                if (DoUpdate != null)
                    DoUpdate.Invoke(this, args);

                if (DoManagementCalculations != null)
                    DoManagementCalculations.Invoke(this, args);

                if (DoStock != null)
                    DoStock.Invoke(this, args);

                if (DoReportCalculations != null)
                    DoReportCalculations.Invoke(this, args);

                if (Today == EndDate && EndOfSimulation != null)
                    EndOfSimulation.Invoke(this, args);

                if (Today.Day == 31 && Today.Month == 12 && EndOfYear != null)
                    EndOfYear.Invoke(this, args);

                if (Today.AddDays(1).Day == 1 && EndOfMonth != null) // is tomorrow the start of a new month?
                    EndOfMonth.Invoke(this, args);

                if (EndOfDay != null)
                    EndOfDay.Invoke(this, args);

                if (DoReport != null)
                    DoReport.Invoke(this, args);

                Today = Today.AddDays(1);
            }

            Summary.WriteMessage(this, "Simulation terminated normally");
        }
示例#5
0
文件: APITest.cs 项目: hol353/ApsimX
        public void Initialise()
        {
            string tempFolder = Path.Combine(Path.GetTempPath(), "UnitTests");
            Directory.CreateDirectory(tempFolder);
            Directory.SetCurrentDirectory(tempFolder);
            FileStream oldfile = new FileStream("Continuous_Wheat.apsim", FileMode.Create);
            oldfile.Write(UnitTests.Properties.Resources.Continuous_Wheat, 0, UnitTests.Properties.Resources.Continuous_Wheat.Length);
            oldfile.Close();

            FileStream f = new FileStream("Test.apsimx", FileMode.Create);
            f.Write(UnitTests.Properties.Resources.TestFile, 0, UnitTests.Properties.Resources.TestFile.Length);
            f.Close();
            FileStream w = new FileStream("Goondiwindi.met", FileMode.Create);
            w.Write(UnitTests.Properties.Resources.Goondiwindi, 0, UnitTests.Properties.Resources.Goondiwindi.Length);
            w.Close();
            this.simulations = Simulations.Read("Test.apsimx");

            string sqliteSourceFileName = this.FindSqlite3DLL();

            string sqliteFileName = Path.Combine(Directory.GetCurrentDirectory(), "sqlite3.dll");
            if (!File.Exists(sqliteFileName))
            {
                File.Copy(sqliteSourceFileName, sqliteFileName);
            }

            this.simulation = this.simulations.Children[0] as Simulation;
            this.simulation.StartRun();
        }
示例#6
0
        /// <summary>
        /// Replace the object specified by 'path' in 'newSimulation' with the specified 'value'
        /// </summary>
        private static void ApplyModelReplacement(Simulation newSimulation, string path, IModel value)
        {
            IModel newModel = Apsim.Clone(value);
            IModel modelToReplace = newSimulation.Get(path) as IModel;
            if (modelToReplace == null)
                throw new Exception("Cannot find model to replace. Model path: " + path);

            int index = modelToReplace.Parent.Children.IndexOf(modelToReplace as Model);
            if (index == -1)
                throw new Exception("Cannot find model to replace. Model path: " + path);

            modelToReplace.Parent.Children.RemoveAt(index);
            modelToReplace.Parent.Children.Insert(index, newModel as Model);
            newModel.Name = modelToReplace.Name;
            newModel.Parent = modelToReplace.Parent;

            Apsim.CallEventHandler(newModel, "Loaded", null);
        }
示例#7
0
 /// <summary>
 /// Use the name of this object as a value to insert into the specified 'newSimulation'
 /// </summary>
 private static void ApplyStringAsValue(Simulation newSimulation, string path, string name)
 {
     object originalValue = newSimulation.Get(path);
     object newValue;
     if (originalValue is DateTime)
         newValue = DateTime.Parse(name, CultureInfo.InvariantCulture);
     else if (originalValue is float)
         newValue = Convert.ToSingle(name, CultureInfo.InvariantCulture);
     else if (originalValue is double)
         newValue = Convert.ToDouble(name, CultureInfo.InvariantCulture);
     else if (originalValue is int)
         newValue = Convert.ToInt32(name, CultureInfo.InvariantCulture);
     else if (originalValue is string)
         newValue = Convert.ToString(name);
     else
         newValue = name;
     newSimulation.Set(path, newValue);
 }
示例#8
0
        /// <summary>Find all report models and give them the factor values.</summary>
        /// <param name="factorValues">The factor values to send to each report model.</param>
        /// <param name="simulation">The simulation to search for report models.</param>
        private void PushFactorsToReportModels(Simulation simulation, List<FactorValue> factorValues)
        {
            List<string> names = new List<string>();
            List<string> values = new List<string>();

            foreach (FactorValue factorValue in factorValues)
            {
                Factor topLevelFactor = factorValue.Factor;
                if (topLevelFactor.Parent is Factor)
                    topLevelFactor = topLevelFactor.Parent as Factor;
                string name = topLevelFactor.Name;
                string value = factorValue.Name.Replace(topLevelFactor.Name, "");
                if (value == string.Empty)
                {
                    name = "Factors";
                    value = factorValue.Name;
                }
                names.Add(name);
                values.Add(value);
            }

            foreach (Report.Report report in Apsim.ChildrenRecursively(simulation, typeof(Report.Report)))
            {
                report.ExperimentFactorNames = names;
                report.ExperimentFactorValues = values;
            }
        }
示例#9
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);
                     }
                 }
             }
         }
     }
 }
示例#10
0
        /// <summary>Documents the specified model.</summary>
        /// <param name="modelNameToDocument">The model name to document.</param>
        /// <param name="tags">The auto doc tags.</param>
        /// <param name="headingLevel">The starting heading level.</param>
        public void DocumentModel(string modelNameToDocument, List <AutoDocumentation.ITag> tags, int headingLevel)
        {
            Simulation simulation = Apsim.Find(this, typeof(Simulation)) as Simulation;

            if (simulation != null)
            {
                // Find the model of the right name.
                IModel modelToDocument = Apsim.Find(simulation, modelNameToDocument);

                // If not found then find a model of the specified type.
                if (modelToDocument == null)
                {
                    modelToDocument = Apsim.Get(simulation, "[" + modelNameToDocument + "]") as IModel;
                }

                // If the simulation has the same name as the model we want to document, dig a bit deeper
                if (modelToDocument == simulation)
                {
                    modelToDocument = Apsim.ChildrenRecursivelyVisible(simulation).FirstOrDefault(m => m.Name.Equals(modelNameToDocument, StringComparison.OrdinalIgnoreCase));
                }

                // If still not found throw an error.
                if (modelToDocument != null)
                {
                    // Get the path of the model (relative to parentSimulation) to document so that
                    // when replacements happen below we will point to the replacement model not the
                    // one passed into this method.
                    string pathOfSimulation      = Apsim.FullPath(simulation) + ".";
                    string pathOfModelToDocument = Apsim.FullPath(modelToDocument).Replace(pathOfSimulation, "");

                    // Clone the simulation
                    Simulation clonedSimulation = Apsim.Clone(simulation) as Simulation;

                    // Make any substitutions.
                    MakeSubstitutions(clonedSimulation);

                    // Now use the path to get the model we want to document.
                    modelToDocument = Apsim.Get(clonedSimulation, pathOfModelToDocument) as IModel;

                    if (modelToDocument == null)
                    {
                        throw new Exception("Cannot find model to document: " + modelNameToDocument);
                    }

                    // resolve all links in cloned simulation.
                    Links.Resolve(clonedSimulation);

                    modelToDocument.IncludeInDocumentation = true;
                    foreach (IModel child in Apsim.ChildrenRecursively(modelToDocument))
                    {
                        child.IncludeInDocumentation = true;
                    }

                    // Document the model.
                    modelToDocument.Document(tags, headingLevel, 0);

                    // Unresolve links.
                    Links.Unresolve(clonedSimulation);
                }
            }
        }