예제 #1
0
        /// <summary>
        /// Add individuals to type based on cohort
        /// </summary>
        /// <param name="addIndividuals">OtherAnimalsTypeCohort Object to add. This object can be double or contain additional information (e.g. Nitrogen) of food being added</param>
        /// <param name="activity">Name of activity adding resource</param>
        /// <param name="relatesToResource"></param>
        /// <param name="category"></param>
        public new void Add(object addIndividuals, CLEMModel activity, string relatesToResource, string category)
        {
            OtherAnimalsTypeCohort cohortToAdd = addIndividuals as OtherAnimalsTypeCohort;

            OtherAnimalsTypeCohort cohortexists = Cohorts.Where(a => a.Age == cohortToAdd.Age && a.Gender == cohortToAdd.Gender).FirstOrDefault();

            if (cohortexists == null)
            {
                // add new
                Cohorts.Add(cohortToAdd);
            }
            else
            {
                cohortexists.Number += cohortToAdd.Number;
            }

            LastCohortChanged = cohortToAdd;
            ResourceTransaction details = new ResourceTransaction
            {
                Gain              = cohortToAdd.Number,
                Activity          = activity,
                RelatesToResource = relatesToResource,
                Category          = category,
                ResourceType      = this,
                ExtraInformation  = cohortToAdd
            };

            LastTransaction = details;
            LastGain        = cohortToAdd.Number;
            TransactionEventArgs eargs = new TransactionEventArgs
            {
                Transaction = LastTransaction
            };

            OnTransactionOccurred(eargs);
        }
예제 #2
0
        /// <summary>
        /// Add product to store
        /// </summary>
        /// <param name="resourceAmount">Object to add. This object can be double or contain additional information (e.g. Nitrogen) of food being added</param>
        /// <param name="activity">Name of activity adding resource</param>
        /// <param name="reason">Name of individual adding resource</param>
        public new void Add(object resourceAmount, CLEMModel activity, string reason)
        {
            double addAmount;

            if (resourceAmount.GetType().Name == "FoodResourcePacket")
            {
                addAmount = (resourceAmount as FoodResourcePacket).Amount;
            }
            else if (resourceAmount.GetType().ToString() == "System.Double")
            {
                addAmount = (double)resourceAmount;
            }
            else
            {
                throw new Exception(String.Format("ResourceAmount object of type [{0}] is not supported in [r={1}]", resourceAmount.GetType().ToString(), this.Name));
            }

            if (addAmount > 0)
            {
                amount += addAmount;

                ResourceTransaction details = new ResourceTransaction
                {
                    Gain         = addAmount,
                    Activity     = activity,
                    Reason       = reason,
                    ResourceType = this
                };
                LastTransaction = details;
                TransactionEventArgs te = new TransactionEventArgs()
                {
                    Transaction = details
                };
                OnTransactionOccurred(te);
            }
        }
 /// <inheritdoc/>
 public override string ModelSummary()
 {
     using (StringWriter htmlWriter = new StringWriter())
     {
         htmlWriter.Write("\r\n<div class=\"activityentry\">Resources added or removed are provided by ");
         htmlWriter.Write(CLEMModel.DisplaySummaryValueSnippet(ResourceDataReader, "Reader not set", HTMLSummaryStyle.FileReader));
         htmlWriter.Write("</div>");
         htmlWriter.Write("\r\n<div class=\"activityentry\">");
         if (AccountName == null || AccountName == "")
         {
             htmlWriter.Write("Financial transactions will be made to <span class=\"errorlink\">FinanceType not set</span>");
         }
         else if (AccountName == "No financial implications")
         {
             htmlWriter.Write("No financial constraints relating to pricing and packet sizes associated with each resource will be included.");
         }
         else
         {
             htmlWriter.Write("Pricing and packet sizes associated with each resource will be used with <span class=\"resourcelink\">" + AccountName + "</span>");
         }
         htmlWriter.Write("</div>");
         return(htmlWriter.ToString());
     }
 }
