예제 #1
0
        internal static PageData Run(string runItemName, bool extract, bool isNormalRun,
                                     ManagementItem mi,
                                     CropParameterItem pi,
                                     RunOptionItem roi,
                                     SiteItem sii,
                                     SoilItem soi,
                                     CropParameterItem vi)
        {
            RunInstance.Start(vi, soi, sii, mi, pi, roi);

            if (extract)
            {
                return(OutputFile.ExtractNormalRun(RunInstance));
            }
            return(null);
        }
예제 #2
0
        public static void GetItems(string runItemName,
                                    string miName, string piName, string roiName, string siiName, string soiName, string viName,
                                    ref ManagementItem mi, ref CropParameterItem pi, ref RunOptionItem roi, ref SiteItem sii, ref SoilItem soi, ref CropParameterItem vi)
        {
            mi = ProjectFile.This.FileContainer.ManagementFile[miName];
            pi = ProjectFile.This.FileContainer.NonVarietyFile[piName];
            if (pi == null)
            {
                pi = ProjectFile.This.FileContainer.MaizeNonVarietyFile[piName];
            }
            roi = ProjectFile.This.FileContainer.RunOptionFile[roiName];
            sii = ProjectFile.This.FileContainer.SiteFile[siiName];
            soi = ProjectFile.This.FileContainer.SoilFile[soiName];
            vi  = ProjectFile.This.FileContainer.VarietyFile[viName];
            if (vi == null)
            {
                vi = ProjectFile.This.FileContainer.MaizeVarietyFile[viName];
            }

            if (mi == null)
            {
                throw new RunException(runItemName, "Management not found: " + miName);
            }
            if (pi == null)
            {
                throw new RunException(runItemName, "Parameter not found: " + piName);
            }
            if (roi == null)
            {
                throw new RunException(runItemName, "Element option not found: " + roiName);
            }
            if (sii == null)
            {
                throw new RunException(runItemName, "Site not found: " + siiName);
            }
            if (soi == null)
            {
                throw new RunException(runItemName, "Soil not found: " + soiName);
            }
            if (vi == null)
            {
                throw new RunException(runItemName, "Variety not found: " + viName);
            }
        }
예제 #3
0
        public double GetValue(ManagementItem mi, CropParameterItem pi, RunOptionItem roi, SiteItem sii, SoilItem soi, CropParameterItem vi)
        {
            double result;
            var    fileID       = GetFileID();
            var    propertyName = GetPropertyName();


            if (fileID == "Crop")
            {
                //look in non varietal file
                if (pi.paramValue.ContainsKey(propertyName))
                {
                    result = pi.paramValue[propertyName];
                }
                else
                {
                    //look in varietal file
                    if (vi.paramValue.ContainsKey(propertyName))
                    {
                        result = vi.paramValue[propertyName];
                    }
                    else
                    {
                        throw new Exception("Parameter " + propertyName + " was not found in the varietal or non varietal files");
                    }
                }
            }
            else
            {
                var item = GetItem(mi, roi, sii, soi);
                if (propertyInfo == null)
                {
                    propertyInfo = item.GetType().GetProperty(propertyName);
                }
                result = (double)propertyInfo.GetValue(item, null);
            }

            return(result);
        }
예제 #4
0
        private object GetItem(ManagementItem mi, RunOptionItem roi, SiteItem sii, SoilItem soi)
        {
            var fileID = GetFileID();

            if (fileID == FileContainer.ManagementID)
            {
                return(mi);
            }
            if (fileID == FileContainer.RunOptionID)
            {
                return(roi);
            }
            if (fileID == FileContainer.SiteID)
            {
                return(sii);
            }
            if (fileID == FileContainer.SoilID)
            {
                return(soi);
            }
            throw new RunException(ParentRunItem.Name, "Unknow file ID : " + fileID);
        }
예제 #5
0
        public void DoStop()
        {
            varietyDef    = null;
            soilDef       = null;
            siteDef       = null;
            managementDef = null;
            parametersDef = null;
            runOptionsDef = null;
            var nbRun = savedUniverses != null ? savedUniverses.Count : 0;

            for (var i = 0; i < nbRun; ++i)
            {
                var universe = savedUniverses[i];
                if (universe != null)
                {
                    universe.Dispose();
                    savedUniverses[i] = null;
                }
            }
            savedUniverses = null;

            currentUniverse = null;
        }
예제 #6
0
        public override void StepRun(bool serialize, int i, string variety = null, string parameterName = null, double parameterValue = 0)
        {
            if (i == 0)
            {
                ///<Behnam>
                string miName, piName, riName, roiName, siiName, soiName, viName;
                miName  = RunItem.Normal.ManagementItem;
                piName  = RunItem.Normal.ParameterItem;
                riName  = RunItem.Name;
                roiName = RunItem.Normal.RunOptionItem;
                siiName = RunItem.Normal.SiteItem;
                soiName = RunItem.Normal.SoilItem;
                viName  = RunItem.Normal.VarietyItem;

                ManagementItem    mi  = null;
                CropParameterItem pi  = null;
                RunOptionItem     roi = null;
                SiteItem          sii = null;
                SoilItem          soi = null;
                CropParameterItem vi  = null;
                RunCore.GetItems(riName, miName, piName, roiName, siiName, soiName, viName, ref mi, ref pi, ref roi, ref sii, ref soi, ref vi);

                switch (roi.OutputPattern)
                {
                case "V13": ProjectFile.OutputVersion = OutputVersion.V13; break;

                case "V15": ProjectFile.OutputVersion = OutputVersion.V15; break;

                case "Cus": ProjectFile.OutputVersion = OutputVersion.Cus; break;

                case "Maize": ProjectFile.OutputVersion = OutputVersion.Maize; break;
                }
                ///</Behnam>

                ///<Behnam (2016.01.19)>
                ///<Comment>Adding the Summary file to the outputs of a Normal run</Comment>
                var SumOutputFileName = OutputFile.ExtractMultiRunHeader();
                SumOutputFileName.Title = OutputFileName.Replace(OutputExtention, SumOutputExtention);
                Book.Add(SumOutputFileName);

                Run.isFirstYear = true;
                var excelPage = RunCore.Run(RunItem.Name, true, true, ManagementItem, ParameterItem, RunOptionItem, SiteItem, SoilItem, VarietyItem);
                excelPage.Title = OutputFileName;
                Book.Add(excelPage);

                var WarningOutputFileName = OutputFile.ExtractWarningsNormalRun(RunCore.RunInstance);
                WarningOutputFileName.Title = "Warnings";
                Book.Add(WarningOutputFileName);


                if (serialize)
                {
                    RunCore.Save(excelPage, AbsoluteOutputPath, true);
                }

                if (ProjectFile.OutputVersion == OutputVersion.Cus)
                {
                    Run.SecondLine = false;
                    Book[0].Add(OutputFile.ExtractMultiRunLine(RunCore.RunInstance));
                }
                Book[0].Add(OutputFile.ExtractMultiRunLine(RunCore.RunInstance));
                ///</Behnam>
            }
            else
            {
                throw new RunException(RunItem.Name, "Normal run index != 0");
            }
        }
