virtual protected void OnSimulationCommencing(object sender, EventArgs e)
        {
            //read list of models into lists

            var folders = Apsim.Children(this, typeof(Folder));

            potentialPartitioningMethods = new List <IPartitionMethod>();
            var folder = folders.Find(f => f.Name == "PotentialPartitioningMethods");

            if (folder != null)
            {
                var methods = Apsim.Children(folder, typeof(IPartitionMethod));
                foreach (var method in methods)
                {
                    potentialPartitioningMethods.Add(method as IPartitionMethod);
                }
            }

            actualPartitioningMethods = new List <IPartitionMethod>();
            folder = folders.Find(f => f.Name == "ActualPartitioningMethods");
            if (folder != null)
            {
                var methods = Apsim.Children(folder, typeof(IPartitionMethod));
                foreach (var method in methods)
                {
                    actualPartitioningMethods.Add(method as IPartitionMethod);
                }
            }

            allocationMethods = new List <IAllocationMethod>();
            folder            = folders.Find(f => f.Name == "AllocationMethods");
            if (folder != null)
            {
                var methods = Apsim.Children(folder, typeof(IAllocationMethod));
                foreach (var method in methods)
                {
                    allocationMethods.Add(method as IAllocationMethod);
                }
            }
        }
        /// <summary>
        /// Method used to perform activity if it can occur as soon as resources are available.
        /// </summary>
        public override void DoActivity()
        {
            // add all provided requests to the individuals intake pools.

            List <LabourType> group = Resources.Labour().Items.Where(a => IncludeHiredLabour | a.Hired != true).ToList();
            double            aE    = group.Sum(a => a.AdultEquivalent);

            Status = ActivityStatus.NotNeeded;
            if (group != null && group.Count > 0)
            {
                var requests = ResourceRequestList.Where(a => a.ResourceType == typeof(HumanFoodStore));
                if (requests.Count() > 0)
                {
                    foreach (ResourceRequest request in requests)
                    {
                        if (request.Provided > 0)
                        {
                            // add to individual intake
                            foreach (LabourType labour in group)
                            {
                                labour.AddIntake(new LabourDietComponent()
                                {
                                    AmountConsumed = request.Provided * (labour.AdultEquivalent / aE),
                                    FoodStore      = request.Resource as HumanFoodStoreType
                                });
                            }
                        }
                    }
                }
                List <LabourActivityFeedTarget> labourActivityFeedTargets = Apsim.Children(this, typeof(LabourActivityFeedTarget)).Cast <LabourActivityFeedTarget>().ToList();
                if (labourActivityFeedTargets.Where(a => !a.TargetMet).Count() > 0)
                {
                    this.Status = ActivityStatus.Partial;
                }
                else
                {
                    this.Status = ActivityStatus.Success;
                }
            }
        }
Exemple #3
0
        /// <summary>
        /// Convert a range specification into factor values.
        /// </summary>
        /// <param name="specification">The specification to examine</param>
        private List <PathValuesPair> ParseModelReplacementSpecification(string specification)
        {
            List <PathValuesPair> pairs = new List <PathValuesPair>();

            // Must be a model replacement.
            // Need to find a child value of the correct type.

            Experiment experiment = Apsim.Parent(this, typeof(Experiment)) as Experiment;

            if (experiment != null)
            {
                IModel modelToReplace = Apsim.Get(experiment.BaseSimulation, specification) as IModel;
                if (modelToReplace == null)
                {
                    throw new ApsimXException(this, "Cannot find model: " + specification);
                }

                if (Specifications.Count == 1)
                {
                    foreach (IModel newModel in Children)
                    {
                        pairs.Add(new PathValuesPair()
                        {
                            path = specification, value = newModel
                        });
                    }
                }
                else
                {
                    foreach (IModel newModel in Apsim.Children(this, modelToReplace.GetType()))
                    {
                        pairs.Add(new PathValuesPair()
                        {
                            path = specification, value = newModel
                        });
                    }
                }
            }
            return(pairs);
        }