예제 #4
0
        private void OnCommencing(object sender, EventArgs e)
        {
            dataToWriteToDb = null;
            // sanitise the variable names and remove duplicates
            List <string> variableNames = new List <string>
            {
                "[Clock].Today"
            };

            if (VariableNames != null && VariableNames.Count() > 0)
            {
                if (VariableNames.Count() > 1)
                {
                    Summary.WriteWarning(this, String.Format("Multiple resource groups not permitted in ReportResourceLedger [{0}]\nAdditional entries have been ignored", this.Name));
                }

                for (int i = 0; i < 1; i++)
                {
                    // each variable name is now a ResourceGroup
                    bool isDuplicate = StringUtilities.IndexOfCaseInsensitive(variableNames, this.VariableNames[i].Trim()) != -1;
                    if (!isDuplicate && this.VariableNames[i] != string.Empty)
                    {
                        // check it is a ResourceGroup
                        CLEMModel model = Resources.GetResourceGroupByName(this.VariableNames[i]) as CLEMModel;
                        if (model == null)
                        {
                            Summary.WriteWarning(this, String.Format("Invalid resource group [{0}] in ReportResourceBalances [{1}]\nEntry has been ignored", this.VariableNames[i], this.Name));
                        }
                        else
                        {
                            bool pricingIncluded = false;
                            if (model.GetType() == typeof(RuminantHerd))
                            {
                                pricingIncluded = Apsim.ChildrenRecursively(model, typeof(AnimalPricing)).Count() > 0;

                                variableNames.Add("[Resources]." + this.VariableNames[i] + ".LastTransaction.ExtraInformation.ID as uID");
                                variableNames.Add("[Resources]." + this.VariableNames[i] + ".LastTransaction.ExtraInformation.Breed as Breed");
                                variableNames.Add("[Resources]." + this.VariableNames[i] + ".LastTransaction.ExtraInformation.HerdName as Herd");
                                variableNames.Add("[Resources]." + this.VariableNames[i] + ".LastTransaction.ExtraInformation.GenderAsString as Sex");
                                variableNames.Add("[Resources]." + this.VariableNames[i] + ".LastTransaction.ExtraInformation.Age as Age");
                                variableNames.Add("[Resources]." + this.VariableNames[i] + ".LastTransaction.ExtraInformation.Weight as Weight");
                                variableNames.Add("[Resources]." + this.VariableNames[i] + ".LastTransaction.ExtraInformation.SaleFlagAsString as Reason");
                                variableNames.Add("[Resources]." + this.VariableNames[i] + ".LastTransaction.ExtraInformation.PopulationChangeDirection as Change");

                                // ToDo: add pricing for ruminants including buy and sell pricing
                                // Needs update in CLEMResourceTypeBase and link between ResourcePricing and AnimalPricing.
                            }
                            else
                            {
                                pricingIncluded = Apsim.ChildrenRecursively(model, typeof(ResourcePricing)).Count() > 0;

                                variableNames.Add("[Resources]." + this.VariableNames[i] + ".LastTransaction.Gain as Gain");
                                variableNames.Add("[Resources]." + this.VariableNames[i] + ".LastTransaction.Loss * -1.0 as Loss");
                                // get all converters for this type of resource
                                var converterList = Apsim.ChildrenRecursively(model, typeof(ResourceUnitsConverter)).Select(a => a.Name).Distinct();
                                if (converterList != null)
                                {
                                    foreach (var item in converterList)
                                    {
                                        variableNames.Add("[Resources]." + this.VariableNames[i] + ".LastTransaction.ConvertTo(" + item + ",\"gain\") as " + item + "_Gain");
                                        variableNames.Add("[Resources]." + this.VariableNames[i] + ".LastTransaction.ConvertTo(" + item + ",\"loss\") as " + item + "_Loss");
                                    }
                                }

                                // add pricing
                                if (pricingIncluded)
                                {
                                    variableNames.Add("[Resources]." + this.VariableNames[i] + ".LastTransaction.ConvertTo(\"$\",\"gain\") as Price_Gain");
                                    variableNames.Add("[Resources]." + this.VariableNames[i] + ".LastTransaction.ConvertTo(\"$\",\"loss\") as Price_Loss");
                                }

                                variableNames.Add("[Resources]." + this.VariableNames[i] + ".LastTransaction.ResourceType.Name as Resource");
                                variableNames.Add("[Resources]." + this.VariableNames[i] + ".LastTransaction.Activity.Name as Activity");
                                variableNames.Add("[Resources]." + this.VariableNames[i] + ".LastTransaction.Reason as Reason");
                            }
                        }
                    }
                }
                events.Subscribe("[Resources]." + this.VariableNames[0] + ".TransactionOccurred", DoOutputEvent);
            }
            // Tidy up variable/event names.
            VariableNames = variableNames.ToArray();
            VariableNames = TidyUpVariableNames();
            EventNames    = TidyUpEventNames();
            this.FindVariableMembers();
        }
예제 #5
0
 /// <summary>
 /// Add resource
 /// </summary>
 /// <param name="resourceAmount">Object to add. This object can be double or contain additional information (e.g. Nitrogen) of food being added</param>
 /// <param name="activity">Name of activity adding resource</param>
 /// <param name="relatesToResource"></param>
 /// <param name="category"></param>
 public new void Add(object resourceAmount, CLEMModel activity, string relatesToResource, string category)
 {
     throw new NotImplementedException();
 }
예제 #6
0
 /// <summary>
 /// Add to Resource method.
 /// This style is not supported in GrazeFoodStoreType
 /// </summary>
 /// <param name="resourceAmount">Object to add. This object can be double or contain additional information (e.g. Nitrogen) of food being added</param>
 /// <param name="activity">Name of activity adding resource</param>
 /// <param name="reason">Name of individual adding resource</param>
 public void Add(object resourceAmount, CLEMModel activity, string reason)
 {
     throw new NotImplementedException();
 }