예제 #7
0
        public override void StepRun(bool serialize, int i, string variety = null, string parameterName = null, double parameterValue = 0)
        {
            #region get items

            string miName, piName, riName, roiName, siiName, soiName, viName, exName;

            if (MultiRuns.Count > 0)
            {
                var item = MultiRuns[i];
                miName  = item.ManagementItemSelected;
                piName  = item.ParameterItemSelected;
                riName  = RunItem.Name;
                roiName = item.RunOptionItemSelected;
                siiName = item.SiteItemSelected;
                soiName = item.SoilItemSelected;
                viName  = item.VarietyItemSelected;
                exName  = item.ExperimentSelected;
            }
            else
            {
                miName  = RunItem.Normal.ManagementItem;
                piName  = RunItem.Normal.ParameterItem;
                riName  = RunItem.Name;
                roiName = RunItem.Normal.RunOptionItem;
                siiName = RunItem.Normal.SiteItem;
                soiName = RunItem.Normal.SoilItem;
                viName  = RunItem.Normal.VarietyItem;
                exName  = RunItem.Normal.ExperimentItem;
            }

            ManagementItem    mi  = null;
            CropParameterItem pi  = null;
            RunOptionItem     roi = null;
            SiteItem          sii = null;
            SoilItem          soi = null;
            CropParameterItem vi  = null;
            RunCore.GetItems(riName, miName, piName, roiName, siiName, soiName, viName, ref mi, ref pi, ref roi, ref sii, ref soi, ref vi);

            #endregion

            #region override some parameters

            if (variety != null)
            {
                if (variety == viName)
                {
                    vi.ParamValue[parameterName] = parameterValue;
                }
            }

            #endregion

            if (!multiYear)
            {
                switch (roi.OutputPattern)
                {
                case "V13": ProjectFile.OutputVersion = OutputVersion.V13; break;

                case "V15": ProjectFile.OutputVersion = OutputVersion.V15; break;

                case "Cus": ProjectFile.OutputVersion = OutputVersion.Cus; break;

                case "Maize": ProjectFile.OutputVersion = OutputVersion.Maize; break;
                }

                ///<Behnam>
                ///<Comment>
                ///Modifications related to estimating sowing window and forcing the model
                ///to put daily outputs into one file if the names of the daily output files
                ///are identical for two successive years.
                ///</Comment>

                var yy = sii.MaxSowingDate.Year - sii.MinSowingDate.Year;
                mi.SowingDate     = new DateTime(mi.SowingDate.Year, mi.SowingDate.Month, mi.SowingDate.Day);
                sii.MinSowingDate = new DateTime(mi.SowingDate.Year, sii.MinSowingDate.Month, sii.MinSowingDate.Day);
                sii.MaxSowingDate = new DateTime(mi.SowingDate.Year + yy, sii.MaxSowingDate.Month, sii.MaxSowingDate.Day);

                Run.isFirstYear = true;
                ///</Behnam>
                //Debug
                var excelPage = RunCore.Run(riName, exportNormalRuns, false, mi, pi, roi, sii, soi, vi);

                ///<Behnam>
                if (i == 0)
                {
                    Book.Clear();
                    var outputFile = OutputFile.ExtractMultiRunHeader();
                    outputFile.Title = OutputFileName;
                    Book.Add(outputFile);
                }


                if (exportNormalRuns)
                {
                    var dailyOutputFileName = OutputPatternVarDef.OutputPatternValue(dailyOutputPattern, miName, piName, riName, roiName, siiName, soiName, viName, exName) + RunItem.Normal.OutputExtention;
                    dailyOutputFileName = dailyOutputFileName.Replace(VarMultiYearSowingYear, "");
                    excelPage.Title     = dailyOutputFileName;
                    Book.Add(excelPage);
                    if (serialize)
                    {
                        RunCore.Save(excelPage, AbsoluteOutputDirectory + "\\" + dailyOutputFileName);
                    }


                    if (i == 0)
                    {
                        warningFile       = OutputFile.ExtractWarningsHeader();
                        warningFile.Title = "warnings";
                    }

                    LineData line = OutputFile.ExtractWarningsMultiRun(RunCore.RunInstance);
                    if (line != null)
                    {
                        warningFile.Add(line);
                    }
                }

                if (i == 0 && ProjectFile.OutputVersion == OutputVersion.Cus)
                {
                    Run.SecondLine = false;
                    Book[0].Add(OutputFile.ExtractMultiRunLine(RunCore.RunInstance));
                }
                ///</Behnam>
                Book[0].Add(OutputFile.ExtractMultiRunLine(RunCore.RunInstance));

                /// Behnam (2016.06.01): Added to write the summaty file after each run is finished.
                /// Other way, if one simulations is not completed, the summary file is not pronted at all.
                if (serialize)
                {
                    RunCore.Save(Book[0], AbsoluteOutputPath);
                }
            }
            else
            {
                mi = mi.Clone();

                ///<Behnam>
                switch (roi.OutputPattern)
                {
                case "V13": ProjectFile.OutputVersion = OutputVersion.V13; break;

                case "V15": ProjectFile.OutputVersion = OutputVersion.V15; break;

                case "Cus": ProjectFile.OutputVersion = OutputVersion.Cus; break;

                case "Maize": ProjectFile.OutputVersion = OutputVersion.Maize; break;
                }

                for (var j = firstYear; j <= lastYear; ++j)
                {
                    foreach (var dateApp in mi.DateApplications)
                    {
                        dateApp.Date = new DateTime(j + (dateApp.Date.Year - mi.SowingDate.Year), dateApp.Date.Month, dateApp.Date.Day);
                    }

                    var yy = sii.MaxSowingDate.Year - sii.MinSowingDate.Year;
                    mi.SowingDate     = new DateTime(j, mi.SowingDate.Month, mi.SowingDate.Day);
                    sii.MinSowingDate = new DateTime(j, sii.MinSowingDate.Month, sii.MinSowingDate.Day);
                    sii.MaxSowingDate = new DateTime(j + yy, sii.MaxSowingDate.Month, sii.MaxSowingDate.Day);

                    Run.isFirstYear = (j == firstYear);

                    var excelPage = RunCore.Run(riName, exportNormalRuns, false, mi, pi, roi, sii, soi, vi);

                    if (i == 0 && j == firstYear)
                    {
                        Book.Clear();
                        var outputFile = OutputFile.ExtractMultiRunHeader();
                        outputFile.Title = OutputFileName;
                        Book.Add(outputFile);
                    }

                    if (exportNormalRuns)
                    {
                        var dailyOutputFileName = OutputPatternVarDef.OutputPatternValue(dailyOutputPattern, miName, piName, riName, roiName, siiName, soiName, viName, exName) + RunItem.Normal.OutputExtention;
                        dailyOutputFileName = dailyOutputFileName.Replace(VarMultiYearSowingYear, sii.MinSowingDate.Year.ToString());
                        excelPage.Title     = dailyOutputFileName;
                        Book.Add(excelPage);

                        if (j == firstYear || (j != firstYear && oldDailyOutputFileName != dailyOutputFileName))
                        {
                            if (serialize)
                            {
                                RunCore.Save(excelPage, AbsoluteOutputDirectory + "\\" + dailyOutputFileName, true);
                            }
                        }
                        else
                        {
                            if (serialize)
                            {
                                RunCore.Save(excelPage, AbsoluteOutputDirectory + "\\" + dailyOutputFileName, false);
                            }
                        }
                        oldDailyOutputFileName = dailyOutputFileName;
                    }

                    if (i == 0 && j == firstYear && ProjectFile.OutputVersion == OutputVersion.Cus)
                    {
                        Run.SecondLine = false;
                        Book[0].Add(OutputFile.ExtractMultiRunLine(RunCore.RunInstance));
                    }
                    Book[0].Add(OutputFile.ExtractMultiRunLine(RunCore.RunInstance));

                    /// Behnam (2016.06.01): Added to write the summaty file after each run is finished.
                    /// Other way, if one simulations is not completed, the summary file is not pronted at all.
                    if (serialize)
                    {
                        RunCore.Save(Book[0], AbsoluteOutputPath);
                    }
                    ///</Behnam>

                    //Warnings
                    if (i == 0 && j == firstYear)
                    {
                        warningFile       = OutputFile.ExtractWarningsHeader();
                        warningFile.Title = "warnings";
                    }

                    LineData line = OutputFile.ExtractWarningsMultiRun(RunCore.RunInstance);
                    if (line != null)
                    {
                        warningFile.Add(line);
                    }
                }
            }
            if (i == (MultiRuns.Count - 1))
            {
                Book.Add(warningFile);
            }
        }
