Example #1
0
        /// <summary>
        /// Return a list of list of factorvalue objects for all permutations.
        /// </summary>
        public List <List <FactorValue> > AllCombinations()
        {
            Factors Factors = Apsim.Child(this, typeof(Factors)) as Factors;

            // Create a list of list of factorValues so that we can do permutations of them.
            List <List <FactorValue> > allValues = new List <List <FactorValue> >();

            if (Factors != null)
            {
                bool doFullFactorial = false;
                foreach (Factor factor in Factors.factors)
                {
                    List <FactorValue> factorValues = factor.CreateValues();
                    allValues.Add(factorValues);
                    doFullFactorial = doFullFactorial || factorValues.Count > 1;
                }
                if (doFullFactorial)
                {
                    return(MathUtilities.AllCombinationsOf <FactorValue>(allValues.ToArray()));
                }
                else
                {
                    return(allValues);
                }
            }
            return(null);
        }
Example #2
0
        /// <summary>
        /// Parse the specification into paths and values.
        /// </summary>
        /// <param name="specification">The specification to parse.</param>
        /// <param name="allPaths">The list of paths to add to.</param>
        /// <param name="allValues">The list of values to add to.</param>
        private void ParseSpecification(string specification, List <string> allPaths, List <object> allValues)
        {
            string path = specification;
            object value;

            if (path.Contains("="))
            {
                value = StringUtilities.SplitOffAfterDelimiter(ref path, "=").Trim();
                if (value == null)
                {
                    throw new Exception("Cannot find any values on the specification line: " + specification);
                }

                allPaths.Add(path.Trim());
                allValues.Add(value.ToString().Trim());
            }
            else
            {
                // Find the model that we are to replace.
                var experiment     = Apsim.Parent(this, typeof(Experiment)) as Experiment;
                var baseSimulation = Apsim.Child(experiment, typeof(Simulation));
                var modelToReplace = Apsim.Get(baseSimulation, path) as IModel;

                // Now find a child of that type.
                value = Apsim.Child(this, modelToReplace.GetType());

                allPaths.Add(path.Trim());
                allValues.Add(value);
            }
        }
Example #3
0
        /// <summary>
        /// Calculate a list of fall combinations of factors.
        /// </summary>
        private List <List <CompositeFactor> > CalculateAllCombinations()
        {
            Factors Factors = Apsim.Child(this, typeof(Factors)) as Factors;

            // Create a list of list of factorValues so that we can do permutations of them.
            List <List <CompositeFactor> > allValues = new List <List <CompositeFactor> >();

            if (Factors != null)
            {
                foreach (Factor factor in Factors.factors)
                {
                    if (factor.Enabled)
                    {
                        allValues.Add(factor.GetCompositeFactors());
                    }
                }
                var allCombinations = MathUtilities.AllCombinationsOf <CompositeFactor>(allValues.ToArray());

                // Remove disabled simulations.
                if (DisabledSimNames != null)
                {
                    allCombinations.RemoveAll(comb => DisabledSimNames.Contains(GetName(comb)));
                }

                return(allCombinations);
            }
            else
            {
                return(null);
            }
        }
Example #4
0
        public void EnsureAllToolsRun()
        {
            string           json = ReflectionUtilities.GetResourceAsString("UnitTests.Core.PostSimulationTool.apsimx");
            List <Exception> errors;
            Simulations      sims = FileFormat.ReadFromString <Simulations>(json, out errors);

            Assert.AreEqual(0, errors.Count);

            IModel script = Apsim.Child(Apsim.Find(sims, "Tool2"), "Script");

            Assert.NotNull(script);

            Simulation sim = Apsim.Find(sims, typeof(Simulation)) as Simulation;

            Assert.NotNull(sim);

            bool hasBeenRun = (bool)ReflectionUtilities.GetValueOfFieldOrProperty("HasBeenRun", script);

            Assert.False(hasBeenRun);

            IJobManager jobManager = new RunOrganiser(sims, sim, false);
            IJobRunner  jobRunner  = new JobRunnerAsync();

            jobRunner.Run(jobManager, wait: true);

            hasBeenRun = (bool)ReflectionUtilities.GetValueOfFieldOrProperty("HasBeenRun", script);
            Assert.True(hasBeenRun, "Failure in a post simulation tool prevented another post simulation tool from running.");
        }