예제 #7
0
        private string FilterString(bool htmltags)
        {
            Initialise();

            using (StringWriter filterWriter = new StringWriter())
            {
                if (propertyInfo is null)
                {
                    filterWriter.Write($"Filter:");
                    string errorlink = (htmltags) ? "<span class=\"errorlink\">" : "";
                    string spanclose = (htmltags) ? "</span>" : "";
                    string message   = (PropertyOfIndividual == null || PropertyOfIndividual == "") ? "Not Set" : $"Unknown: {PropertyOfIndividual}";
                    filterWriter.Write($"{errorlink}{message}{spanclose}");
                    return(filterWriter.ToString());
                }

                filterWriter.Write($"Filter:");
                bool truefalse = IsOperatorTrueFalseTest();
                if (truefalse | (propertyInfo != null && propertyInfo.PropertyType.IsEnum))
                {
                    if (propertyInfo.PropertyType == typeof(bool))
                    {
                        if (Operator == ExpressionType.IsFalse || Value?.ToString().ToLower() == "false")
                        {
                            filterWriter.Write(" not");
                        }
                        filterWriter.Write($" {CLEMModel.DisplaySummaryValueSnippet(PropertyOfIndividual, "Not set", HTMLSummaryStyle.Filter, htmlTags: htmltags)}");
                    }
                    else
                    {
                        filterWriter.Write($" {CLEMModel.DisplaySummaryValueSnippet(PropertyOfIndividual, "Not set", HTMLSummaryStyle.Filter, htmlTags: htmltags)}");
                        if (validOperator)
                        {
                            filterWriter.Write((Operator == ExpressionType.IsFalse || Value?.ToString().ToLower() == "false") ? " not" : " is");
                        }
                        else
                        {
                            string errorlink = (htmltags) ? "<span class=\"errorlink\">" : "";
                            string spanclose = (htmltags) ? "</span>" : "";
                            filterWriter.Write($"{errorlink}{OperatorToSymbol()} is invalid for property {propertyInfo.PropertyType.Name}{spanclose}");
                        }
                        filterWriter.Write($" {CLEMModel.DisplaySummaryValueSnippet(Value?.ToString(), "No value", HTMLSummaryStyle.Filter, htmlTags: htmltags)}");
                    }
                }
                else
                {
                    filterWriter.Write($" {CLEMModel.DisplaySummaryValueSnippet(PropertyOfIndividual, "Not set", HTMLSummaryStyle.Filter, htmlTags: htmltags)}");

                    if (propertyInfo != null)
                    {
                        if (validOperator)
                        {
                            filterWriter.Write($" {CLEMModel.DisplaySummaryValueSnippet(OperatorToSymbol(), "Unknown operator", HTMLSummaryStyle.Filter, htmlTags: htmltags)}");
                        }
                        else
                        {
                            string errorlink = (htmltags) ? "<span class=\"errorlink\">" : "";
                            string spanclose = (htmltags) ? "</span>" : "";
                            filterWriter.Write($"{errorlink}{OperatorToSymbol()} is invalid for property {propertyInfo.PropertyType.Name}{spanclose}");
                        }
                    }
                    else
                    {
                        filterWriter.Write($" {CLEMModel.DisplaySummaryValueSnippet(OperatorToSymbol(), "Unknown operator", HTMLSummaryStyle.Filter, htmlTags: htmltags)}");
                    }

                    filterWriter.Write($" {CLEMModel.DisplaySummaryValueSnippet(Value?.ToString(), "No value", HTMLSummaryStyle.Filter, htmlTags: htmltags)}");
                }
                return(filterWriter.ToString());
            }
        }
예제 #8
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="removeAmount"></param>
 /// <param name="activity"></param>
 /// <param name="reason"></param>
 public double Remove(double removeAmount, CLEMModel activity, string reason)
 {
     removeAmount = Math.Min(this.amount, removeAmount);
     this.amount -= removeAmount;
     return(removeAmount);
 }