예제 #8
0
        ///<summary>
        ///Update the run. This does the loop calculation over the year and calculate universe state.
        ///</summary>
        ///<param name="variety">The genotypeDef used in the run.</param>
        ///<param name="soil">The soilDef used in the run.</param>
        ///<param name="site">The siteDef used in the run.</param>
        ///<param name="management">The managementDef used in the run.</param>
        ///<param name="Inparameters">The parameter set used in the run.</param>
        ///<param name="runOptions">The run option set used in the run.</param>


        public void Start(
            CropParameterItem variety,
            SoilItem soil,
            SiteItem site,
            ManagementItem management,
            CropParameterItem Inparameters,
            RunOptionItem runOptions)
        {
            this.DoStop();

            // Initialisation
            //Ph=new Phenology.Phenology(new Universe(this));
            createParameters(variety, Inparameters);
            this.varietyDef    = variety;
            this.soilDef       = soil;
            this.siteDef       = site;
            this.managementDef = management;
            this.parametersDef = Inparameters;
            this.runOptionsDef = runOptions;

            if (variety != null &&
                management != null &&
                Inparameters != null &&
                runOptions != null &&
                site != null &&
                soil != null)
            {
            }

            else
            {
                throw new InvalidOperationException("Some input are null.");
            }


            savedUniverses = new RawData <Universe>(400);
            //weather = new Weather(this);

            currentUniverse = new Universe(this);

            ///<Behnam>
            ///<Comment>Estimating sowing date or using a fixed sowing date</Comment>

            IsSowDateEstimate          = management.IsSowDateEstimate;
            SowingWindowType           = site.SowingWindowType;
            management.FinalSowingDate = management.SowingDate;
            currentUniverse.Init(site, management);
            currentUniverse.Weather_.EstimateSowingWindows(site, management);
            currentUniverse.IsSowDateEstimate = IsSowDateEstimate;

            double SkipDays = Math.Max(1, management.SkipDays);

            SowingDate = management.SowingDate;
            // UseActualBase = runOptionsDef.UseActualBase;
            DoInteractions  = runOptionsDef.DoInteractions;
            InteractionsW   = runOptionsDef.InteractionsW;
            InteractionsN   = runOptionsDef.InteractionsN;
            InteractionsT   = runOptionsDef.InteractionsT;
            InteractionsWN  = runOptionsDef.InteractionsWN;
            InteractionsWT  = runOptionsDef.InteractionsWT;
            InteractionsNT  = runOptionsDef.InteractionsNT;
            InteractionsWNT = runOptionsDef.InteractionsWNT;

            if (IsSowDateEstimate)
            {
                var year1 = SowingDate.Year;

                if (SowingWindowType == 0) // Fixed sowing window
                {
                    site.FinalMinSowingDate = currentUniverse.Weather_.ESD_Fixed(year1, site);
                    site.FinalMaxSowingDate = currentUniverse.Weather_.LSD_Fixed(year1, site);
                }
                else if (SowingWindowType == 1) // JRC winter sowing window
                {
                    site.FinalMinSowingDate = currentUniverse.Weather_.ESD_Winter(year1);
                    site.FinalMaxSowingDate = currentUniverse.Weather_.LSD_Winter(year1);
                }
                else if (SowingWindowType == 2) // JRC spring sowing window
                {
                    site.FinalMinSowingDate = currentUniverse.Weather_.ESD_Spring(year1, site);
                    site.FinalMaxSowingDate = currentUniverse.Weather_.LSD_Spring(year1, site);
                }
                else if (SowingWindowType == 3) // SiriusQuality method (based on nominal sowing date)
                {
                    site.FinalMinSowingDate = currentUniverse.Weather_.ESD_Sirius(year1, site);
                    site.FinalMaxSowingDate = currentUniverse.Weather_.LSD_Sirius(year1, site);
                }

                flagReSow  = true;
                MinSowDate = site.FinalMinSowingDate.AddDays(-SkipDays);
                MaxSowDate = site.FinalMaxSowingDate;
                SowingDate = MinSowDate;
                management.FinalSowingDate = MinSowDate;
            }
            else
            {
                flagReSow = false;
                management.FinalSowingDate = SowingDate;
                site.FinalMinSowingDate    = site.MinSowingDate;
                site.FinalMaxSowingDate    = site.MaxSowingDate;
            }

            currentUniverse.Init(site, management);
            SaveCurrentUniverse();
            currentUniverse.CurrentDate = currentUniverse.CurrentDate.AddDays(1);
            //currentUniverse.Crop_.Sow(currentUniverse.calculateDailyThermalTime_.CumulTT, currentUniverse.CurrentDate);

            int    numdSkipDays = 0;
            int    numdFreezing = 0;
            int    numdSoilTemp = 0;
            int    numdSoilMois = 0;
            double numdPcp      = 0;

            ///<Behnam (2015.11.27)>
            ///<Comment>To enable using soil depth without any limitations</Comment>
            checkLay = Convert.ToInt16(Math.Ceiling(management.CheckDepth / 5)); // Soil layer to be ckecked
            checkLay = Math.Min(checkLay, currentUniverse.Soil_.Layers.Count) - 1;
            ///</Behnam>

            double CheckDaysTemp = management.CheckDaysTemp;
            double CheckDaysPcp  = management.CheckDaysPcp;

            double TAveThr       = management.TAveThr;
            double TMinThr       = management.TMinThr;
            double SoilMoistThr  = management.SoilMoistThr;
            double CumPcpThr     = management.CumPcpThr;
            double SoilWorkabThr = management.SoilWorkabThr;

            ///<Relaxation variables>
            double origTAveThr       = management.TAveThr;
            double origTMinThr       = management.TMinThr;
            double origSoilMoistThr  = management.SoilMoistThr;
            double origCumPcpThr     = management.CumPcpThr;
            double origSoilWorkabThr = management.SoilWorkabThr;

            double poTAveThr       = 1.0;
            double poTMinThr       = 1.0;
            double poSoilMoistThr  = 1.0;
            double poCumPcpThr     = 1.0;
            double poSoilWorkabThr = 1.0;
            double length          = (int)(site.FinalMaxSowingDate - site.FinalMinSowingDate).TotalDays;

            double TAveThrRelax       = 0;
            double TMinThrRelax       = -4;
            double SoilMoistThrRelax  = 0;
            double CumPcpThrRelax     = 3;
            double SoilWorkabThrRelax = 1.5;

            ///</Relaxation variables>

            ///<Relaxation curves>
            poTAveThr       = DecreasePower(TAveThr, TAveThrRelax, length);
            poTMinThr       = DecreasePower(TMinThr, TMinThrRelax, length);
            poSoilMoistThr  = DecreasePower(SoilMoistThr, SoilMoistThrRelax, length);
            poCumPcpThr     = DecreasePower(CumPcpThr, CumPcpThrRelax, length);
            poSoilWorkabThr = IncreasePower(SoilWorkabThr, SoilWorkabThrRelax, length);
            ///</Relaxation curves>

            bool oldLimitedWater       = runOptionsDef.UnlimitedWater;
            bool oldLimitedNitrogen    = runOptionsDef.UnlimitedNitrogen;
            bool oldLimitedTemperature = runOptionsDef.UnlimitedTemperature;

            bool   initSoilAfterSowing         = false;
            double minTempInitSoilAfterSowing  = 0.0;
            double maxTempInitSoilAfterSowing  = 0.0;
            double meanTempInitSoilAfterSowing = 0.0;

            while (!currentUniverse.Crop_.IsEnd)
            {
                if (!IsSowDateEstimate && !flagReSow)
                ///<Comment>Non-stressed conditions are only applied after sowing</Comment>
                {
                    if (DoInteractions)
                    {
                        ///<Parallel runs>
                        double OutputTotalDM_W   = 0;
                        double OutputTotalDM_N   = 0;
                        double OutputTotalDM_T   = 0;
                        double OutputTotalDM_WN  = 0;
                        double OutputTotalDM_WT  = 0;
                        double OutputTotalDM_NT  = 0;
                        double OutputTotalDM_WNT = 0;

                        /// Behnam (2016.07.13): The runOld.RunOptionDef.UseActualBase was previously used. Pierre wanted it to be deleted.
                        /// At one stage, we decided to use Potential conditions as the base run. Now it is not working anymore.

                        if (true)
                        {
                            ///<Use actual conditions as the base run>
                            if (InteractionsW)
                            {
                                OutputTotalDM_W = RunUnlimited(currentUniverse, true, false, false);
                            }
                            if (InteractionsN)
                            {
                                OutputTotalDM_N = RunUnlimited(currentUniverse, false, true, false);
                            }
                            if (InteractionsT)
                            {
                                OutputTotalDM_T = RunUnlimited(currentUniverse, false, false, true);
                            }
                            if (InteractionsWN)
                            {
                                OutputTotalDM_WN = RunUnlimited(currentUniverse, true, true, false);
                            }
                            if (InteractionsWT)
                            {
                                OutputTotalDM_WT = RunUnlimited(currentUniverse, true, false, true);
                            }
                            if (InteractionsNT)
                            {
                                OutputTotalDM_NT = RunUnlimited(currentUniverse, false, true, true);
                            }
                            if (InteractionsWNT)
                            {
                                OutputTotalDM_WNT = RunUnlimited(currentUniverse, true, true, true);
                            }

                            currentUniverse.isUnlimitedWater       = false;
                            currentUniverse.isUnlimitedNitrogen    = false;
                            currentUniverse.isUnlimitedTemperature = false;

                            currentUniverse.Crop_.areRootsToBeGrown = true;

                            if (initSoilAfterSowing)
                            {
                                currentUniverse.Soil_.Init(minTempInitSoilAfterSowing, maxTempInitSoilAfterSowing, meanTempInitSoilAfterSowing, false);
                                currentUniverse.ShootTemperature_.MinShootTemperature  = 0;
                                currentUniverse.ShootTemperature_.MaxShootTemperature  = 0;
                                currentUniverse.ShootTemperature_.MeanShootTemperature = 0;
                                currentUniverse.CumAirTempFromSowing       = 0.0;
                                currentUniverse.CumMaxCanopyTempFromSowing = 0.0;
                                currentUniverse.CumMaxAirTempFromSowing    = 0.0;
                                currentUniverse.PrevAppliedStagesN         = 1;
                                currentUniverse.PrevAppliedStagesIrr       = 1;
                                //currentUniverse.NFertChange = 1;
                                currentUniverse.CalcChangeinNFertilisation();


                                initSoilAfterSowing = false;
                            }
                            currentUniverse.RunDayStep();
                        }
                        else
                        {
                            ///<Use non-stressed conditions as the base run>
                            if (InteractionsW)
                            {
                                OutputTotalDM_W = RunUnlimited(currentUniverse, false, true, true);
                            }
                            if (InteractionsN)
                            {
                                OutputTotalDM_N = RunUnlimited(currentUniverse, true, false, true);
                            }
                            if (InteractionsT)
                            {
                                OutputTotalDM_T = RunUnlimited(currentUniverse, true, true, false);
                            }
                            if (InteractionsWN)
                            {
                                OutputTotalDM_WN = RunUnlimited(currentUniverse, false, false, true);
                            }
                            if (InteractionsWT)
                            {
                                OutputTotalDM_WT = RunUnlimited(currentUniverse, false, true, false);
                            }
                            if (InteractionsNT)
                            {
                                OutputTotalDM_NT = RunUnlimited(currentUniverse, true, false, false);
                            }
                            if (InteractionsWNT)
                            {
                                OutputTotalDM_WNT = RunUnlimited(currentUniverse, false, false, false);
                            }

                            currentUniverse.isUnlimitedWater        = true;
                            currentUniverse.isUnlimitedNitrogen     = true;
                            currentUniverse.isUnlimitedTemperature  = true;
                            currentUniverse.Crop_.areRootsToBeGrown = true;
                            if (initSoilAfterSowing)
                            {
                                currentUniverse.Soil_.Init(minTempInitSoilAfterSowing, maxTempInitSoilAfterSowing, meanTempInitSoilAfterSowing, false);
                                currentUniverse.ShootTemperature_.MinShootTemperature  = 0;
                                currentUniverse.ShootTemperature_.MaxShootTemperature  = 0;
                                currentUniverse.ShootTemperature_.MeanShootTemperature = 0;
                                currentUniverse.CumAirTempFromSowing       = 0.0;
                                currentUniverse.CumMaxCanopyTempFromSowing = 0.0;
                                currentUniverse.CumMaxAirTempFromSowing    = 0.0;
                                currentUniverse.PrevAppliedStagesN         = 1;
                                currentUniverse.PrevAppliedStagesIrr       = 1;
                                //currentUniverse.NFertChange = 1;
                                currentUniverse.CalcChangeinNFertilisation();
                            }
                            currentUniverse.RunDayStep();
                        }


                        currentUniverse.Crop_.OutputTotalDM_W   = OutputTotalDM_W;
                        currentUniverse.Crop_.OutputTotalDM_N   = OutputTotalDM_N;
                        currentUniverse.Crop_.OutputTotalDM_T   = OutputTotalDM_T;
                        currentUniverse.Crop_.OutputTotalDM_WN  = OutputTotalDM_WN;
                        currentUniverse.Crop_.OutputTotalDM_WT  = OutputTotalDM_WT;
                        currentUniverse.Crop_.OutputTotalDM_NT  = OutputTotalDM_NT;
                        currentUniverse.Crop_.OutputTotalDM_WNT = OutputTotalDM_WNT;
                        ///</Parallel runs>
                    }
                    else
                    {
                        ///<Normal run>
                        currentUniverse.isUnlimitedWater        = oldLimitedWater;
                        currentUniverse.isUnlimitedNitrogen     = oldLimitedNitrogen;
                        currentUniverse.isUnlimitedTemperature  = oldLimitedTemperature;
                        currentUniverse.Crop_.areRootsToBeGrown = true;
                        if (initSoilAfterSowing)
                        {
                            currentUniverse.Soil_.Init(minTempInitSoilAfterSowing, maxTempInitSoilAfterSowing, meanTempInitSoilAfterSowing, false);
                            currentUniverse.ShootTemperature_.MinShootTemperature  = 0;
                            currentUniverse.ShootTemperature_.MaxShootTemperature  = 0;
                            currentUniverse.ShootTemperature_.MeanShootTemperature = 0;
                            currentUniverse.CumAirTempFromSowing       = 0.0;
                            currentUniverse.CumMaxCanopyTempFromSowing = 0.0;
                            currentUniverse.CumMaxAirTempFromSowing    = 0.0;
                            currentUniverse.PrevAppliedStagesN         = 1;
                            currentUniverse.PrevAppliedStagesIrr       = 1;
                            //currentUniverse.NFertChange = 1;
                            currentUniverse.CalcChangeinNFertilisation();



                            initSoilAfterSowing = false;
                        }
                        currentUniverse.RunDayStep();
                        ///</Normal run>
                    }
                }
                else

                {
                    ///<Comment>Non-stressed conditions are only applied after sowing</Comment>
                    currentUniverse.isUnlimitedWater        = false;
                    currentUniverse.isUnlimitedNitrogen     = false;
                    currentUniverse.isUnlimitedTemperature  = false;
                    currentUniverse.Crop_.areRootsToBeGrown = false;
                    currentUniverse.RunDayStep();
                }


                if (IsSowDateEstimate)
                {
                    // Checking sowing conditions:

                    ///<Skip days>
                    numdSkipDays += 1;
                    flagSkipDays  = (numdSkipDays <= SkipDays);
                    ///</Skip days>

                    flagMaxDate  = true;
                    flagSoilMois = true;
                    flagCumPcp   = true;
                    flagSoilTemp = true;
                    flagFreezing = true;
                    flagWorkabil = true;

                    if (!flagSkipDays)
                    {
                        if (management.DoRelax)
                        {
                            ///<Relaxation>
                            ///<Comment>The criteria are relaxed here using four exponential curves, if DoRelax=TRUE</Comment>
                            var n = numdSkipDays - SkipDays - 1;
                            TAveThr       = ExpoDecrease(TAveThr, TAveThrRelax, origTAveThr, n, poTAveThr);
                            TMinThr       = ExpoDecrease(TMinThr, TMinThrRelax, origTMinThr, n, poTMinThr);
                            SoilMoistThr  = ExpoDecrease(SoilMoistThr, SoilMoistThrRelax, origSoilMoistThr, n, poSoilMoistThr);
                            CumPcpThr     = ExpoDecrease(CumPcpThr, CumPcpThrRelax, origCumPcpThr, n, poCumPcpThr);
                            SoilWorkabThr = ExpoIncrease(SoilWorkabThr, SoilWorkabThrRelax, origSoilWorkabThr, n, poSoilWorkabThr);
                            ///</Relaxation>
                        }

                        ///<Average daily air temperature temperature>
                        numdSoilTemp = 0;
                        for (var i = 1; i <= CheckDaysTemp; ++i)
                        {
                            if (currentUniverse.Weather_.MeanTemp(currentUniverse.CurrentDate.AddDays(i)) >= TAveThr)
                            {
                                numdSoilTemp += 1;
                            }
                        }
                        flagSoilTemp = (numdSoilTemp < CheckDaysTemp);
                        ///</Average daily air temperature temperature>

                        ///<Minimum daily air temperature (frost risk)>
                        numdFreezing = 0;
                        for (var i = 1; i <= CheckDaysTemp; ++i)
                        {
                            if (currentUniverse.Weather_.MinTemp(currentUniverse.CurrentDate.AddDays(i)) >= TMinThr)
                            {
                                numdFreezing += 1;
                            }
                        }
                        flagFreezing = (numdFreezing < CheckDaysTemp);
                        ///</Minimum daily air temperature (frost risk)>

                        ///<Cumulative precipitation>
                        numdPcp = 0;
                        for (var i = 1; i <= CheckDaysPcp; ++i)
                        {
                            numdPcp += currentUniverse.Weather_.Rain(currentUniverse.CurrentDate.AddDays(i)) / MMwaterToGwater;
                        }
                        flagCumPcp = (numdPcp < CumPcpThr);
                        ///</Cumulative precipitation>

                        ///<Soil moisture>
                        if (currentUniverse.Soil_.Layers[checkLay].AvWater < SoilMoistThr * currentUniverse.Soil_.Layers[checkLay].MaxAvWater)
                        {
                            numdSoilMois = 0;
                        }
                        if (currentUniverse.Soil_.Layers[checkLay].AvWater >= SoilMoistThr * currentUniverse.Soil_.Layers[checkLay].MaxAvWater)
                        {
                            numdSoilMois += 1;
                        }
                        flagSoilMois = (numdSoilMois == 0);
                        ///</Soil moisture>

                        ///<Soil compaction (workability)>
                        flagWorkabil = ((currentUniverse.Soil_.Layers[checkLay].AvWater +
                                         currentUniverse.Soil_.Layers[checkLay].ExWater) / currentUniverse.Soil_.Layers[checkLay].FcWater
                                        > SoilWorkabThr);
                        ///</Soil compaction (workability)>
                    }

                    ///<Sowing window>
                    flagMaxDate = (currentUniverse.CurrentDate < MaxSowDate.AddDays(-1));
                    ///</Sowing window>

                    flagReSow = flagMaxDate & (flagSkipDays || flagSoilMois || flagCumPcp ||
                                               flagSoilTemp || flagFreezing || flagWorkabil);
                }

                if (IsSowDateEstimate) // If sowing date search is ON, at least one day before sowing must be simulated.
                {
                    SowingDate = currentUniverse.CurrentDate.AddDays(1);
                    currentUniverse.Crop_.Dispose();
                    currentUniverse.Crop_ = new CropModel.Crop(currentUniverse);

                    //Debug

                    //currentUniverse.CumMaxCanopyTempFromSowing = 0.0;
                    //??currentUniverse.Crop_.RootLength = 0.0;
                    //??currentUniverse.Crop_.Tau = 1.0;
                    //??currentUniverse.Crop_.SumInternodesLength = 0.0;
                    //??currentUniverse.Crop_.PotentialWaterOnLeaves = 0.0;
                    //??currentUniverse.Crop_.RootLength = 0.0;
                    //currentUniverse.Crop_.LeafNumber = 0.0;
                    //currentUniverse.Crop_.Ntip = 0.0;

                    /*currentUniverse.ShootTemperature_.MinShootTemperature=0.0;
                     * currentUniverse.ShootTemperature_.MaxShootTemperature=0.0;
                     * //currentUniverse.Soil_.Init(currentUniverse.Weather_.MinTemp(currentUniverse.CurrentDate/*.AddDays(1)*//*)/*, currentUniverse.Weather_.MaxTemp(currentUniverse.CurrentDate/*.AddDays(1)*//*), (currentUniverse.Weather_.MinTemp(currentUniverse.CurrentDate/*.AddDays(1)*//*) + currentUniverse.Weather_.MaxTemp(currentUniverse.CurrentDate/*.AddDays(1)*//*))/2, false);*/
                    //currentUniverse.Soil_.energyBalanceBiomaWrapper_.Init(false);
                    //Debug /**/
                    //currentUniverse.Soil_.MaximumCanopyTemperature = currentUniverse.Weather_.MaxTemp(currentUniverse.CurrentDate/*.AddDays(1)*/);//??
                    //currentUniverse.Soil_.MinimumCanopyTemperature = currentUniverse.Weather_.MinTemp(currentUniverse.CurrentDate/*.AddDays(1)*/);//??
                    //currentUniverse.Soil_.SoilMinTemperature = currentUniverse.Weather_.MinTemp(currentUniverse.CurrentDate/*.AddDays(1)*/);//??
                    //currentUniverse.Soil_.SoilMaxTemperature = currentUniverse.Weather_.MaxTemp(currentUniverse.CurrentDate/*.AddDays(1)*/);//??;
                    //currentUniverse.ShootTemperature_.MinShootTemperature = 0;
                    //currentUniverse.ShootTemperature_.MaxShootTemperature = 0;
                    //currentUniverse.ShootTemperature_.MeanShootTemperature = 0;
                    //currentUniverse.Crop_.Universe_.thermalTimeWrapper_.Init();
                    initSoilAfterSowing        = true;
                    minTempInitSoilAfterSowing = currentUniverse.Weather_.MinTemp(currentUniverse.CurrentDate /*.AddDays(1)*/);
                    maxTempInitSoilAfterSowing = currentUniverse.Weather_.MaxTemp(currentUniverse.CurrentDate /*.AddDays(1)*/);
                    // meanTempInitSoilAfterSowing = (currentUniverse.Weather_.MinTemp(currentUniverse.CurrentDate/*.AddDays(1)*/) + currentUniverse.Weather_.MaxTemp(currentUniverse.CurrentDate/*.AddDays(1)*/)) / 2;


                    //Debug /**/
                    currentUniverse.Crop_.Universe_.thermalTimeWrapper_.Init();

                    currentUniverse.Crop_.Init(currentUniverse.thermalTimeWrapper_.CumulTT, currentUniverse.CurrentDate.AddDays(1));
                    currentUniverse.CurrentDate = currentUniverse.CurrentDate.AddDays(1);

                    meanTempInitSoilAfterSowing = currentUniverse.Weather_.GetMeanTemperatureBeforeSowing(SowingDate);
                }



                if (IsSowDateEstimate & flagReSow) // At least one of the sowing criteria is not met.
                {
                    IsSowDateEstimate = true;      // Sowing date search continues;
                    SaveCurrentUniverse();
                }
                else if (IsSowDateEstimate & !flagReSow) // All of the sowing criteria are met.
                {
                    IsSowDateEstimate = false;           // Sowing date search ends;
                    currentUniverse.IsSowDateEstimate = false;
                    management.FinalSowingDate        = SowingDate;
                    currentUniverse.CalcChangeinNFertilisation();
                    SaveCurrentUniverse();
                }
                else if (!IsSowDateEstimate) // Sowing date search is OFF or all of the sowing criteria are met.
                {
                    SaveCurrentUniverse();
                    currentUniverse.CurrentDate = currentUniverse.CurrentDate.AddDays(1);
                }
            }
        }