Exemple #4
0
        /// <summary>Fills in missing values where possible.</summary>
        /// <param name="soil">The soil.</param>
        public static void FillInMissingValues(Soil soil)
        {
            AddPredictedCrops(soil);
            CheckAnalysisForMissingValues(soil);

            var water = Apsim.Child(soil, typeof(Water)) as Water;

            if (water != null)
            {
                var crops = Apsim.Children(water, typeof(SoilCrop)).Cast <SoilCrop>().ToArray();

                foreach (var crop in crops)
                {
                    if (crop.XF == null)
                    {
                        crop.XF         = MathUtilities.CreateArrayOfValues(1.0, crop.Thickness.Length);
                        crop.XFMetadata = StringUtilities.CreateStringArray("Estimated", crop.Thickness.Length);
                    }
                    if (crop.KL == null)
                    {
                        FillInKLForCrop(crop);
                    }

                    CheckCropForMissingValues(crop, soil);
                }
            }

            var samples = Apsim.Children(soil, typeof(Sample)).Cast <Sample>().ToArray();

            foreach (Sample sample in samples)
            {
                CheckSampleForMissingValues(sample, soil);
            }

            // Make sure there are the correct number of KS values.
            if (water?.KS != null && water?.KS.Length > 0)
            {
                water.KS = FillMissingValues(water.KS, water.Thickness.Length, 0.0);
            }
        }
        /// <summary>
        /// Gets the names of all the items for each ResourceGroup whose items you want to put into a dropdown list.
        /// eg. "AnimalFoodStore,HumanFoodStore,ProductStore"
        /// Will create a dropdown list with all the items from the AnimalFoodStore, HumanFoodStore and ProductStore.
        ///
        /// To help uniquely identify items in the dropdown list will need to add the ResourceGroup name to the item name.
        /// eg. The names in the drop down list will become AnimalFoodStore.Wheat, HumanFoodStore.Wheat, ProductStore.Wheat, etc.
        /// </summary>
        /// <returns>Will create a string array with all the items from the AnimalFoodStore, HumanFoodStore and ProductStore.
        /// to help uniquely identify items in the dropdown list will need to add the ResourceGroup name to the item name.
        /// eg. The names in the drop down list will become AnimalFoodStore.Wheat, HumanFoodStore.Wheat, ProductStore.Wheat, etc. </returns>
        private string[] GetCLEMResourceNames(Type[] resourceNameResourceGroups)
        {
            List <string>   result    = new List <string>();
            ZoneCLEM        zoneCLEM  = Apsim.Parent(this.model, typeof(ZoneCLEM)) as ZoneCLEM;
            ResourcesHolder resHolder = Apsim.Child(zoneCLEM, typeof(ResourcesHolder)) as ResourcesHolder;

            if (resourceNameResourceGroups != null)
            {
                // resource groups specified (use them)
                foreach (Type resGroupType in resourceNameResourceGroups)
                {
                    IModel resGroup = Apsim.Child(resHolder, resGroupType);
                    if (resGroup != null)  //see if this group type is included in this particular simulation.
                    {
                        foreach (IModel item in resGroup.Children)
                        {
                            if (item.GetType() != typeof(Memo))
                            {
                                result.Add(resGroup.Name + "." + item.Name);
                            }
                        }
                    }
                }
            }
            else
            {
                // no resource groups specified so use all avaliable resources
                foreach (IModel resGroup in Apsim.Children(resHolder, typeof(IModel)))
                {
                    foreach (IModel item in resGroup.Children)
                    {
                        if (item.GetType() != typeof(Memo))
                        {
                            result.Add(resGroup.Name + "." + item.Name);
                        }
                    }
                }
            }
            return(result.ToArray());
        }