예제 #9
0
        /// <summary>
        /// Graze food add method.
        /// This style is not supported in GrazeFoodStoreType
        /// </summary>
        /// <param name="resourceAmount">Object to add. This object can be double or contain additional information (e.g. Nitrogen) of food being added</param>
        /// <param name="activity">Name of activity adding resource</param>
        /// <param name="relatesToResource"></param>
        /// <param name="category"></param>
        public new void Add(object resourceAmount, CLEMModel activity, string relatesToResource, string category)
        {
            GrazeFoodStorePool pool;

            switch (resourceAmount.GetType().Name)
            {
            case "GrazeFoodStorePool":
                pool = resourceAmount as GrazeFoodStorePool;
                // adjust N content only if new growth (age = 0) based on yield limits and month range defined in GrazeFoodStoreFertilityLimiter if present
                if (pool.Age == 0 && !(grazeFoodStoreFertilityLimiter is null))
                {
                    double reduction = grazeFoodStoreFertilityLimiter.GetProportionNitrogenLimited(pool.Amount / Manager.Area);
                    pool.Nitrogen = Math.Max(MinimumNitrogen, pool.Nitrogen * reduction);
                }
                break;

            case "FoodResourcePacket":
                pool = new GrazeFoodStorePool();
                FoodResourcePacket packet = resourceAmount as FoodResourcePacket;
                pool.Set(packet.Amount);
                pool.Nitrogen = packet.PercentN;
                pool.DMD      = packet.DMD;
                break;

            case "Double":
                pool = new GrazeFoodStorePool();
                pool.Set((double)resourceAmount);
                pool.Nitrogen = this.Nitrogen;
                pool.DMD      = this.EstimateDMD(this.Nitrogen);
                break;

            default:
                // expecting a GrazeFoodStoreResource (PastureManage) or FoodResourcePacket (CropManage) or Double from G-Range
                throw new Exception(String.Format("ResourceAmount object of type {0} is not supported in Add method in {1}", resourceAmount.GetType().ToString(), this.Name));
            }
            if (pool.Amount > 0)
            {
                // allow decaying or no pools currently available
                if (PastureDecays || Pools.Count() == 0)
                {
                    Pools.Insert(0, pool);
                }
                else
                {
                    Pools[0].Add(pool);
                }
                // update biomass available
                if (!category.StartsWith("Initialise"))
                {
                    // do not update if this is ian initialisation pool
                    biomassAddedThisYear += pool.Amount;
                }

                ResourceTransaction details = new ResourceTransaction
                {
                    Style             = TransactionStyle.Gain,
                    Amount            = pool.Amount,
                    Activity          = activity,
                    RelatesToResource = relatesToResource,
                    Category          = category,
                    ResourceType      = this
                };
                LastTransaction = details;
                LastGain        = pool.Amount;
                TransactionEventArgs te = new TransactionEventArgs()
                {
                    Transaction = details
                };
                OnTransactionOccurred(te);
            }
        }