예제 #9
0
        void RunJob(object sender, DoWorkEventArgs e)
        {
            DirectoryInfo folderInfo = null;

            try
            {
                if (exit)
                {
                    return;
                }

                folderInfo = new DirectoryInfo(FolderPath);

                saveFileDialog1.Title        = @"Select 'Folder run' summary file location";
                saveFileDialog1.AddExtension = true;

                outputFilePath = null;
                InvokeDelegate selectOutputPath = () =>
                {
                    saveFileDialog1.FileName = FolderPath + "\\" + folderInfo.Name + ".sqfro";
                    if (saveFileDialog1.ShowDialog() != DialogResult.OK)
                    {
                        outputFilePath = null;
                    }
                    else
                    {
                        outputFilePath = saveFileDialog1.FileName;
                    }
                };
                Invoke(selectOutputPath);

                if (outputFilePath == null)
                {
                    return;
                }


                var updateDelegate = new InvokeDelegate(UpdateStatus);
                var stopWatch      = new Stopwatch();
                stopWatch.Start();
                Action <bool, Func <string>, Func <int?> > updateStatus = (f, s, p) =>
                {
                    if (f || stopWatch.ElapsedMilliseconds > 750)
                    {
                        stopWatch.Reset();
                        stopWatch.Start();
                        status = (permanentStatus ?? "") + (s != null ? s() : null);
                        beginInvoke(updateDelegate);
                        var percent = p != null?p() : null;

                        if (percent.HasValue)
                        {
                            backgroundWorker1.ReportProgress(percent.Value);
                        }
                        else
                        {
                            backgroundWorker1.ReportProgress(0);
                        }
                    }
                };
                var loadDelegate = new InvokeDelegate(() =>
                {
                    var file = (IProjectItem)Serialization.DeserializeXml(fileTypeToLoad, fileToLoad);
                    file.ClearWarnings();
                    loadedItem = file;
                });
                Func <string, Type, IProjectItem> loadFile = (f, t) =>
                {
                    fileToLoad     = f;
                    fileTypeToLoad = t;
                    invoke(loadDelegate);
                    return(loadedItem);
                };

                permanentStatus = "Loading folder files...\n\n";
                updateStatus(true, () => null, () => 0);
                var files     = folderInfo.GetFiles("*", SearchOption.AllDirectories);
                var fileIndex = 0;
                var fileCount = files.Length;

                var managements = new List <Item <ManagementItem> >();
                var parameters  = new List <Item <CropParameterItem> >();
                var sites       = new List <Item <SiteItem> >();
                var soils       = new List <Item <SoilItem> >();
                var varieties   = new List <Item <CropParameterItem> >();

                foreach (var fileInfo in files)
                {
                    var info  = fileInfo;
                    var index = fileIndex;
                    if (backgroundWorker1.CancellationPending)
                    {
                        hasCancelled = true;
                        break;
                    }
                    var extension = fileInfo.Extension.ToLower();
                    switch (extension)
                    {
                    case ".sqman":
                        updateStatus(false, () => "Loading management file: '" + info.FullName + "'...", () => 100 * index / fileCount);
                        var managementFile = (ManagementFile)loadFile(fileInfo.FullName, typeof(ManagementFile));
                        managements.AddRange(managementFile.Items.Select(i => new Item <ManagementItem> {
                            SourceFile = info.FullName, Value = i
                        }));
                        break;

                    case ".sqpar":
                        updateStatus(false, () => "Loading non-varietal parameter file: '" + info.FullName + "'...", () => 100 * index / fileCount);
                        var nonVarietyFile = (NonVarietyFile)loadFile(fileInfo.FullName, typeof(NonVarietyFile));
                        parameters.AddRange(nonVarietyFile.Items.Select(i => new Item <CropParameterItem> {
                            SourceFile = info.FullName, Value = i
                        }));
                        break;

                    case ".sqsit":
                        updateStatus(false, () => "Loading site file: '" + info.FullName + "'...", () => 100 * index / fileCount);
                        var siteFile = (SiteFile)loadFile(fileInfo.FullName, typeof(SiteFile));
                        sites.AddRange(siteFile.Items.Select(i =>
                        {
                            foreach (var file in i.WeatherFiles)
                            {
                                file.File = Path.Combine(info.DirectoryName, file.File);
                            }
                            return(new Item <SiteItem> {
                                SourceFile = info.FullName, Value = i
                            });
                        }));
                        break;

                    case ".sqsoi":
                        updateStatus(false, () => "Loading soil file: '" + info.FullName + "'...", () => 100 * index / fileCount);
                        var soilFile = (SoilFile)loadFile(fileInfo.FullName, typeof(SoilFile));
                        soils.AddRange(soilFile.Items.Select(i => new Item <SoilItem> {
                            SourceFile = info.FullName, Value = i
                        }));
                        break;

                    case ".sqvar":
                        updateStatus(false, () => "Loading variety file: '" + info.FullName + "'...", () => 100 * index / fileCount);
                        var varietyFile = (VarietyFile)loadFile(fileInfo.FullName, typeof(VarietyFile));
                        varieties.AddRange(varietyFile.Items.Select(i => new Item <CropParameterItem> {
                            SourceFile = info.FullName, Value = i
                        }));
                        break;

                    default:
                        updateStatus(false, () => "Skipping file: '" + info.FullName + "'...", () => 100 * index / fileCount);
                        break;
                    }
                    ++fileIndex;
                }

                if (backgroundWorker1.CancellationPending)
                {
                    hasCancelled = true;
                    return;
                }

                var totalNumberOfCombinations = ((long)managements.Count) * ((long)parameters.Count) * ((long)sites.Count) * ((long)soils.Count) * ((long)varieties.Count);

                permanentStatus = string.Format("Found: {0} managements, {1} parameters, {2} sites, {3} soils, {4} varieties...\n{5} runs.\n\n",
                                                managements.Count, parameters.Count, sites.Count, soils.Count, varieties.Count, totalNumberOfCombinations);
                updateStatus(true, () => "", null);
                Thread.Sleep(totalNumberOfCombinations == 0 ? 3000 : 2000);
                if (totalNumberOfCombinations < 0)
                {
                    throw new OverflowException("Number of combination is greater than " + long.MaxValue + ". Can't proceed.");
                }
                if (totalNumberOfCombinations == 0)
                {
                    result = "0 / 0 runs processed.";
                    return;
                }

                var run        = new Run();
                var runOptions = new RunOptionItem("FolderRun")
                {
                    UseObservedGrainNumber = checkBoxGrainNumber.Checked,
                    UnlimitedNitrogen      = checkBoxLimitNitrogen.Checked,
                    UnlimitedWater         = checkBoxLimitWater.Checked,
                };
                var combinationIndex = 0L;
                using (var outputFile = new StreamWriter(outputFilePath))
                {
                    WriteVersionDate(outputFile);
                    outputFile.WriteLine();
                    outputFile.WriteLine();
                    WriteColumnHeaders(outputFile);

                    foreach (var combination in CartesianProduct(totalNumberOfCombinations, managements, parameters, sites, soils, varieties))
                    {
                        var c     = combination;
                        var index = combinationIndex;
                        updateStatus(false, () => string.Format("Processing #{5}: {0}, {1}, {2}, {3}, {4}...",
                                                                c.Management.Value.Name, c.Parameter.Value.Name, c.Site.Value.Name, c.Soil.Value.Name, c.Variety.Value.Name, index),
                                     () => (int)(100 * (index / totalNumberOfCombinations)));

                        try
                        {
                            run.Start(c.Variety.Value, c.Soil.Value, c.Site.Value, c.Management.Value, c.Parameter.Value, runOptions);
                            WriteColumnValues(outputFile, combination, run);
                        }
                        catch (Exception runningException)
                        {
                            errors.Add(new Error {
                                Exception = runningException, Combination = combination
                            });
                        }

                        ++combinationIndex;

                        if (backgroundWorker1.CancellationPending)
                        {
                            hasCancelled = true;
                            break;
                        }
                    }
                }
                result = combinationIndex + " / " + totalNumberOfCombinations + " runs processed.";
            }
            catch (Exception exception)
            {
                if (folderInfo == null)
                {
                    exception = new Exception(@"Invalid folder: '" + FolderPath + @"'.");
                }
                errors.Insert(0, new Error {
                    Exception = exception
                });
            }
            finally
            {
                if (!exit)
                {
                    beginInvoke(JobEnd);
                }
            }
        }