Exemple #6
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)
            {
                tags.Add(new AutoDocumentation.Heading(Name, headingLevel));

                // write memos
                foreach (IModel childFolder in Apsim.Children(this, typeof(Memo)))
                {
                    childFolder.Document(tags, headingLevel + 1, indent);
                }

                // write a sorted list of cultivar names.
                List <string> cultivarNames = new List <string>();
                foreach (Cultivar cultivar in Apsim.Children(this, typeof(Cultivar)))
                {
                    cultivarNames.Add(cultivar.Name);
                    cultivarNames.AddRange(cultivar.Aliases);
                }
                cultivarNames.Sort();

                string text = StringUtilities.BuildString(cultivarNames.ToArray(), ", ");
                if (text != string.Empty)
                {
                    tags.Add(new AutoDocumentation.Paragraph(text, indent));
                }

                // write child cultivars.
                foreach (IModel childCultivar in Apsim.Children(this, typeof(Cultivar)))
                {
                    childCultivar.Document(tags, headingLevel + 1, indent);
                }

                // write child folders.
                foreach (IModel childFolder in Apsim.Children(this, typeof(CultivarFolder)))
                {
                    childFolder.Document(tags, headingLevel + 1, indent);
                }
            }
        }
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)
 {
     // write memos.
     foreach (IModel memo in Apsim.Children(this, typeof(Memo)))
     {
         memo.Document(tags, -1, indent);
     }
     if (ChildFunctions == null)
     {
         ChildFunctions = Apsim.Children(this, typeof(IFunction));
     }
     foreach (IFunction child in ChildFunctions)
     {
         if (child != Lower && child != Upper)
         {
             tags.Add(new AutoDocumentation.Paragraph(Name + " is the value of " + (child as IModel).Name + " bound between a lower and upper bound where:", indent));
             (child as IModel).Document(tags, -1, indent + 1);
         }
     }
     (Lower as IModel).Document(tags, -1, indent + 1);
     (Upper as IModel).Document(tags, -1, indent + 1);
 }
Exemple #8
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));

                // write memos.
                foreach (IModel memo in Apsim.Children(this, typeof(Memo)))
                {
                    memo.Document(tags, -1, indent);
                }

                // write children.
                foreach (IModel child in Apsim.Children(this, typeof(IFunction)))
                {
                    child.Document(tags, -1, indent + 1);
                }

                tags.Add(new AutoDocumentation.Paragraph(this.Name + " has a value of zero for phases not specified above ", indent + 1));
            }
        }