예제 #10
0
        private void OnCommencing(object sender, EventArgs e)
        {
            dataToWriteToDb = null;
            // sanitise the variable names and remove duplicates
            List <string> variableNames = new List <string>();

            variableNames.Add("Parent.Name as Zone");

            if (VariableNames.Where(a => a.Contains("[Clock].Today")).Count() == 0)
            {
                variableNames.Add("[Clock].Today as Date");
            }

            if (VariableNames != null)
            {
                for (int i = 0; i < this.VariableNames.Length; i++)
                {
                    // each variable name is now a ResourceGroup
                    bool isDuplicate = StringUtilities.IndexOfCaseInsensitive(variableNames, this.VariableNames[i].Trim()) != -1;
                    if (!isDuplicate && this.VariableNames[i] != string.Empty)
                    {
                        if (this.VariableNames[i].StartsWith("["))
                        {
                            variableNames.Add(this.VariableNames[i]);
                        }
                        else
                        {
                            // check it is a ResourceGroup
                            CLEMModel model = Resources.GetResourceGroupByName(this.VariableNames[i]) as CLEMModel;
                            if (model == null)
                            {
                                throw new ApsimXException(this, String.Format("@error:Invalid resource group [r={0}] in ReportResourceBalances [{1}]\nEntry has been ignored", this.VariableNames[i], this.Name));
                            }
                            else
                            {
                                if (model.GetType().Name == "Labour")
                                {
                                    for (int j = 0; j < (model as Labour).Items.Count; j++)
                                    {
                                        variableNames.Add("[Resources]." + this.VariableNames[i] + ".Items[" + (j + 1).ToString() + "].AvailableDays as " + (model as Labour).Items[j].Name);
                                    }
                                }
                                else
                                {
                                    // get all children
                                    foreach (CLEMModel item in model.Children.Where(a => a.GetType().IsSubclassOf(typeof(CLEMModel)))) // Apsim.Children(this, typeof(CLEMModel))) //
                                    {
                                        string amountStr = "Amount";
                                        switch (item.GetType().Name)
                                        {
                                        case "FinanceType":
                                            amountStr = "Balance";
                                            break;

                                        case "LabourType":
                                            amountStr = "AvailableDays";
                                            break;

                                        default:
                                            break;
                                        }
                                        variableNames.Add("[Resources]." + this.VariableNames[i] + "." + item.Name + "." + amountStr + " as " + item.Name);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            base.VariableNames = variableNames.ToArray();
            this.FindVariableMembers();

            if (EventNames[0] == "")
            {
                events.Subscribe("[Clock].CLEMEndOfTimeStep", DoOutputEvent);
            }
            else
            {
                // Subscribe to events.
                foreach (string eventName in EventNames)
                {
                    if (eventName != string.Empty)
                    {
                        events.Subscribe(eventName.Trim(), DoOutputEvent);
                    }
                }
            }
        }
예제 #11
0
        /// <inheritdoc/>
        public override string ModelSummary()
        {
            string tagstring = CLEMModel.DisplaySummaryValueSnippet(TagLabel, "Not set");

            return($"\r\n<div class=\"activityentry\">{ApplicationStyle} the tag {tagstring} {((ApplicationStyle == TagApplicationStyle.Add)?"to":"from")} all individuals in the following groups</div>");
        }
예제 #12
0
        /// <inheritdoc/>
        public override string ModelSummary()
        {
            string html = $"<div class=\"activityentry\">Currency is {CLEMModel.DisplaySummaryValueSnippet(CurrencyName, "Not specified")}</div>";

            return(html);
        }
예제 #13
0
        private void OnCommencing(object sender, EventArgs e)
        {
            int lossModifier = 1;

            if (ReportLossesAsNegative)
            {
                lossModifier = -1;
            }

            // check if running from a CLEM.Market
            bool market = (FindAncestor <Zone>().GetType() == typeof(Market));

            List <string> variableNames = new List <string>
            {
                "[Clock].Today as Date"
            };

            if (IncludeFinancialYear)
            {
                Finance financeStore = resources.FindResourceGroup <Finance>();
                if (financeStore != null)
                {
                    variableNames.Add($"[Resources].{financeStore.Name}.FinancialYear as FY");
                }
            }

            List <string> eventNames = new List <string>();

            if (ResourceGroupsToReport != null && ResourceGroupsToReport.Trim() != "")
            {
                // check it is a ResourceGroup
                CLEMModel model = resources.FindResource <ResourceBaseWithTransactions>(ResourceGroupsToReport);
                if (model == null)
                {
                    summary.WriteMessage(this, String.Format("Invalid resource group [{0}] in ReportResourceBalances [{1}]\r\nEntry has been ignored", this.ResourceGroupsToReport, this.Name), MessageType.Warning);
                }
                else
                {
                    bool pricingIncluded = false;
                    if (model.GetType() == typeof(RuminantHerd))
                    {
                        pricingIncluded = model.FindAllDescendants <AnimalPricing>().Where(a => a.Enabled).Count() > 0;

                        variableNames.Add("[Resources]." + this.ResourceGroupsToReport + ".LastIndividualChanged.ID as uID");
                        variableNames.Add("[Resources]." + this.ResourceGroupsToReport + ".LastIndividualChanged.Breed as Breed");
                        variableNames.Add("[Resources]." + this.ResourceGroupsToReport + ".LastIndividualChanged.Sex as Sex");
                        variableNames.Add("[Resources]." + this.ResourceGroupsToReport + ".LastIndividualChanged.Age as Age");
                        variableNames.Add("[Resources]." + this.ResourceGroupsToReport + ".LastIndividualChanged.Weight as Weight");
                        variableNames.Add("[Resources]." + this.ResourceGroupsToReport + ".LastIndividualChanged.AdultEquivalent as AE");
                        variableNames.Add("[Resources]." + this.ResourceGroupsToReport + ".LastIndividualChanged.SaleFlag as Category");
                        variableNames.Add("[Resources]." + this.ResourceGroupsToReport + ".LastIndividualChanged.Class as Class");
                        variableNames.Add("[Resources]." + this.ResourceGroupsToReport + ".LastIndividualChanged.HerdName as RelatesTo");
                        variableNames.Add("[Resources]." + this.ResourceGroupsToReport + ".LastIndividualChanged.PopulationChangeDirection as Change");

                        // ToDo: add pricing for ruminants including buy and sell pricing
                        // Needs update in CLEMResourceTypeBase and link between ResourcePricing and AnimalPricing.
                    }
                    else
                    {
                        pricingIncluded = model.FindAllDescendants <ResourcePricing>().Where(a => a.Enabled).Count() > 0;

                        if (ReportStyle == ReportTransactionStyle.GainAndLossColumns)
                        {
                            variableNames.Add("[Resources]." + this.ResourceGroupsToReport + ".LastTransaction.Gain as Gain");
                            variableNames.Add("[Resources]." + this.ResourceGroupsToReport + $".LastTransaction.Loss * {lossModifier} as Loss");
                        }
                        else
                        {
                            variableNames.Add("[Resources]." + this.ResourceGroupsToReport + ".LastTransaction.TransactionType as Type");
                            variableNames.Add("[Resources]." + this.ResourceGroupsToReport + $".LastTransaction.AmountModifiedForLoss({ReportLossesAsNegative}) as Amount");
                        }

                        // get all converters for this type of resource
                        if (IncludeConversions)
                        {
                            var converterList = model.FindAllDescendants <ResourceUnitsConverter>().Select(a => a.Name).Distinct();
                            if (converterList != null)
                            {
                                foreach (var item in converterList)
                                {
                                    if (ReportStyle == ReportTransactionStyle.GainAndLossColumns)
                                    {
                                        variableNames.Add($"[Resources].{this.ResourceGroupsToReport}.LastTransaction.ConvertTo(\"{item}\",\"gain\",{ReportLossesAsNegative}) as {item}_Gain");
                                        variableNames.Add($"[Resources].{this.ResourceGroupsToReport}.LastTransaction.ConvertTo(\"{item}\",\"loss\",{ReportLossesAsNegative}) as {item}_Loss");
                                    }
                                    else
                                    {
                                        variableNames.Add($"[Resources].{this.ResourceGroupsToReport}.LastTransaction.ConvertTo(\"{item}\", {ReportLossesAsNegative}) as {item}_Amount");
                                    }
                                }
                            }
                        }

                        // add pricing
                        if (IncludePrice && pricingIncluded)
                        {
                            if (ReportStyle == ReportTransactionStyle.GainAndLossColumns)
                            {
                                variableNames.Add("[Resources]." + this.ResourceGroupsToReport + $".LastTransaction.ConvertTo(\"$gain\",\"gain\", {ReportLossesAsNegative}) as Price_Gain");
                                variableNames.Add("[Resources]." + this.ResourceGroupsToReport + $".LastTransaction.ConvertTo(\"$loss\",\"loss\", {ReportLossesAsNegative}) as Price_Loss");
                            }
                            else
                            {
                                variableNames.Add("[Resources]." + this.ResourceGroupsToReport + $".LastTransaction.ConvertTo(\"$gain\", {ReportLossesAsNegative}) as Price_Amount");
                            }
                        }

                        variableNames.Add("[Resources]." + this.ResourceGroupsToReport + ".LastTransaction.ResourceType.Name as Resource");
                        // if this is a multi CLEM model simulation then add a new column with the parent Zone name
                        if (FindAncestor <Simulation>().FindChild <Market>() != null)
                        {
                            variableNames.Add("[Resources]." + this.ResourceGroupsToReport + ".LastTransaction.Activity.CLEMParentName as Source");
                        }
                        variableNames.Add("[Resources]." + this.ResourceGroupsToReport + ".LastTransaction.Activity.Name as Activity");
                        variableNames.Add("[Resources]." + this.ResourceGroupsToReport + ".LastTransaction.RelatesToResource as RelatesTo");
                        variableNames.Add("[Resources]." + this.ResourceGroupsToReport + ".LastTransaction.Category as Category");
                    }
                }
                eventNames.Add("[Resources]." + this.ResourceGroupsToReport + ".TransactionOccurred");
            }

            VariableNames = variableNames.ToArray();
            EventNames    = eventNames.ToArray();
            SubscribeToEvents();
        }
예제 #14
0
        [EventSubscribe("FinalInitialise")] // "Commencing"
        private void OnCommencing(object sender, EventArgs e)
        {
            if (ResourceGroupsToReport is null || !ResourceGroupsToReport.Any())
            {
                return;
            }

            timers = FindAllChildren <IActivityTimer>();

            List <string> variableNames = new List <string>();

            if (ResourceGroupsToReport.Where(a => a.Contains("[Clock].Today")).Any() is false)
            {
                variableNames.Add("[Clock].Today as Date");
            }

            if (ResourceGroupsToReport != null)
            {
                for (int i = 0; i < this.ResourceGroupsToReport.Length; i++)
                {
                    // each variable name is now a ResourceGroup
                    bool isDuplicate = StringUtilities.IndexOfCaseInsensitive(variableNames, this.ResourceGroupsToReport[i].Trim()) != -1;
                    if (!isDuplicate && this.ResourceGroupsToReport[i] != string.Empty)
                    {
                        if (this.ResourceGroupsToReport[i].StartsWith("["))
                        {
                            variableNames.Add(this.ResourceGroupsToReport[i]);
                        }
                        else
                        {
                            // check it is a ResourceGroup
                            CLEMModel model = resources.FindResource <ResourceBaseWithTransactions>(this.ResourceGroupsToReport[i]);
                            if (model == null)
                            {
                                summary.WriteMessage(this, $"Invalid resource group [r={this.ResourceGroupsToReport[i]}] in ReportResourceBalances [{this.Name}]{Environment.NewLine}Entry has been ignored", MessageType.Warning);
                            }
                            else
                            {
                                if (model is Labour)
                                {
                                    string amountStr = "Amount";
                                    if (ReportLabourIndividuals)
                                    {
                                        amountStr = "Individuals";
                                    }

                                    for (int j = 0; j < (model as Labour).Items.Count; j++)
                                    {
                                        if (ReportAmount)
                                        {
                                            variableNames.Add("[Resources]." + this.ResourceGroupsToReport[i] + ".Items[" + (j + 1).ToString() + $"].{amountStr} as " + (model as Labour).Items[j].Name);
                                        }

                                        //TODO: what economic metric is needed for labour
                                        //TODO: add ability to report labour value if required
                                    }
                                }
                                else
                                {
                                    foreach (CLEMModel item in model.FindAllChildren <CLEMModel>())
                                    {
                                        string amountStr = "Amount";
                                        switch (item)
                                        {
                                        case FinanceType ftype:
                                            amountStr = "Balance";
                                            break;

                                        case LandType ltype:
                                            if (ReportLandEntire)
                                            {
                                                amountStr = "LandArea";
                                            }
                                            break;

                                        default:
                                            break;
                                        }
                                        if (item is RuminantType)
                                        {
                                            // add each variable needed
                                            foreach (var category in (model as RuminantHerd).GetReportingGroups(item as RuminantType))
                                            {
                                                if (ReportAmount)
                                                {
                                                    variableNames.Add($"[Resources].{this.ResourceGroupsToReport[i]}.GetRuminantReportGroup(\"{(item as IModel).Name}\",\"{category}\").Count as {item.Name.Replace(" ", "_")}{(((model as RuminantHerd).TransactionStyle != RuminantTransactionsGroupingStyle.Combined) ? $".{category.Replace(" ", "_")}" : "")}.Count");
                                                }
                                                if (ReportAnimalEquivalents)
                                                {
                                                    variableNames.Add($"[Resources].{this.ResourceGroupsToReport[i]}.GetRuminantReportGroup(\"{(item as IModel).Name}\",\"{category}\").TotalAdultEquivalent as {item.Name.Replace(" ", "_")}{(((model as RuminantHerd).TransactionStyle != RuminantTransactionsGroupingStyle.Combined) ? $".{category.Replace(" ", "_")}" : "")}.TotalAdultEquivalent");
                                                }
                                                if (ReportAnimalWeight)
                                                {
                                                    variableNames.Add($"[Resources].{this.ResourceGroupsToReport[i]}.GetRuminantReportGroup(\"{(item as IModel).Name}\",\"{category}\").TotalWeight as {item.Name.Replace(" ", "_")}{(((model as RuminantHerd).TransactionStyle != RuminantTransactionsGroupingStyle.Combined) ? $".{category.Replace(" ", "_")}" : "")}.TotalWeight");
                                                }
                                                if (ReportValue)
                                                {
                                                    variableNames.Add($"[Resources].{this.ResourceGroupsToReport[i]}.GetRuminantReportGroup(\"{(item as IModel).Name}\",\"{category}\").TotalPrice as {item.Name.Replace(" ", "_")}{(((model as RuminantHerd).TransactionStyle != RuminantTransactionsGroupingStyle.Combined) ? $".{category.Replace(" ", "_")}" : "")}.TotalPrice");
                                                }
                                            }
                                        }
                                        else
                                        {
                                            if (ReportAmount)
                                            {
                                                variableNames.Add($"[Resources].{this.ResourceGroupsToReport[i]}.{ item.Name}.{ amountStr } as { item.Name.Replace(" ", "_") }_Amount");
                                            }
                                            if (ReportValue & item.GetType() != typeof(FinanceType))
                                            {
                                                variableNames.Add($"[Resources].{this.ResourceGroupsToReport[i]}.{item.Name}.Value as { item.Name.Replace(" ", "_") }_DollarValue");
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            VariableNames = variableNames.ToArray();
            // Subscribe to events.
            if (EventNames == null || !EventNames.Where(a => a.Trim() != "").Any())
            {
                EventNames = new string[] { "[Clock].CLEMFinalizeTimeStep" }
            }
            ;

            SubscribeToEvents();
        }
예제 #15
0
 public void Refresh()
 {
     this.genericView.Text = CreateMarkdown(this.model);
     // save summary to disk
     System.IO.File.WriteAllText(Path.Combine(Path.GetDirectoryName(explorer.ApsimXFile.FileName), "CurrentDescriptiveSummary.html"), CLEMModel.CreateDescriptiveSummaryHTML(this.model, Utility.Configuration.Settings.DarkTheme));
 }
예제 #16
0
        private void OnCommencing(object sender, EventArgs e)
        {
            int lossModifier = 1;

            if (ReportLossesAsNegative)
            {
                lossModifier = -1;
            }

            // check if running from a CLEM.Market
            bool market = (FindAncestor <Zone>().GetType() == typeof(Market));

            dataToWriteToDb = null;
            // sanitise the variable names and remove duplicates
            List <string> variableNames = new List <string>
            {
                "[Clock].Today as Date"
            };

            if (VariableNames != null && VariableNames.Count() > 0)
            {
                if (VariableNames.Count() > 1)
                {
                    Summary.WriteWarning(this, String.Format("Multiple resource groups not permitted in ReportResourceLedger [{0}]\r\nAdditional entries have been ignored", this.Name));
                }

                for (int i = 0; i < 1; i++)
                {
                    // each variable name is now a ResourceGroup
                    bool isDuplicate = StringUtilities.IndexOfCaseInsensitive(variableNames, this.VariableNames[i].Trim()) != -1;
                    if (!isDuplicate && this.VariableNames[i] != string.Empty)
                    {
                        // check it is a ResourceGroup
                        CLEMModel model = Resources.GetResourceGroupByName(this.VariableNames[i]) as CLEMModel;
                        if (model == null)
                        {
                            Summary.WriteWarning(this, String.Format("Invalid resource group [{0}] in ReportResourceBalances [{1}]\r\nEntry has been ignored", this.VariableNames[i], this.Name));
                        }
                        else
                        {
                            bool pricingIncluded = false;
                            if (model.GetType() == typeof(RuminantHerd))
                            {
                                pricingIncluded = model.FindAllDescendants <AnimalPricing>().Where(a => a.Enabled).Count() > 0;

                                variableNames.Add("[Resources]." + this.VariableNames[i] + ".LastTransaction.ExtraInformation.ID as uID");
                                variableNames.Add("[Resources]." + this.VariableNames[i] + ".LastTransaction.ExtraInformation.Breed as Breed");
                                variableNames.Add("[Resources]." + this.VariableNames[i] + ".LastTransaction.ExtraInformation.Gender as Sex");
                                variableNames.Add("[Resources]." + this.VariableNames[i] + ".LastTransaction.ExtraInformation.Age as Age");
                                variableNames.Add("[Resources]." + this.VariableNames[i] + ".LastTransaction.ExtraInformation.Weight as Weight");
                                variableNames.Add("[Resources]." + this.VariableNames[i] + ".LastTransaction.ExtraInformation.AdultEquivalent as AE");
                                variableNames.Add("[Resources]." + this.VariableNames[i] + ".LastTransaction.ExtraInformation.SaleFlag as Category");
                                variableNames.Add("[Resources]." + this.VariableNames[i] + ".LastTransaction.ExtraInformation.HerdName as RelatesTo");
                                variableNames.Add("[Resources]." + this.VariableNames[i] + ".LastTransaction.ExtraInformation.PopulationChangeDirection as Change");

                                // ToDo: add pricing for ruminants including buy and sell pricing
                                // Needs update in CLEMResourceTypeBase and link between ResourcePricing and AnimalPricing.
                            }
                            else
                            {
                                pricingIncluded = model.FindAllDescendants <ResourcePricing>().Where(a => a.Enabled).Count() > 0;

                                if (ReportStyle == ReportTransactionStyle.GainAndLossColumns)
                                {
                                    variableNames.Add("[Resources]." + this.VariableNames[i] + ".LastTransaction.Gain as Gain");
                                    variableNames.Add("[Resources]." + this.VariableNames[i] + $".LastTransaction.Loss * {lossModifier} as Loss");
                                }
                                else
                                {
                                    variableNames.Add("[Resources]." + this.VariableNames[i] + ".LastTransaction.TransactionType as Type");
                                    variableNames.Add("[Resources]." + this.VariableNames[i] + $".LastTransaction.AmountModifiedForLoss({ReportLossesAsNegative}) as Amount");
                                }

                                // get all converters for this type of resource
                                if (IncludeConversions)
                                {
                                    var converterList = model.FindAllDescendants <ResourceUnitsConverter>().Select(a => a.Name).Distinct();
                                    if (converterList != null)
                                    {
                                        foreach (var item in converterList)
                                        {
                                            if (ReportStyle == ReportTransactionStyle.GainAndLossColumns)
                                            {
                                                variableNames.Add("[Resources]." + this.VariableNames[i] + ".LastTransaction.ConvertTo(" + item + $",\"gain\",{ReportLossesAsNegative}) as " + item + "_Gain");
                                                variableNames.Add("[Resources]." + this.VariableNames[i] + ".LastTransaction.ConvertTo(" + item + $",\"loss\",{ReportLossesAsNegative}) as " + item + "_Loss");
                                            }
                                            else
                                            {
                                                variableNames.Add("[Resources]." + this.VariableNames[i] + ".LastTransaction.ConvertTo(" + item + $"\", {ReportLossesAsNegative}) as " + item + "_Amount");
                                            }
                                        }
                                    }
                                }

                                // add pricing
                                if (IncludePrice && pricingIncluded)
                                {
                                    if (ReportStyle == ReportTransactionStyle.GainAndLossColumns)
                                    {
                                        variableNames.Add("[Resources]." + this.VariableNames[i] + $".LastTransaction.ConvertTo(\"$gain\",\"gain\", {ReportLossesAsNegative}) as Price_Gain");
                                        variableNames.Add("[Resources]." + this.VariableNames[i] + $".LastTransaction.ConvertTo(\"$loss\",\"loss\", {ReportLossesAsNegative}) as Price_Loss");
                                    }
                                    else
                                    {
                                        variableNames.Add("[Resources]." + this.VariableNames[i] + $".LastTransaction.ConvertTo(\"$gain\", {ReportLossesAsNegative}) as Price_Amount");
                                    }
                                }

                                variableNames.Add("[Resources]." + this.VariableNames[i] + ".LastTransaction.ResourceType.Name as Resource");
                                // if this is a multi CLEM model simulation then add a new column with the parent Zone name
                                if (FindAncestor <Simulation>().FindChild <Market>() != null)
                                {
                                    variableNames.Add("[Resources]." + this.VariableNames[i] + ".LastTransaction.Activity.CLEMParentName as Source");
                                }
                                variableNames.Add("[Resources]." + this.VariableNames[i] + ".LastTransaction.Activity.Name as Activity");
                                variableNames.Add("[Resources]." + this.VariableNames[i] + ".LastTransaction.RelatesToResource as RelatesTo");
                                variableNames.Add("[Resources]." + this.VariableNames[i] + ".LastTransaction.Category as Category");
                            }
                        }
                    }
                }
                events.Subscribe("[Resources]." + this.VariableNames[0] + ".TransactionOccurred", DoOutputEvent);
            }
            // Tidy up variable/event names.
            base.VariableNames = variableNames.ToArray();
            VariableNames      = variableNames.ToArray();
            base.VariableNames = TidyUpVariableNames();
            VariableNames      = base.VariableNames;
            base.EventNames    = TidyUpEventNames();
            EventNames         = base.EventNames;
            this.FindVariableMembers();
        }