Example #5
0
        public void TestEditingNullProperty()
        {
            ExplorerPresenter explorerPresenter = UITestUtilities.OpenResourceFileInTab(Assembly.GetExecutingAssembly(),
                                                                                        "UnitTests.ApsimNG.Resources.SampleFiles.NullSample.apsimx");

            GtkUtilities.WaitForGtkEvents();

            Simulations sims   = explorerPresenter.ApsimXFile;
            Soil        soil   = Apsim.Find(sims, typeof(Soil)) as Soil;
            Sample      sample = Apsim.Child(soil, typeof(Sample)) as Sample;

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

            Assert.IsNull(sample.NO3N);

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

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

            // The sample's NO3N property should now be an array containing 1.1.
            Assert.NotNull(sample.NO3N);
            Assert.AreEqual(new double[1] {
                1.1
            }, sample.NO3N);
        }
Example #6
0
        /// <summary>Find our children.</summary>
        public void FindChildren()
        {
            waterNode = Apsim.Child(this, typeof(Physical)) as Physical;

            Weirdo    = Apsim.Child(this, typeof(WEIRDO)) as WEIRDO;
            SoilWater = Apsim.Child(this, typeof(ISoilWater)) as ISoilWater;
            if (Weirdo == null && SoilWater == null)
            {
                throw new Exception($"{Name}: Unable to find SoilWater or WEIRDO child model");
            }
            if (Weirdo == null && waterNode == null)
            {
                throw new Exception($"{Name}: Unable to find Physical or WEIRDO child model");
            }

            SoilOrganicMatter = Apsim.Child(this, typeof(Organic)) as Organic;
            if (SoilOrganicMatter == null)
            {
                throw new Exception($"{Name}: Unable to find Organic child model");
            }

            temperatureModel = Apsim.Child(this, typeof(ISoilTemperature)) as ISoilTemperature;
            if (temperatureModel == null)
            {
                throw new Exception($"{Name}: Unable to find soil temperature child model");
            }

            Initial   = Children.Find(child => child is Sample) as Sample;
            structure = Apsim.Child(this, typeof(LayerStructure)) as LayerStructure;
        }
Example #7
0
        /// <summary>Gets a list of simulation descriptions.</summary>
        public List <SimulationDescription> GenerateSimulationDescriptions()
        {
            var baseSimulation = Apsim.Child(this, typeof(Simulation)) as Simulation;

            // Calculate all combinations.
            CalculateFactors();

            // Loop through all combinations and add a simulation description to the
            // list of simulations descriptions being returned to the caller.
            var simulationDescriptions = new List <SimulationDescription>();
            int simulationNumber       = 1;

            foreach (var combination in allCombinations)
            {
                // Create a simulation.
                var simulationName = Name + "Simulation" + simulationNumber;
                var simDescription = new SimulationDescription(baseSimulation, simulationName);
                simDescription.Descriptors.Add(new SimulationDescription.Descriptor("SimulationName", simulationName));

                // Apply each composite factor of this combination to our simulation description.
                combination.ForEach(c => c.ApplyToSimulation(simDescription));

                // Add simulation description to the return list of descriptions
                simulationDescriptions.Add(simDescription);

                simulationNumber++;
            }

            return(simulationDescriptions);
        }