예제 #10
0
        private bool Increment(int stepIndex, ManagementItem mi, CropParameterItem pi, RunOptionItem roi, SiteItem sii, SoilItem soi, CropParameterItem vi)
        {
            if (oneByOne)
            {
                var sensitivityRunCount = SensitivityRuns.Count;
                var found = false;
                var i     = 0;
                while (!found && i < sensitivityRunCount)
                {
                    var sensitivityRun       = SensitivityRuns[i];
                    var sensitivityRunNbStep = sensitivityRun.NbStep;
                    if (stepIndex < sensitivityRunNbStep)
                    {
                        sensitivityRun.SetStep(stepIndex, mi, pi, roi, sii, soi, vi);
                        found = true;
                    }
                    else
                    {
                        if (stepIndex == sensitivityRunNbStep)
                        {
                            sensitivityRun.SetValue(mi, pi, roi, sii, soi, vi, sensitivityRun.InitialValue);
                        }
                        stepIndex -= sensitivityRunNbStep;
                    }
                    ++i;
                }
                return(!found);
            }
            else
            {
                var end = true;
                var i   = SensitivityRuns.Count - 1;

                while (i >= 0 && end)
                {
                    var sensitivityRun     = SensitivityRuns[i];
                    var sensitivityRunStep = sensitivityRun.Step;
                    if (sensitivityRunStep == sensitivityRun.NbStep - 1)
                    {
                        sensitivityRun.SetStep(0, mi, pi, roi, sii, soi, vi);
                    }
                    else
                    {
                        sensitivityRun.SetStep(sensitivityRunStep + 1, mi, pi, roi, sii, soi, vi);
                        end = false;
                    }
                    --i;
                }
                return(end);
            }
        }