Exemple #9
0
        /// <summary>
        /// Get value of a specific individual
        /// </summary>
        /// <returns>value</returns>
        public double ValueofIndividual(Ruminant ind, PurchaseOrSalePricingStyleType purchaseStyle)
        {
            if (PricingAvailable())
            {
                List <Ruminant> animalList = new List <Ruminant>()
                {
                    ind
                };

                // search through RuminantPriceGroups for first match with desired purchase or sale flag
                foreach (AnimalPriceGroup item in Apsim.Children(PriceList, typeof(AnimalPriceGroup)).Cast <AnimalPriceGroup>().Where(a => a.PurchaseOrSale == purchaseStyle || a.PurchaseOrSale == PurchaseOrSalePricingStyleType.Both))
                {
                    if (animalList.Filter(item).Count() == 1)
                    {
                        return(item.Value * ((item.PricingStyle == PricingStyleType.perKg) ? ind.Weight : 1.0));
                    }
                }
                // no price match found.
                Summary.WriteWarning(this, "No " + purchaseStyle.ToString() + " price entry was found for indiviudal [" + ind.ID + "] with details ([f=age: " + ind.Age + "] [f=herd: " + ind.HerdName + "] [f=gender: " + ind.GenderAsString + "] [f=weight: " + ind.Weight + "])");
            }
            return(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)
        {
            // add a heading.
            tags.Add(new AutoDocumentation.Heading(Name, headingLevel));

            // write memos.
            foreach (IModel memo in Apsim.Children(this, typeof(Memo)))
            {
                memo.Document(tags, -1, indent);
            }

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

            string RelativeDocString = "Arbitration is performed in two passes for each of the biomass supply sources.  On the first pass, structural and metabolic biomass is allocated to each organ based on their demand relative to the demand from all organs.  On the second pass any remaining biomass is allocated to non-structural demands based on the organ's relative demand.";

            //string RelativeThenPriorityDocStirng = "Arbitration is performed in two passes for each of the biomass supply sources.  On the first pass, structural and metabolic biomass is allocated to each organ based on their order of priority with higher priority organs recieving their full demand first. On the second pass any remaining biomass is allocated to non-structural demands based on the relative demand from all organs.";
            //string PriorityDocString = "Arbitration is performed in two passes for each of the biomass supply sources.  On the first pass, structural and metabolic biomass is allocated to each organ based on their order of priority with higher priority organs recieving their full demand first.  On the second pass any remaining biomass is allocated to non-structural demands based on the same order of priority.";
            //string SinglePassDocString = "Arbitration is performed in a single pass for each of the biomass supply sources.  Biomass is partitioned between organs based on their relative demand in a single pass so non-structural demands compete dirrectly with structural demands.";

            tags.Add(new AutoDocumentation.Paragraph(RelativeDocString, indent));
        }
        /// <summary>
        /// Validate component
        /// </summary>
        /// <param name="validationContext"></param>
        /// <returns></returns>
        public IEnumerable <ValidationResult> Validate(ValidationContext validationContext)
        {
            var results = new List <ValidationResult>();

            // if finances and not account provided throw error
            if (SellExcess && Resources.GetResourceGroupByType(typeof(Finance)) != null)
            {
                if (bankAccount is null)
                {
                    string[] memberNames = new string[] { "AccountName" };
                    results.Add(new ValidationResult($"A valid bank account must be supplied as sales of excess food is enabled and [r=Finance] resources are available.", memberNames));
                }
            }

            // check that at least one target has been provided.
            if (Apsim.Children(this, typeof(LabourActivityFeedTarget)).Count() == 0)
            {
                string[] memberNames = new string[] { "LabourActivityFeedToTargets" };
                results.Add(new ValidationResult(String.Format("At least one [LabourActivityFeedTarget] component is required below the feed activity [{0}]", this.Name), memberNames));
            }
            return(results);
        }
Exemple #12
0
        /// <summary>
        /// Convert a range specification into factor values.
        /// </summary>
        /// <param name="specification">The specification to examine</param>
        /// <param name="paths">The return list of factor paths</param>
        /// <param name="values">The return list of factor values</param>
        private void ParseModelReplacementSpecification(string specification, List <string> paths, List <object> values)
        {
            // Must be a model replacement.
            // Need to find a child value of the correct type.

            Experiment experiment = Apsim.Parent(this, typeof(Experiment)) as Experiment;

            if (experiment != null)
            {
                IModel modelToReplace = Apsim.Get(experiment.BaseSimulation, specification) as IModel;
                if (modelToReplace == null)
                {
                    throw new ApsimXException(this, "Cannot find model: " + specification);
                }

                foreach (IModel newModel in Apsim.Children(this, modelToReplace.GetType()))
                {
                    paths.Add(specification);
                    values.Add(newModel);
                }
            }
        }
Exemple #13
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 void Document(List <AutoDocumentation.ITag> tags, int headingLevel, int indent)
        {
            if (IncludeInDocumentation)
            {
                // add a heading.
                tags.Add(new AutoDocumentation.Heading(Name, headingLevel));

                // write memos.
                foreach (IModel memo in Apsim.Children(this, typeof(Memo)))
                {
                    AutoDocumentation.DocumentModel(memo, tags, headingLevel + 1, indent);
                }

                // Write Phase Table
                tags.Add(new AutoDocumentation.Paragraph("**Destination of C from " + this.Name + "**", indent));
                DataTable tableData = new DataTable();
                tableData.Columns.Add("Destination Pool", typeof(string));
                tableData.Columns.Add("Carbon Fraction", typeof(string));

                if (destinationNames != null)
                {
                    for (int j = 0; j < destinationNames.Length; j++)
                    {
                        DataRow row = tableData.NewRow();
                        row[0] = destinationNames[j];
                        row[1] = destinationFraction[j].ToString();
                        tableData.Rows.Add(row);
                    }
                }

                tags.Add(new AutoDocumentation.Table(tableData, indent));

                // write remaining children
                foreach (IModel memo in Apsim.Children(this, typeof(IFunction)))
                {
                    AutoDocumentation.DocumentModel(memo, tags, headingLevel + 1, indent);
                }
            }
        }
Exemple #14
0
        private void OnStartOfSimulation(object sender, EventArgs e)
        {
            ChildStages = new List <Lifestage>();
            foreach (Lifestage stage in Apsim.Children(this, typeof(Lifestage)))
            {
                stage.OwningCycle = this;
                ChildStages.Add(stage);
            }

            int i = 0;

            //create new cohorts from the InitialPopulation[]
            foreach (Lifestage stage in ChildStages)
            {
                if (InitialPopulation.Length > i)
                {
                    Cohort newCohort = stage.NewCohort();
                    newCohort.Count = InitialPopulation[i];
                }
                i++;
            }
        }
Exemple #15
0
 private void OnSimulationCommencing(object sender, EventArgs e)
 {
     Items = new List <LabourType>();
     foreach (LabourType labourChildModel in Apsim.Children(this, typeof(IModel)).Cast <LabourType>().ToList())
     {
         for (int i = 0; i < Math.Max(labourChildModel.Individuals, 1); i++)
         {
             LabourType labour = new LabourType()
             {
                 Gender          = labourChildModel.Gender,
                 Individuals     = 1,
                 InitialAge      = labourChildModel.InitialAge,
                 AgeInMonths     = labourChildModel.InitialAge * 12,
                 MaxLabourSupply = labourChildModel.MaxLabourSupply,
                 Parent          = this,
                 Name            = labourChildModel.Name // + ((labourChildModel.Individuals>1)?i.ToString():"")
             };
             labour.TransactionOccurred += Resource_TransactionOccurred;
             Items.Add(labour);
         }
     }
 }
Exemple #16
0
        /// <summary>
        /// Provides the closing html tags for object
        /// </summary>
        /// <returns></returns>
        public override string ModelSummaryInnerOpeningTags(bool formatForParentControl)
        {
            string html = "";

            if (formatForParentControl)
            {
                html += "<tr><td>" + this.Name + "</td><td>";
                if (!(Apsim.Children(this, typeof(LabourFilter)).Count() >= 1))
                {
                    html += "<div class=\"filter\">All individuals</div>";
                }
            }
            else
            {
                html += "\n<div class=\"filterborder clearfix\">";
                if (!(Apsim.Children(this, typeof(LabourFilter)).Count() >= 1))
                {
                    html += "<div class=\"filter\">All individuals</div>";
                }
            }
            return(html);
        }
        /// <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)
        {
            // add a heading.
            tags.Add(new AutoDocumentation.Heading(Name, headingLevel));

            AutoDocumentation.GetClassDescription(this, tags, indent);

            // write memos.
            foreach (IModel memo in Apsim.Children(this, typeof(Memo)))
            {
                memo.Document(tags, -1, indent);
            }

            // Links aren't resolved at this point so go find xy pairs manually.
            XYPairs xypairs = Apsim.Child(this, "XYPairs") as XYPairs;

            // add graph and table.
            if (xypairs != null)
            {
                tags.Add(new AutoDocumentation.GraphAndTable(xypairs, Name, "Temperature (oC)", Name + " (deg. day)", indent));
            }
        }
Exemple #18
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)
        {
            // add a heading.
            tags.Add(new AutoDocumentation.Heading(Name, headingLevel));

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

            //

            string XName = "";

            if (ChildFunctions.Count == 1)
            {
                IFunction F = ChildFunctions[0] as IFunction;
                XName = ChildFunctions[0].Name;
            }
            tags.Add(new AutoDocumentation.Paragraph("Where " + this.Name + "is calculated using a sigmoid function of the form" +
                                                     "y = Xmax * 1 / 1 + exp<sup>-(" + XName + " - Xo) / b</sup>", indent));

            // write a list of constant functions.
            foreach (IModel child in Apsim.Children(this, typeof(Constant)))
            {
                child.Document(tags, -1, indent);
            }

            // write children.
            foreach (IModel child in Apsim.Children(this, typeof(IModel)))
            {
                if (child is Constant || child is Biomass || child is CompositeBiomass || child is ArrayBiomass)
                {
                    // don't document.
                }
                else
                {
                    child.Document(tags, headingLevel + 1, indent);
                }
            }
        }