Example #8
0
        /// <summary>Constructor</summary>
        /// <param name="Plant">The parant plant</param>
        /// <param name="Root">The parent root organ</param>
        /// <param name="soil">The soil in the zone.</param>
        /// <param name="depth">Root depth (mm)</param>
        /// <param name="initialDM">Initial dry matter</param>
        /// <param name="population">plant population</param>
        /// <param name="maxNConc">maximum n concentration</param>
        /// <param name="rfv">Root front velocity</param>
        /// <param name="mrd">Maximum root depth</param>
        /// <param name="remobCost">Remobilisation cost</param>
        public ZoneState(Plant Plant, Root Root, Soil soil, double depth,
                         double initialDM, double population, double maxNConc,
                         IFunction rfv, IFunction mrd, IFunction remobCost)
        {
            this.soil               = soil;
            this.plant              = Plant;
            this.root               = Root;
            this.rootFrontVelocity  = rfv;
            this.maximumRootDepth   = mrd;
            this.remobilisationCost = remobCost;

            Clear();
            Zone zone = Apsim.Parent(soil, typeof(Zone)) as Zone;

            if (zone == null)
            {
                throw new Exception("Soil " + soil + " is not in a zone.");
            }
            solutes = Apsim.Child(zone, typeof(SoluteManager)) as SoluteManager;
            if (solutes == null)
            {
                throw new Exception("Cannot find solute manager in zone");
            }
            Name = zone.Name;
            Initialise(depth, initialDM, population, maxNConc);
        }
Example #9
0
        public void SiblingsTest()
        {
            IModel        clock       = Apsim.Child(simulation, typeof(Clock));
            List <IModel> allSiblings = Apsim.Siblings(clock);

            Assert.AreEqual(allSiblings.Count, 5);
        }
Example #10
0
        /// <summary>
        /// Return a list of predicted crop names or an empty string[] if none found.
        /// </summary>
        /// <param name="soil">The soil.</param>
        /// <returns></returns>
        private static void AddPredictedCrops(Soil soil)
        {
            if (soil.SoilType != null)
            {
                string[] predictedCropNames = null;
                if (soil.SoilType.Equals("Black Vertosol", StringComparison.CurrentCultureIgnoreCase))
                {
                    predictedCropNames = BlackVertosolCropList;
                }
                else if (soil.SoilType.Equals("Grey Vertosol", StringComparison.CurrentCultureIgnoreCase))
                {
                    predictedCropNames = GreyVertosolCropList;
                }

                if (predictedCropNames != null)
                {
                    var water = Apsim.Child(soil, typeof(Water)) as Water;
                    var crops = Apsim.Children(water, typeof(SoilCrop));

                    foreach (string cropName in predictedCropNames)
                    {
                        // if a crop parameterisation already exists for this crop then don't add a predicted one.
                        if (crops.Find(c => c.Name.Equals(cropName, StringComparison.InvariantCultureIgnoreCase)) == null)
                        {
                            crops.Add(PredictedCrop(soil, cropName));
                        }
                    }
                }
            }
        }
Example #11
0
        /// <summary>Gets a list of simulation descriptions.</summary>
        public List <SimulationDescription> GenerateSimulationDescriptions()
        {
            var baseSimulation = Apsim.Child(this, typeof(Simulation)) as Simulation;

            // Calculate all combinations.
            CalculateFactors();

            // Loop through all combinations and add a simulation description to the
            // list of simulations descriptions being returned to the caller.
            var simulationDescriptions = new List <SimulationDescription>();
            int simulationNumber       = 1;

            foreach (var combination in allCombinations)
            {
                // Create a simulation.
                var simulationName = Name + "Simulation" + simulationNumber;
                var simDescription = new SimulationDescription(baseSimulation, simulationName);

                // Add some descriptors
                int path = (simulationNumber - 1) / (Parameters.Count + 1) + 1;
                simDescription.Descriptors.Add(new SimulationDescription.Descriptor("SimulationName", simulationName));
                simDescription.Descriptors.Add(new SimulationDescription.Descriptor("Path", path.ToString()));

                // Apply each composite factor of this combination to our simulation description.
                combination.ForEach(c => c.ApplyToSimulation(simDescription));

                // Add simulation description to the return list of descriptions
                simulationDescriptions.Add(simDescription);

                simulationNumber++;
            }

            Console.WriteLine($"Simulation names generated by morris:\n{string.Join("\n", simulationDescriptions.Select(s => s.Name))}");
            return(simulationDescriptions);
        }