예제 #11
0
        public override void StepRun(bool serialize, int i, string variety = null, string parameterName = null, double parameterValue = 0)
        {
            BindingList <MultiRunItem> multiRuns = RunItem.Multi.MultiRuns;
            var multiYear = RunItem.Multi.MultiYear;

            #region get items

            string miName, piName, riName, roiName, siiName, soiName, viName, exName;

            if (multiRuns.Count > 0)
            {
                var item = multiRuns[i];
                miName  = item.ManagementItemSelected;
                piName  = item.ParameterItemSelected;
                riName  = RunItem.Name;
                roiName = item.RunOptionItemSelected;
                siiName = item.SiteItemSelected;
                soiName = item.SoilItemSelected;
                viName  = item.VarietyItemSelected;
                exName  = item.ExperimentSelected;
            }
            else
            {
                miName  = RunItem.Normal.ManagementItem;
                piName  = RunItem.Normal.ParameterItem;
                riName  = RunItem.Name;
                roiName = RunItem.Normal.RunOptionItem;
                siiName = RunItem.Normal.SiteItem;
                soiName = RunItem.Normal.SoilItem;
                viName  = RunItem.Normal.VarietyItem;
                exName  = RunItem.Normal.ExperimentItem;
            }

            ManagementItem    mi  = null;
            CropParameterItem pi  = null;
            RunOptionItem     roi = null;
            SiteItem          sii = null;
            SoilItem          soi = null;
            CropParameterItem vi  = null;
            RunCore.GetItems(riName, miName, piName, roiName, siiName, soiName, viName, ref mi, ref pi, ref roi, ref sii, ref soi, ref vi);

            mi  = mi.Clone();
            pi  = pi.Clone();
            roi = roi.Clone();
            sii = sii.Clone();
            soi = soi.Clone();
            vi  = vi.Clone();

            #endregion

            ///<Behnam>
            var deltaHeader = new string[SensitivityRuns.Count];
            var index1      = 0;

            if (oneByOne)
            {
                nbSensitivityStep = 1;
                SensitivityRuns.Iterate(
                    delegate(SensitivityRunItem item)
                {
                    nbSensitivityStep    += item.NbStep;
                    deltaHeader[index1++] = item.GetHeader();
                });
            }
            else
            {
                nbSensitivityStep = 1;
                SensitivityRuns.Iterate(
                    delegate(SensitivityRunItem item)
                {
                    nbSensitivityStep    *= item.NbStep;
                    deltaHeader[index1++] = item.GetHeader();
                });
            }
            ///</Behnam>

            var   deltaValue = new double[SensitivityRuns.Count];
            int[] index      = { 0 };

            if (!multiYear)
            {
                ///<Behnam>
                switch (roi.OutputPattern)
                {
                case "V13": ProjectFile.OutputVersion = OutputVersion.V13; break;

                case "V15": ProjectFile.OutputVersion = OutputVersion.V15; break;

                case "Cus": ProjectFile.OutputVersion = OutputVersion.Cus; break;

                case "Maize": ProjectFile.OutputVersion = OutputVersion.Maize; break;
                }
                ///</Behnam>

                var yy = sii.MaxSowingDate.Year - sii.MinSowingDate.Year;
                mi.SowingDate     = new DateTime(mi.SowingDate.Year, mi.SowingDate.Month, mi.SowingDate.Day);
                sii.MinSowingDate = new DateTime(mi.SowingDate.Year, sii.MinSowingDate.Month, sii.MinSowingDate.Day);
                sii.MaxSowingDate = new DateTime(mi.SowingDate.Year + yy, sii.MaxSowingDate.Month, sii.MaxSowingDate.Day);

                Run.isFirstYear = true;
                ///</Behnam>

                var end = false;
                InitStepSensitivity(mi, pi, roi, sii, soi, vi, deltaValue, index);

                var stepIndex = 0;
                while (!end)
                {
                    var excelPage        = RunCore.Run(riName, exportNormalRuns, false, mi, pi, roi, sii, soi, vi);
                    var deltaSensitivity = "";

                    index[0] = 0;
                    SensitivityRuns.Iterate(
                        item =>
                    {
                        deltaValue[index[0]] = item.GetValue(mi, pi, roi, sii, soi, vi);
                        deltaSensitivity    += item.GetHeader() + "_" + Math.Round(deltaValue[index[0]], 4) + "_";
                        ++index[0];
                    });

                    ///<Behnam>
                    if (i == 0 && stepIndex == 0)
                    {
                        Book.Clear();
                        var outputFile = OutputFile.ExtractSensitivityRunHeader(deltaHeader);
                        outputFile.Title = OutputFileName;
                        Book.Add(outputFile);
                    }

                    if (exportNormalRuns)
                    {
                        var dailyOutputFileName = OutputPatternVarDef.OutputPatternValue(dailyOutputPattern, miName, piName, riName, roiName, siiName, soiName, viName, exName) + RunItem.Normal.OutputExtention;
                        dailyOutputFileName = dailyOutputFileName.Replace(VarDeltaSensitivity, deltaSensitivity);
                        dailyOutputFileName = dailyOutputFileName.Replace(RunItemModeMulti.VarMultiYearSowingYear, "");
                        excelPage.Title     = dailyOutputFileName;
                        Book.Add(excelPage);
                        if (serialize)
                        {
                            RunCore.Save(excelPage, AbsoluteOutputDirectory + "\\" + dailyOutputFileName);
                        }
                    }

                    if (i == 0 && ProjectFile.OutputVersion == OutputVersion.Cus && stepIndex == 0)
                    {
                        Run.SecondLine = false;
                        Book[0].Add(OutputFile.ExtractSensitivityRunLine(RunCore.RunInstance, deltaHeader, deltaValue));
                    }
                    Book[0].Add(OutputFile.ExtractSensitivityRunLine(RunCore.RunInstance, deltaHeader, deltaValue));
                    ///</Behnam>

                    end = Increment(stepIndex, mi, pi, roi, sii, soi, vi);
                    ++stepIndex;
                }
            }
            else
            {
                ///<Behnam>
                switch (roi.OutputPattern)
                {
                case "V13": ProjectFile.OutputVersion = OutputVersion.V13; break;

                case "V15": ProjectFile.OutputVersion = OutputVersion.V15; break;

                case "Cus": ProjectFile.OutputVersion = OutputVersion.Cus; break;

                case "Maize": ProjectFile.OutputVersion = OutputVersion.Maize; break;
                }
                ///</Behnam>

                var firstYear = RunItem.Multi.FirstYear;
                var lastYear  = RunItem.Multi.LastYear;

                for (var j = firstYear; j <= lastYear; ++j)
                {
                    foreach (var dateApp in mi.DateApplications)
                    {
                        dateApp.Date = new DateTime(j + (dateApp.Date.Year - mi.SowingDate.Year), dateApp.Date.Month, dateApp.Date.Day);
                    }

                    ///<Behnam>
                    var yy = sii.MaxSowingDate.Year - sii.MinSowingDate.Year;
                    mi.SowingDate     = new DateTime(j, mi.SowingDate.Month, mi.SowingDate.Day);
                    sii.MinSowingDate = new DateTime(j, sii.MinSowingDate.Month, sii.MinSowingDate.Day);
                    sii.MaxSowingDate = new DateTime(j + yy, sii.MaxSowingDate.Month, sii.MaxSowingDate.Day);

                    Run.isFirstYear = (j == firstYear);
                    ///</Behnam>

                    var end = false;
                    InitStepSensitivity(mi, pi, roi, sii, soi, vi, deltaValue, index);

                    var stepIndex = 0;

                    while (!end)
                    {
                        var excelPage        = RunCore.Run(riName, exportNormalRuns, false, mi, pi, roi, sii, soi, vi);
                        var deltaSensitivity = "";

                        index[0] = 0;
                        var index0 = index[0];
                        SensitivityRuns.Iterate(
                            delegate(SensitivityRunItem item)
                        {
                            deltaValue[index0] = item.GetValue(mi, pi, roi, sii, soi, vi);
                            deltaSensitivity  += item.GetHeader() + "_" + Math.Round(deltaValue[index[0]], 4) + "_";
                            ++index0;
                        });

                        ///<Behnam (2016.11.12)>
                        if (i == 0 && j == firstYear && stepIndex == 0)
                        {
                            Book.Clear();
                            var outputFile = OutputFile.ExtractSensitivityRunHeader(deltaHeader);
                            outputFile.Title = OutputFileName;
                            Book.Add(outputFile);
                        }

                        if (exportNormalRuns)
                        {
                            var dailyOutputFileName = OutputPatternVarDef.OutputPatternValue(dailyOutputPattern, miName, piName, riName, roiName, siiName, soiName, viName, exName) + RunItem.Normal.OutputExtention;
                            dailyOutputFileName = dailyOutputFileName.Replace(VarDeltaSensitivity, deltaSensitivity);
                            dailyOutputFileName = dailyOutputFileName.Replace(RunItemModeMulti.VarMultiYearSowingYear, mi.FinalSowingDate.Year.ToString());
                            excelPage.Title     = dailyOutputFileName;
                            Book.Add(excelPage);

                            if ((j == firstYear || (j != firstYear && oldDailyOutputFileName != dailyOutputFileName)) && stepIndex == 0)
                            {
                                if (serialize)
                                {
                                    RunCore.Save(excelPage, AbsoluteOutputDirectory + "\\" + dailyOutputFileName, true);
                                }
                            }
                            else
                            {
                                if (serialize)
                                {
                                    RunCore.Save(excelPage, AbsoluteOutputDirectory + "\\" + dailyOutputFileName, false);
                                }
                            }
                            oldDailyOutputFileName = dailyOutputFileName;
                        }

                        if (i == 0 && j == firstYear && ProjectFile.OutputVersion == OutputVersion.Cus && stepIndex == 0)
                        {
                            Run.SecondLine = false;
                            Book[0].Add(OutputFile.ExtractSensitivityRunLine(RunCore.RunInstance, deltaHeader, deltaValue));
                        }
                        Book[0].Add(OutputFile.ExtractSensitivityRunLine(RunCore.RunInstance, deltaHeader, deltaValue));
                        ///</Behnam>

                        end = Increment(stepIndex, mi, pi, roi, sii, soi, vi);
                        ++stepIndex;
                    }
                }
            }
        }