Exemple #19
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)
        {
            // add a heading.
            tags.Add(new AutoDocumentation.Heading(Name + " Phase", headingLevel));

            // write memos.
            foreach (IModel memo in Apsim.Children(this, typeof(Memo)))
            {
                memo.Document(tags, -1, indent);
            }

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

            tags.Add(new AutoDocumentation.Paragraph("The phase goes from " + Start + " to " + End + ".", indent));

            // write children.
            foreach (IModel child in Apsim.Children(this, typeof(IFunction)))
            {
                child.Document(tags, -1, indent);
            }
        }
        /// <summary>
        /// Validate component
        /// </summary>
        /// <param name="validationContext"></param>
        /// <returns></returns>
        public IEnumerable <ValidationResult> Validate(ValidationContext validationContext)
        {
            var results = new List <ValidationResult>();

            // if finances and not account provided throw error
            if (SellExcess && Resources.GetResourceGroupByType(typeof(Finance)) != null)
            {
                if (bankAccount is null)
                {
                    string[] memberNames = new string[] { "AccountName" };
                    results.Add(new ValidationResult($"A valid bank account must be supplied as sales of excess food is enabled and [r=Finance] resources are available.", memberNames));
                }
            }

            Market market = Apsim.Children(Apsim.Parent(this, typeof(Simulation)), typeof(Market)).FirstOrDefault() as Market;

            if (market != null & bankAccount is null)
            {
                string[] memberNames = new string[] { "AccountName" };
                results.Add(new ValidationResult($"A valid bank account must be supplied for purchases of food from the market used by [a=" + this.Name + "].", memberNames));
            }

            // check that at least one target has been provided.
            if (Apsim.Children(this, typeof(LabourActivityFeedTarget)).Count() == 0)
            {
                string[] memberNames = new string[] { "LabourActivityFeedToTargets" };
                results.Add(new ValidationResult(String.Format("At least one [LabourActivityFeedTarget] component is required below the feed activity [{0}]", this.Name), memberNames));
            }

            // check purchases
            if (Apsim.Children(this, typeof(LabourActivityFeedTargetPurchase)).Cast <LabourActivityFeedTargetPurchase>().Sum(a => a.TargetProportion) != 1)
            {
                string[] memberNames = new string[] { "LabourActivityFeedToTargetPurchases" };
                results.Add(new ValidationResult(String.Format("The sum of all [LabourActivityFeedTargetPurchase] proportions should be 1 for the targeted feed activity [{0}]", this.Name), memberNames));
            }

            return(results);
        }
 /// <summary>
 /// Convert specified amount of this resource to another value using ResourceType supplied converter
 /// </summary>
 /// <param name="converterName">Name of converter to use</param>
 /// <param name="amount">Amount to convert</param>
 /// <returns>Value to report</returns>
 public object ConvertTo(string converterName, double amount)
 {
     // get converted value
     if (converterName == "$")
     {
         // calculate price as special case using pricing structure if present.
         ResourcePricing price = Price;
         if (price.PricePerPacket > 0)
         {
             double packets = amount / price.PacketSize;
             // this does not include whole packet restriction as needs to report full value
             //if(price.UseWholePackets)
             //{
             //    packets = Math.Floor(packets);
             //}
             return(packets * price.PricePerPacket);
         }
         else
         {
             return(null);
         }
     }
     else
     {
         ResourceUnitsConverter converter = Apsim.Children(this, typeof(ResourceUnitsConverter)).Where(a => a.Name.ToLower() == converterName.ToLower()).FirstOrDefault() as ResourceUnitsConverter;
         if (converter != null)
         {
             return(amount * converter.Factor);
         }
         else
         {
             string warning = "Unable to find the required unit converter [r=" + converterName + "] in resource [r=" + this.Name + "]";
             Warnings.Add(warning);
             Summary.WriteWarning(this, warning);
             return(null);
         }
     }
 }