Example #12
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)
        {
            JobSequence   parentJob       = new JobSequence();
            JobParallel   simulationJobs  = new JobParallel();
            List <string> simulationNames = new List <string>();

            FindAllSimulationsToRun(model, simulationJobs, simulationNames);
            parentJob.Jobs.Add(simulationJobs);
            parentJob.Jobs.Add(new RunAllCompletedEvent(simulations));

            // IF 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.
            // Otherwise just remove the unwanted simulations from the DataStore.
            DataStore store = Apsim.Child(simulations, typeof(DataStore)) as DataStore;

            if (model is Simulations)
            {
                store.DeleteAllTables(true);
            }
            else
            {
                store.RemoveUnwantedSimulations(simulations, simulationNames);
            }
            store.Disconnect();

            if (runTests)
            {
                foreach (Tests tests in Apsim.ChildrenRecursively(model, typeof(Tests)))
                {
                    parentJob.Jobs.Add(tests);
                }
            }
            jobManager.AddChildJob(this, parentJob);
        }
Example #13
0
        /// <summary>Standardise the specified soil with a uniform thickness.</summary>
        /// <param name="soil">The soil.</param>
        /// <returns>A standardised soil.</returns>
        public static void Standardise(Soil soil)
        {
            var waterNode      = Apsim.Child(soil, typeof(Physical)) as Physical;
            var analysisNode   = Apsim.Child(soil, typeof(Chemical)) as Chemical;
            var layerStructure = Apsim.Child(soil, typeof(LayerStructure)) as LayerStructure;

            // Determine the target layer structure.
            var targetThickness = soil.Thickness;

            if (layerStructure != null)
            {
                targetThickness = layerStructure.Thickness;
            }

            foreach (Sample sample in Apsim.Children(soil, typeof(Sample)))
            {
                SetSampleThickness(sample, targetThickness, soil);
            }

            if (soil.SoilWater is WaterModel.WaterBalance)
            {
                SetSoilWaterThickness(soil.SoilWater as WaterModel.WaterBalance, targetThickness);
            }
            if (soil.Weirdo != null)
            {
                soil.Weirdo.MapVariables(targetThickness);
            }
            SetAnalysisThickness(analysisNode, targetThickness);
            SetSoilOrganicMatterThickness(soil.SoilOrganicMatter, targetThickness);
            SetWaterThickness(waterNode, targetThickness, soil);
        }
Example #14
0
        /// <summary>
        /// Internal export method.
        /// </summary>
        /// <param name="tags">The autodoc tags.</param>
        /// <param name="modelToExport">The model to export.</param>
        /// <param name="workingDirectory">The folder path where bitmaps can be written.</param>
        /// <param name="url">The URL.</param>
        /// <returns>True if something was written to index.</returns>
        private void AddValidationTags(List <AutoDocumentation.ITag> tags, IModel modelToExport, int headingLevel, string workingDirectory)
        {
            // Look for child models that are a folder or simulation etc
            // that we need to recurse down through.
            foreach (Model child in modelToExport.Children)
            {
                bool ignoreChild = (child is Simulation && child.Parent is Experiment);

                if (!ignoreChild)
                {
                    if (Array.IndexOf(modelTypesToRecurseDown, child.GetType()) != -1)
                    {
                        tags.Add(new AutoDocumentation.Heading(child.Name, headingLevel));
                        string childFolderPath = Path.Combine(workingDirectory, child.Name);
                        AddValidationTags(tags, child, headingLevel + 1, workingDirectory);

                        if (child.Name == "Validation")
                        {
                            IModel dataStore = Apsim.Child(modelToExport, "DataStore");
                            if (dataStore != null)
                            {
                                tags.Add(new AutoDocumentation.Heading("Statistics", headingLevel + 1));
                                AddValidationTags(tags, dataStore, headingLevel + 2, workingDirectory);
                            }
                        }
                    }
                    else if (child.Name != "TitlePage" && child.Name != "Introduction" && (child is Memo || child is Graph || child is Map || child is Tests))
                    {
                        child.Document(tags, headingLevel, 0);
                    }
                }
            }
        }