예제 #12
0
        public override int InitRun(bool serialize)
        {
            ///<Behnam 92015.12.08)>
            #region get items
            string miName, piName, riName, roiName, siiName, soiName, viName, exName;
            BindingList <MultiRunItem> multiRuns = RunItem.Multi.MultiRuns;
            var multiYear = RunItem.Multi.MultiYear;

            if (multiRuns.Count > 0)
            {
                var item = multiRuns[0];
                miName  = item.ManagementItemSelected;
                piName  = item.ParameterItemSelected;
                riName  = RunItem.Name;
                roiName = item.RunOptionItemSelected;
                siiName = item.SiteItemSelected;
                soiName = item.SoilItemSelected;
                viName  = item.VarietyItemSelected;
                exName  = item.ExperimentSelected;
            }
            else
            {
                miName  = RunItem.Normal.ManagementItem;
                piName  = RunItem.Normal.ParameterItem;
                riName  = RunItem.Name;
                roiName = RunItem.Normal.RunOptionItem;
                siiName = RunItem.Normal.SiteItem;
                soiName = RunItem.Normal.SoilItem;
                viName  = RunItem.Normal.VarietyItem;
                exName  = RunItem.Normal.ExperimentItem;
            }

            ManagementItem    mi  = null;
            CropParameterItem pi  = null;
            RunOptionItem     roi = null;
            SiteItem          sii = null;
            SoilItem          soi = null;
            CropParameterItem vi  = null;
            RunCore.GetItems(riName, miName, piName, roiName, siiName, soiName, viName, ref mi, ref pi, ref roi, ref sii, ref soi, ref vi);

            mi  = mi.Clone();
            pi  = pi.Clone();
            roi = roi.Clone();
            sii = sii.Clone();
            soi = soi.Clone();
            vi  = vi.Clone();

            switch (roi.OutputPattern)
            {
            case "V13": ProjectFile.OutputVersion = OutputVersion.V13; break;

            case "V15": ProjectFile.OutputVersion = OutputVersion.V15; break;

            case "Cus": ProjectFile.OutputVersion = OutputVersion.Cus; break;

            case "Maize": ProjectFile.OutputVersion = OutputVersion.Maize; break;
            }
            #endregion
            ///</Behnam>

            if (RunItem.Multi.MultiYear && RunItem.Multi.FirstYear > RunItem.Multi.LastYear)
            {
                throw new RunException(RunItem.Name, "First year (" + RunItem.Multi.FirstYear + ") must be <= to last year (" + RunItem.Multi.LastYear + ")");
            }

            var deltaHeader = new string[SensitivityRuns.Count];
            var index       = 0;

            if (oneByOne)
            {
                nbSensitivityStep = 1;
                SensitivityRuns.Iterate(
                    delegate(SensitivityRunItem item)
                {
                    nbSensitivityStep   += item.NbStep;
                    deltaHeader[index++] = item.GetHeader();
                });
            }
            else
            {
                nbSensitivityStep = 1;
                SensitivityRuns.Iterate(
                    delegate(SensitivityRunItem item)
                {
                    nbSensitivityStep   *= item.NbStep;
                    deltaHeader[index++] = item.GetHeader();
                });
            }

            if (Book != null)
            {
                Book.Clear();
            }
            else
            {
                Book = new Book();
            }
            var page = OutputFile.ExtractSensitivityRunHeader(deltaHeader);
            page.Title = OutputFileName;
            Book.Add(page);
            return(Math.Max(1, RunItem.Multi.MultiRuns.Count));
        }