Exemple #22
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.
                var possibleMatches = Apsim.Children(this, modelToReplace.GetType());
                if (possibleMatches.Count > 1)
                {
                    value = possibleMatches.Find(m => m.Name == modelToReplace.Name);
                }
                else
                {
                    value = possibleMatches[0];
                }

                allPaths.Add(path.Trim());
                allValues.Add(value);
            }
        }
        private void OnCLEMInitialiseActivity(object sender, EventArgs e)
        {
            this.InitialiseHerd(false, false);

            // get herd to add to
            herdToUse = Resources.GetResourceItem(this, typeof(RuminantHerd), this.PredictedHerdName, OnMissingResourceActionTypes.ReportErrorAndStop, OnMissingResourceActionTypes.ReportErrorAndStop) as RuminantType;

            if (!herdToUse.PricingAvailable())
            {
                Summary.WriteWarning(this, "No pricing is supplied for herd [" + PredictedHerdName + "] and so no pricing will be included with [" + this.Name + "]");
            }

            // check GrazeFoodStoreExists
            grazeStore = "";
            if (GrazeFoodStoreName != null && !GrazeFoodStoreName.StartsWith("Not specified"))
            {
                grazeStore = GrazeFoodStoreName.Split('.').Last();
            }

            // check for managed paddocks and warn if animals placed in yards.
            if (grazeStore == "")
            {
                var ah = Apsim.Find(this, typeof(ActivitiesHolder));
                if (Apsim.ChildrenRecursively(ah, typeof(PastureActivityManage)).Count() != 0)
                {
                    Summary.WriteWarning(this, String.Format("Trade animals purchased by [a={0}] are currently placed in [Not specified - general yards] while a managed pasture is available. These animals will not graze until mustered and will require feeding while in yards.\nSolution: Set the [GrazeFoodStore to place purchase in] located in the properties [General].[PastureDetails]", this.Name));
                }
            }

            numberToStock = Apsim.Children(this, typeof(Relationship)).FirstOrDefault() as Relationship;
            if (numberToStock != null)
            {
                if (grazeStore != "")
                {
                    foodStore = Resources.GetResourceItem(this, GrazeFoodStoreName, OnMissingResourceActionTypes.ReportErrorAndStop, OnMissingResourceActionTypes.ReportErrorAndStop) as GrazeFoodStoreType;
                }
            }
        }
        private void OnCLEMInitialiseActivity(object sender, EventArgs e)
        {
            this.InitialiseHerd(false, true);
            List <Ruminant> testherd = this.CurrentHerd(true);

            // check if finance is available and warn if not supplying bank account.
            if (Resources.ResourceGroupExist(typeof(Finance)))
            {
                if (Resources.ResourceItemsExist(typeof(Finance)))
                {
                    if (BankAccountName == "")
                    {
                        Summary.WriteWarning(this, "No bank account has been specified in [a={0}] while Finances are available in the simulation. No financial transactions will be recorded for the purchase and sale of animals.");
                    }
                }
            }
            if (BankAccountName != "")
            {
                bankAccount = Resources.GetResourceItem(this, BankAccountName, OnMissingResourceActionTypes.Ignore, OnMissingResourceActionTypes.ReportErrorAndStop) as FinanceType;
            }

            // get trucking settings
            trucking = Apsim.Children(this, typeof(TruckingSettings)).FirstOrDefault() as TruckingSettings;

            // check if pricing is present
            if (bankAccount != null)
            {
                RuminantHerd ruminantHerd = Resources.RuminantHerd();
                var          breeds       = ruminantHerd.Herd.Where(a => a.BreedParams.Breed == this.PredictedHerdBreed).GroupBy(a => a.HerdName);
                foreach (var herd in breeds)
                {
                    if (!herd.FirstOrDefault().BreedParams.PricingAvailable())
                    {
                        Summary.WriteWarning(this, String.Format("No pricing schedule has been provided for herd [r={0}]. No transactions will be recorded for activity [a={1}]", herd.Key, this.Name));
                    }
                }
            }
        }