Example #15
0
        /// <summary>
        /// Initialise the experiment ready for creating simulations.
        /// </summary>
        private void Initialise(bool fullFactorial = false)
        {
            parentSimulations = Apsim.Parent(this, typeof(Simulations)) as Simulations;
            allCombinations   = fullFactorial ? AllCombinations() : EnabledCombinations();
            Simulation baseSimulation = Apsim.Child(this, typeof(Simulation)) as Simulation;

            serialisedBase = Apsim.SerialiseToStream(baseSimulation) as Stream;
        }
Example #16
0
        public void ChildTest()
        {
            IModel clock = Apsim.Child(simulation, typeof(Clock));

            Assert.NotNull(clock);
            clock = Apsim.Child(simulation, "Clock");
            Assert.NotNull(clock);
        }
Example #17
0
        private void OnBeginRun(IEnumerable <string> knownSimulationNames = null, IEnumerable <string> simulationNamesBeingRun = 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;
        }
Example #18
0
        /// <summary>
        /// Initialise the experiment ready for creating simulations.
        /// </summary>
        private void Initialise()
        {
            parentSimulations = Apsim.Parent(this, typeof(Simulations)) as Simulations;
            Simulation baseSimulation = Apsim.Child(this, typeof(Simulation)) as Simulation;

            serialisedBase = Apsim.SerialiseToStream(baseSimulation) as Stream;
            allCombinations.Clear();
            CalculateFactors();
        }
Example #19
0
        /// <summary>Checks the analysis for missing values.</summary>
        /// <param name="soil">The soil.</param>
        private static void CheckAnalysisForMissingValues(Soil soil)
        {
            var analysis = Apsim.Child(soil, typeof(Chemical)) as Chemical;

            analysis.CL  = FillMissingValues(analysis.CL, analysis.Thickness.Length, 0);
            analysis.EC  = FillMissingValues(analysis.EC, analysis.Thickness.Length, 0);
            analysis.ESP = FillMissingValues(analysis.ESP, analysis.Thickness.Length, 0);
            analysis.PH  = FillMissingValues(analysis.PH, analysis.Thickness.Length, 7.0);
        }
Example #20
0
        private static void DocumentNode(StreamWriter OutputFile, XmlNode N, int NextLevel, Model parentModel)
        {
            if (N.Name == "Name")
            {
                return;
            }

            if (XmlUtilities.Attribute(N, "shortcut") != "")
            {
                OutputFile.WriteLine("<p>" + XmlUtilities.Value(N, "Name") + " uses the same value as " + XmlUtilities.Attribute(N, "shortcut"));
            }
            else if (N.Name == "Constant")
            {
                OutputFile.WriteLine(Header(XmlUtilities.Value(N, "Name"), NextLevel, XmlUtilities.Value(N.ParentNode, "Name")));

                WriteDescriptionForTypeName(OutputFile, N, parentModel);
                TryDocumentMemo(OutputFile, N, NextLevel);

                OutputFile.WriteLine("<p>Value = " + XmlUtilities.Value(N, "Value") + "</p>");
            }
            else if (XmlUtilities.ChildNodes(N, "").Count == 0)
            {
                WriteDescriptionForTypeName(OutputFile, N, parentModel);

                DocumentProperty(OutputFile, N, NextLevel);
            }
            else if (XmlUtilities.ChildNodes(N, "XYPairs").Count > 0)
            {
                CreateGraph(OutputFile, XmlUtilities.ChildNodes(N, "XYPairs")[0], NextLevel, parentModel);
            }
            else if (XmlUtilities.Type(N) == "TemperatureFunction")
            {
                DocumentTemperatureFunction(OutputFile, N, NextLevel, parentModel);
            }
            //else if (XmlUtilities.Type(N) == "GenericPhase")
            //   DocumentFixedPhase(OutputFile, N, NextLevel);
            // else if (XmlUtilities.Type(N) == "PhaseLookupValue")
            //   DocumentPhaseLookupValue(OutputFile, N, NextLevel);
            else if (XmlUtilities.Type(N) == "ChillingPhase")
            {
                ChillingPhaseFunction(OutputFile, N, NextLevel);
            }
            else if (N.Name == "Memo")
            {
                DocumentMemo(OutputFile, N, NextLevel);
            }
            else
            {
                string childName  = XmlUtilities.Value(N, "Name");
                Model  childModel = null;
                if (parentModel != null)
                {
                    childModel = Apsim.Child(parentModel, childName) as Model;
                }
                DocumentNodeAndChildren(OutputFile, N, NextLevel, childModel);
            }
        }
Example #21
0
 private void OnStartOfSimulation(object sender, EventArgs e)
 {
     InfestingOrganisum = Apsim.Find(this.Parent, InfestingOrganisumName) as LifeCycle;
     if (InfestingOrganisum == null)
     {
         throw new Exception(Apsim.FullPath(this) + " Could not find an infesting organisum called " + InfestingOrganisumName);
     }
     InfestingPhase = Apsim.Child(InfestingOrganisum, InfestingPhaseName) as LifeCyclePhase;
 }
Example #22
0
 /// <summary>Find our children.</summary>
 private void FindChildren()
 {
     waterNode         = Apsim.Child(this, typeof(Physical)) as Physical;
     Weirdo            = Apsim.Child(this, typeof(WEIRDO)) as WEIRDO;
     structure         = Apsim.Child(this, typeof(LayerStructure)) as LayerStructure;
     SoilWater         = Apsim.Child(this, typeof(ISoilWater)) as ISoilWater;
     SoilOrganicMatter = Apsim.Child(this, typeof(Organic)) as Organic;
     temperatureModel  = Apsim.Child(this, typeof(ISoilTemperature)) as ISoilTemperature;
     Initial           = Children.Find(child => child is Sample) as Sample;
 }
Example #23
0
        /// <summary>
        /// Attach the model (report) and the view (IReportView)
        /// </summary>
        /// <param name="model">The report model object</param>
        /// <param name="view">The view object</param>
        /// <param name="explorerPresenter">The explorer presenter</param>
        public void Attach(object model, object view, ExplorerPresenter explorerPresenter)
        {
            this.report            = model as Report;
            this.explorerPresenter = explorerPresenter;
            this.view                    = view as IReportView;
            this.intellisense            = new IntellisensePresenter(view as ViewBase);
            intellisense.ItemSelected   += OnIntellisenseItemSelected;
            this.view.VariableList.Mode  = EditorType.Report;
            this.view.EventList.Mode     = EditorType.Report;
            this.view.VariableList.Lines = report.VariableNames;
            this.view.EventList.Lines    = report.EventNames;
            this.view.GroupByEdit.Value  = report.GroupByVariableName;
            this.view.VariableList.ContextItemsNeeded     += OnNeedVariableNames;
            this.view.EventList.ContextItemsNeeded        += OnNeedEventNames;
            this.view.GroupByEdit.IntellisenseItemsNeeded += OnNeedVariableNames;
            this.view.VariableList.TextHasChangedByUser   += OnVariableNamesChanged;
            this.view.EventList.TextHasChangedByUser      += OnEventNamesChanged;
            this.view.GroupByEdit.Changed += OnGroupByChanged;
            this.view.SplitterChanged     += OnSplitterChanged;
            this.view.SplitterPosition     = Configuration.Settings.ReportSplitterPosition;
            this.explorerPresenter.CommandHistory.ModelChanged += OnModelChanged;
            this.view.TabChanged += OnChangeTab;

            Simulations simulations = Apsim.Parent(report, typeof(Simulations)) as Simulations;

            if (simulations != null)
            {
                dataStore = Apsim.Child(simulations, typeof(IDataStore)) as IDataStore;
            }

            //// TBI this.view.VariableList.SetSyntaxHighlighter("Report");

            dataStorePresenter = new DataStorePresenter();
            Simulation simulation = Apsim.Parent(report, typeof(Simulation)) as Simulation;
            Experiment experiment = Apsim.Parent(report, typeof(Experiment)) as Experiment;
            Zone       paddock    = Apsim.Parent(report, typeof(Zone)) as Zone;

            // Only show data which is in scope of this report.
            // E.g. data from this zone and either experiment (if applicable) or simulation.
            if (paddock != null)
            {
                dataStorePresenter.ZoneFilter = paddock;
            }
            if (experiment != null)
            {
                dataStorePresenter.ExperimentFilter = experiment;
            }
            else if (simulation != null)
            {
                dataStorePresenter.SimulationFilter = simulation;
            }

            dataStorePresenter.Attach(dataStore, this.view.DataStoreView, explorerPresenter);
            this.view.TabIndex = this.report.ActiveTabIndex;
        }