Exemple #25
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 void Document(List <AutoDocumentation.ITag> tags, int headingLevel, int indent)
        {
            if (IncludeInDocumentation)
            {
                // add a heading
                tags.Add(new AutoDocumentation.Heading(Name, headingLevel));

                // get description of this class.
                tags.Add(new AutoDocumentation.Paragraph("This is the collection of functions for calculating the demands for each of the biomass pools (Structural, Metabolic, and Storage).", indent));

                // write memos.
                foreach (IModel memo in Apsim.Children(this, typeof(Memo)))
                {
                    AutoDocumentation.DocumentModel(memo, tags, headingLevel + 1, indent);
                }

                // write children.
                foreach (IModel child in Apsim.Children(this, typeof(IFunction)))
                {
                    AutoDocumentation.DocumentModel(child, tags, headingLevel + 1, indent);
                }
            }
        }
        /// <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 void Document(List <AutoDocumentation.ITag> tags, int headingLevel, int indent)
        {
            if (IncludeInDocumentation)
            {
                // add a heading.
                tags.Add(new AutoDocumentation.Heading(Name, headingLevel));

                // add graph and table.
                if (XYPairs != null)
                {
                    tags.Add(new AutoDocumentation.Paragraph("<i>" + Name + " is calculated as a function of daily min and max temperatures, these are weighted toward max temperature according to the specified MaximumTemperatureWeighting factor.  A value equal to 1.0 means it will use max temperature, a value of 0.5 means average temperature.</i>", indent));
                    tags.Add(new AutoDocumentation.Paragraph("<i>MaximumTemperatureWeighting = " + MaximumTemperatureWeighting + "</i>", indent));

                    // write memos.
                    foreach (IModel memo in Apsim.Children(this, typeof(Memo)))
                    {
                        AutoDocumentation.DocumentModel(memo, tags, headingLevel + 1, indent);
                    }

                    tags.Add(new AutoDocumentation.GraphAndTable(XYPairs, string.Empty, "Average temperature (oC)", Name, indent));
                }
            }
        }
        /// <summary>Gets the value.</summary>
        /// <value>The value.</value>
        /// <exception cref="System.Exception">Power function must have only one argument</exception>
        public double Value(int arrayIndex = -1)
        {
            if (ChildFunctions == null)
            {
                ChildFunctions = Apsim.Children(this, typeof(IFunction));
            }

            if (ChildFunctions.Count == 1)
            {
                IFunction F = ChildFunctions[0] as IFunction;
                return(Math.Pow(F.Value(arrayIndex), Exponent));
            }
            else if (ChildFunctions.Count == 2)
            {
                IFunction F = ChildFunctions[0] as IFunction;
                IFunction P = ChildFunctions[1] as IFunction;
                return(Math.Pow(F.Value(arrayIndex), P.Value(arrayIndex)));
            }
            else
            {
                throw new Exception("Invalid number of arguments for Power function");
            }
        }
        /// <summary>
        /// Provides the closing html tags for object
        /// </summary>
        /// <returns></returns>
        public override string ModelSummaryInnerOpeningTags(bool formatForParentControl)
        {
            string html = "";

            html += "\n<div class=\"croprotationborder\">";
            html += "<div class=\"croprotationlabel\">The following targets and purchases will be used:</div>";

            if (Apsim.Children(this, typeof(LabourActivityFeedTarget)).Count() == 0)
            {
                html += "\n<div class=\"errorbanner clearfix\">";
                html += "<div class=\"filtererror\">No Feed To Target component provided</div>";
                html += "</div>";
            }

            if (Apsim.Children(this, typeof(LabourActivityFeedTargetPurchase)).Count() == 0)
            {
                html += "\n<div class=\"errorbanner clearfix\">";
                html += "<div class=\"filtererror\">No food items will be purchased above what is currently available</div>";
                html += "</div>";
            }

            return(html);
        }
        private void OnCLEMInitialiseActivity(object sender, EventArgs e)
        {
            this.InitialiseHerd(true, true);

            // link to graze food store type pasture to muster to
            // blank is general yards.
            if (ManagedPastureName != "")
            {
                Pasture = Resources.GetResourceItem(this, typeof(GrazeFoodStore), ManagedPastureName, OnMissingResourceActionTypes.ReportErrorAndStop, OnMissingResourceActionTypes.ReportErrorAndStop) as GrazeFoodStoreType;
            }

            // get labour specifications
            labour = Apsim.Children(this, typeof(LabourFilterGroupSpecified)).Cast <LabourFilterGroupSpecified>().ToList(); //  this.Children.Where(a => a.GetType() == typeof(LabourFilterGroupSpecified)).Cast<LabourFilterGroupSpecified>().ToList();
            if (labour == null)
            {
                labour = new List <LabourFilterGroupSpecified>();
            }

            if (PerformAtStartOfSimulation)
            {
                Muster();
            }
        }
Exemple #30
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 void Document(List <AutoDocumentation.ITag> tags, int headingLevel, int indent)
        {
            if (IncludeInDocumentation)
            {
                // add a heading.
                tags.Add(new AutoDocumentation.Heading(Name, headingLevel));

                // get description of this class.
                AutoDocumentation.DocumentModelSummary(this, tags, headingLevel, indent, false);

                // write memos.
                foreach (IModel memo in Apsim.Children(this, typeof(Memo)))
                {
                    AutoDocumentation.DocumentModel(memo, tags, headingLevel + 1, indent);
                }

                // write children.
                foreach (IModel child in Apsim.Children(this, typeof(IFunction)))
                {
                    AutoDocumentation.DocumentModel(child, tags, headingLevel + 1, indent);
                }
            }
        }