Example #24
0
        /// <summary>Map soil water from one layer structure to another.</summary>
        /// <param name="fromValues">The from values.</param>
        /// <param name="fromThickness">The from thickness.</param>
        /// <param name="toThickness">To thickness.</param>
        /// <param name="soil">The soil.</param>
        /// <returns></returns>
        public static double[] MapSW(double[] fromValues, double[] fromThickness, double[] toThickness, Soil soil)
        {
            if (fromValues == null || fromThickness == null)
            {
                return(null);
            }

            var waterNode = Apsim.Child(soil, typeof(Physical)) as Physical;

            // convert from values to a mass basis with a dummy bottom layer.
            List <double> values = new List <double>();

            values.AddRange(fromValues);
            values.Add(MathUtilities.LastValue(fromValues) * 0.8);
            values.Add(MathUtilities.LastValue(fromValues) * 0.4);
            values.Add(0.0);
            List <double> thickness = new List <double>();

            thickness.AddRange(fromThickness);
            thickness.Add(MathUtilities.LastValue(fromThickness));
            thickness.Add(MathUtilities.LastValue(fromThickness));
            thickness.Add(3000);

            // Get the first crop ll or ll15.
            double[] LowerBound;
            if (waterNode != null && soil.Crops.Count > 0)
            {
                LowerBound = LLMapped(soil.Crops[0] as SoilCrop, thickness.ToArray());
            }
            else
            {
                LowerBound = LL15Mapped(soil, thickness.ToArray());
            }
            if (LowerBound == null)
            {
                throw new Exception("Cannot find crop lower limit or LL15 in soil");
            }

            // Make sure all SW values below LastIndex don't go below CLL.
            int bottomLayer = fromThickness.Length - 1;

            for (int i = bottomLayer + 1; i < thickness.Count; i++)
            {
                values[i] = Math.Max(values[i], LowerBound[i]);
            }

            double[] massValues = MathUtilities.Multiply(values.ToArray(), thickness.ToArray());

            // Convert mass back to concentration and return
            double[] newValues = MathUtilities.Divide(MapMass(massValues, thickness.ToArray(), toThickness), toThickness);



            return(newValues);
        }
Example #25
0
        /// <summary>
        /// Return a list of list of factorvalue objects for all permutations.
        /// </summary>
        public List <List <FactorValue> > AllCombinations()
        {
            Factors Factors = Apsim.Child(this, typeof(Factors)) as Factors;

            // Create a list of list of factorValues so that we can do permutations of them.
            List <List <FactorValue> > allValues = new List <List <FactorValue> >();

            if (Factors != null)
            {
                bool doFullFactorial = true;
                foreach (Factor factor in Factors.factors)
                {
                    if (factor.Enabled)
                    {
                        List <FactorValue> factorValues = factor.CreateValues();

                        // Iff any of the factors modify the same model (e.g. have a duplicate path), then we do not want to do a full factorial.
                        // This code should check if there are any such duplicates by checking each path in each factor value in the list of factor
                        // values for the current factor against each path in each list of factor values in the list of all factors which we have
                        // already added to the global list of list of factor values.
                        foreach (FactorValue currentFactorValue in factorValues)
                        {
                            foreach (string currentFactorPath in currentFactorValue.Paths)
                            {
                                foreach (List <FactorValue> allFactorValues in allValues)
                                {
                                    foreach (FactorValue globalValue in allFactorValues)
                                    {
                                        foreach (string globalPath in globalValue.Paths)
                                        {
                                            if (string.Equals(globalPath, currentFactorPath, StringComparison.CurrentCulture))
                                            {
                                                doFullFactorial = false;
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        allValues.Add(factorValues);
                    }
                }
                if (doFullFactorial)
                {
                    return(MathUtilities.AllCombinationsOf <FactorValue>(allValues.ToArray()));
                }
                else
                {
                    return(allValues);
                }
            }
            return(null);
        }
        /// <summary>Writes documentation for this cultivar 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)
            {
                // write description of this class.
                AutoDocumentation.DocumentModelSummary(this, tags, headingLevel, indent, false);

                tree = Apsim.Child(this, typeof(TreeProxy)) as TreeProxy;
                AutoDocumentation.DocumentModel(tree, tags, headingLevel, indent);
            }
        }
Example #27
0
        /// <summary>Writes documentation for this cultivar 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)
        {
            // need to put something here
            // add a heading.
            //tags.Add(new AutoDocumentation.Heading(Name, headingLevel));

            // write description of this class.
            AutoDocumentation.GetClassDescription(this, tags, indent);

            tree = Apsim.Child(this, typeof(TreeProxy)) as TreeProxy;
            tree.Document(tags, headingLevel, indent);
        }
Example #28
0
        /// <summary>Checks the analysis for missing values.</summary>
        /// <param name="soil">The soil.</param>
        private static void CheckAnalysisForMissingValues(Soil soil)
        {
            var analysis = Apsim.Child(soil, typeof(Analysis)) as Analysis;

            analysis.CL  = FillMissingValues(analysis.CL, analysis.Thickness.Length, 0);
            analysis.EC  = FillMissingValues(analysis.EC, analysis.Thickness.Length, 0);
            analysis.ESP = FillMissingValues(analysis.ESP, analysis.Thickness.Length, 0);
            analysis.PH  = FillMissingValues(analysis.PH, analysis.Thickness.Length, 7.0);
            analysis.ParticleSizeClay = FillMissingValues(analysis.ParticleSizeClay, analysis.Thickness.Length, 0);
            analysis.ParticleSizeSand = FillMissingValues(analysis.ParticleSizeSand, analysis.Thickness.Length, 0);
            analysis.ParticleSizeSilt = FillMissingValues(analysis.ParticleSizeSilt, analysis.Thickness.Length, 0);
        }
Example #29
0
        /// <summary>
        /// Called when the model is deserialised.
        /// </summary>
        public override void OnCreated()
        {
            if (Apsim.Child(this, typeof(Manager)) == null)
            {
                Manager script = new Manager();
                script.Name = "Config";
                script.Code = ReflectionUtilities.GetResourceAsString("Models.Resources.Scripts.GraphPanelScriptTemplate.cs");
                Children.Insert(0, script);
            }

            base.OnCreated();
        }
Example #30
0
        /// <summary>
        /// Calculate a list of fall combinations of factors.
        /// </summary>
        private List <List <CompositeFactor> > CalculateAllCombinations()
        {
            Factors Factors = Apsim.Child(this, typeof(Factors)) as Factors;

            // Create a list of list of factorValues so that we can do permutations of them.
            List <List <CompositeFactor> > allValues = new List <List <CompositeFactor> >();

            if (Factors != null)
            {
                foreach (CompositeFactor compositeFactor in Apsim.Children(Factors, typeof(CompositeFactor)))
                {
                    if (compositeFactor.Enabled)
                    {
                        allValues.Add(new List <CompositeFactor>()
                        {
                            compositeFactor
                        });
                    }
                }
                foreach (Factor factor in Factors.factors)
                {
                    if (factor.Enabled)
                    {
                        foreach (var compositeFactor in factor.GetCompositeFactors())
                        {
                            allValues.Add(new List <CompositeFactor>()
                            {
                                compositeFactor
                            });
                        }
                    }
                }
                foreach (Permutation factor in Apsim.Children(Factors, typeof(Permutation)))
                {
                    if (factor.Enabled)
                    {
                        allValues.AddRange(factor.GetPermutations());
                    }
                }

                // Remove disabled simulations.
                if (DisabledSimNames != null)
                {
                    allValues.RemoveAll(comb => DisabledSimNames.Contains(GetName(comb)));
                }

                return(allValues);
            }
            else
            {
                return(null);
            }
        }