예제 #1
0
        public StudentEditViewModel(string connectionString, int id)
        {
            _connectionString = connectionString;

            allExercises = GetAllExercises().Select(exercise => new SelectListItem()
            {
                Text     = exercise.exerciseName,
                Value    = exercise.Id.ToString(),
                Selected = student.exerciseList.Find(assignedExercise => assignedExercise.Id == exercise.Id) != null
            })
                           .ToList();

            Cohorts = GetAllCohorts()
                      .Select(cohort => new SelectListItem()
            {
                Text  = cohort.cohortName,
                Value = cohort.Id.ToString()
            })
                      .ToList();

            Cohorts.Insert(0, new SelectListItem
            {
                Text  = "Choose a cohort",
                Value = "0"
            });

            allExercises.Insert(0, new SelectListItem
            {
                Text  = "Assign an exercise",
                Value = "0"
            });
        }
예제 #2
0
        public StudentEditViewModel(string connectionString)
        {
            _connectionString = connectionString;

            //student = StudentRepository.GetOneStudent(studentId);

            // Get the exercises that are currently assigned to this student
            // The student model already has a list for this!
            Student.StudentExs = GetAssignedExercisesByStudent(studentId);

            allExercises = ExerciseRepository.GetAllExercises()
                           .Select(singleExercise => new SelectListItem()
            {
                Text     = singleExercise.Name,
                Value    = singleExercise.id.ToString(),
                Selected = Student.StudentExs.Find(assignedExercise => assignedExercise.id == singleExercise.id) != null
            })
                           .ToList();

            //Query the database to get all cohorts
            Cohorts = GetAllCohorts()
                      .Select(cohort => new SelectListItem()
            {
                Text  = cohort.CohortName,
                Value = cohort.CohortId.ToString()
            })
                      .ToList();

            // Add an option with instructions for how to use the dropdown
            Cohorts.Insert(0, new SelectListItem
            {
                Text  = "Choose a cohort",
                Value = "0"
            });
        }
예제 #3
0
        private void AddChildren(ExtractionConfiguration extractionConfiguration, DescendancyList descendancy)
        {
            HashSet <object> children = new HashSet <object>();

            var parameters = AllGlobalExtractionFilterParameters.Where(p => p.ExtractionConfiguration_ID == extractionConfiguration.ID)
                             .ToArray();

            if (parameters.Any())
            {
                var parameterNode = new ParametersNode(extractionConfiguration, parameters);
                children.Add(parameterNode);
            }

            //if it has a cohort
            if (extractionConfiguration.Cohort_ID != null)
            {
                var cohort = Cohorts.Single(c => c.ID == extractionConfiguration.Cohort_ID);
                children.Add(new LinkedCohortNode(extractionConfiguration, cohort));
            }

            //if it has extractable datasets add those
            foreach (SelectedDataSets ds in GetDatasets(extractionConfiguration))
            {
                children.Add(ds);
                AddChildren(ds, descendancy.Add(ds));
            }

            AddToDictionaries(children, descendancy);
        }
예제 #4
0
 public void CalcCohorts(List <ChemExIcon> exIcons, Cohorts cohorts)
 {
     foreach (var exIcon in exIcons)
     {
         foreach (var pop in exIcon.Pops)
         {
             cohorts[pop.Key] += pop.Value;
         }
     }
 }
예제 #5
0
        private void AddChildren(ExternalCohortTable externalCohortTable, DescendancyList descendancy)
        {
            var cohorts = Cohorts.Where(c => c.ExternalCohortTable_ID == externalCohortTable.ID).ToArray();

            foreach (ExtractableCohort cohort in cohorts)
            {
                cohort.InjectKnown(externalCohortTable);
            }

            AddToDictionaries(new HashSet <object>(cohorts), descendancy);
        }
        public InstructorEditViewModel(string config)
        {
            _connectionString = config;

            /*
             *  Query the database to get all cohorts
             */

            using (SqlConnection conn = Connection)
            {
                conn.Open();
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = "SELECT Id, CohortName FROM Cohort";
                    SqlDataReader reader = cmd.ExecuteReader();

                    List <Cohort> cohorts = new List <Cohort>();
                    while (reader.Read())
                    {
                        cohorts.Add(new Cohort
                        {
                            Id         = reader.GetInt32(reader.GetOrdinal("Id")),
                            CohortName = reader.GetString(reader.GetOrdinal("CohortName")),
                        });
                    }



                    Cohorts = cohorts.Select(c => new SelectListItem
                    {
                        Text  = c.CohortName,
                        Value = c.Id.ToString()
                    })
                              .ToList();

                    Cohorts
                    .Insert(0, new SelectListItem
                    {
                        Text  = "Choose cohort...",
                        Value = "0"
                    });

                    reader.Close();
                }
            }



            /*
             *  Use the LINQ .Select() method to convert
             *  the list of Cohort into a list of SelectListItem
             *  objects
             */
        }
예제 #7
0
        private void Blacklist(ExternalCohortTable source, Exception ex)
        {
            BlackListedSources.Add(source);

            _errorsCheckNotifier.OnCheckPerformed(new CheckEventArgs("Could not reach cohort '" + source + "' (it may be slow responding or inaccessible due to user permissions)", CheckResult.Fail, ex));

            //tell them not to bother looking for the cohort data because its inaccessible
            foreach (ExtractableCohort cohort in Cohorts.Where(c => c.ExternalCohortTable_ID == source.ID).ToArray())
            {
                cohort.InjectKnown((ExternalCohortDefinitionData)null);
            }
        }
예제 #8
0
        /// <summary>
        /// Cleanup the list of cohorts by removing any that have no population.
        /// </summary>
        public void RemoveEmptyCohorts()
        {
            int i = Cohorts.Count - 1;

            while (i >= 0)
            {
                if (Cohorts[i].Count < 0.001)
                {
                    Cohorts.RemoveAt(i);
                }
                i--;
            }
        }
예제 #9
0
        /// <summary>
        /// Construct a new cohort, add it to the list and return a reference to it.
        /// </summary>
        /// <returns>A new initialised cohort object</returns>
        public Cohort NewCohort()
        {
            if (Cohorts == null)
            {
                Cohorts = new List <Cohort>();
            }

            Cohort a = new Cohort(this);

            a.Count            = 0;
            a.ChronoAge        = 0;
            a.PhysiologicalAge = 0;
            Cohorts.Add(a);
            return(a);
        }
        public StudentCreateViewModel(string connectionString)
        {
            _connectionString = connectionString;

            Cohorts = GetAllCohorts().Select(li => new SelectListItem
            {
                Text  = li.Name,
                Value = li.Id.ToString()
            }).ToList();

            Cohorts.Insert(0, new SelectListItem
            {
                Text  = "Choose cohort...",
                Value = "0"
            });
        }
예제 #11
0
        public GetApprovedProvidersQueryHandlerFixture AddNotApprovedCohortAndProviderForAccount()
        {
            Provider.Add(
                new Provider(GetNextProviderId(), "Foo", DateTime.UtcNow, DateTime.UtcNow)
                );

            Cohorts.Add(new Cohort
            {
                EmployerAccountId = AccountId,
                Id               = GetNextCohortId(),
                EditStatus       = Types.EditStatus.EmployerOnly,
                TransferSenderId = null,
                ProviderId       = 1
            });

            return(this);
        }
예제 #12
0
        public GetApprovedProvidersQueryHandlerFixture AddApprovedCohortAndProviderForAccount()
        {
            var provider = new Provider(GetNextProviderId(), "Foo", DateTime.UtcNow, DateTime.UtcNow);

            Provider.Add(provider);

            Cohorts.Add(new Cohort
            {
                EmployerAccountId = AccountId,
                Id               = GetNextCohortId(),
                EditStatus       = 0,
                TransferSenderId = null,
                ProviderId       = provider.UkPrn
            });

            return(this);
        }
예제 #13
0
        public void RemoveNulls(Cohorts cohorts)
        {
            List <string> keysToBeRemoved = new List <string>();

            foreach (var cohortKey in cohorts.Keys)
            {
                if (cohorts[cohortKey] == 0)
                {
                    keysToBeRemoved.Add(cohortKey);
                }
            }

            foreach (var keyToBeRemoved in keysToBeRemoved)
            {
                cohorts.Remove(keyToBeRemoved);
            }
        }
예제 #14
0
        public GetApprovedProvidersQueryHandlerFixture AddCohortAndProvider_WithTransfserSenderNotApproved()
        {
            var provider = new Provider(GetNextProviderId(), "Foo", DateTime.UtcNow, DateTime.UtcNow);

            Provider.Add(provider);

            Cohorts.Add(new Cohort
            {
                EmployerAccountId = AccountId,
                Id                     = GetNextCohortId(),
                EditStatus             = 0,
                TransferSenderId       = 1,
                ProviderId             = provider.UkPrn,
                TransferApprovalStatus = Types.TransferApprovalStatus.Pending
            });

            return(this);
        }
        public InstructorCreateViewModel(string connectionString)
        {
            _connectionString = connectionString;

            Cohorts = GetAllCohorts()
                      .Select(cohort => new SelectListItem()
            {
                Text  = cohort.cohortName,
                Value = cohort.Id.ToString()
            })
                      .ToList();

            Cohorts.Insert(0, new SelectListItem
            {
                Text  = "Choose a cohort",
                Value = "0"
            });
        }
예제 #16
0
        public InstructorCreateViewModel(string connectionString)
        {
            _connectionString = connectionString;

            Cohorts = GetAllCohorts()
                      .Select(cohort => new SelectListItem()
            {
                Text  = cohort.Name,
                Value = cohort.Id.ToString()
            })
                      .ToList();

            // Add an option with instructiosn for how to use the dropdown
            Cohorts.Insert(0, new SelectListItem
            {
                Text  = "Choose a cohort",
                Value = "0"
            });
        }
예제 #17
0
 public InstructorCreateViewModel(IConfiguration config)
 {
     using (IDbConnection conn = new SqlConnection(config.GetConnectionString("DefaultConnection")))
     {
         Cohorts = conn.Query <Cohort>(@"
             SELECT Id, Name FROM Cohort;
         ")
                   .AsEnumerable()
                   .Select(li => new SelectListItem
         {
             Text  = li.Name,
             Value = li.Id.ToString()
         }).ToList();
         ;
     }
     Cohorts.Insert(0, new SelectListItem
     {
         Text  = "Choose cohort...",
         Value = "0"
     });
 }
        // This is an example of method overloading! We have one constructor with no parameter and another constructor that's expecting a connection string. We can call either one!
        public CreateStudentViewModel(string connectionString)
        {
            _connectionString = connectionString;

            // When we create a new instance of this view model, we'll call the internal methods to get all the cohorts from the database
            // Then we'll map over them and convert the list of cohorts to a list of select list items
            Cohorts = GetAllCohorts()
                      .Select(cohort => new SelectListItem()
            {
                Text  = cohort.name,
                Value = cohort.id.ToString()
            })
                      .ToList();

            // Add an option with instructiosn for how to use the dropdown
            Cohorts.Insert(0, new SelectListItem
            {
                Text  = "Choose a cohort",
                Value = "0"
            });
        }
예제 #19
0
        public StudentEditViewModel(Student student, List <Cohort> cohortList, List <Instructor> instructorList, List <Exercise> exerciseList)
        {
            Student = student;
            //add exercises that are already assigned to the student to the AssignExercise list
            student.Exercises.ForEach(exercise => AssignedExercises.Add(exercise.Id));
            //use cohort data to create a list of select items
            Cohorts = cohortList
                      .Select(cohort => new SelectListItem
            {
                Text  = cohort.Name,
                Value = cohort.Id.ToString()
            })
                      .ToList();

            Cohorts.Insert(0, new SelectListItem
            {
                Text  = "Choose cohort...",
                Value = "0"
            });

            //if there are no instructors for that student's cohort, then exercises shouldn't be able to be assigned to that student
            if (instructorList.Count > 0)
            {
                Instructors = instructorList
                              .Select(i => new SelectListItem
                {
                    Text  = i.FullName,
                    Value = i.Id.ToString()
                })
                              .ToList();

                Exercises = exerciseList
                            .Select(e => new SelectListItem
                {
                    Text  = e.Name,
                    Value = e.Id.ToString()
                })
                            .ToList();
            }
        }
예제 #20
0
        //---------------------------------------------------------------------
        public static void WriteLogFile(int CurrentTime)
        {
            double[] avgLiveB       = new double[PlugIn.ModelCore.Ecoregions.Count];
            double[] avgAG_NPP      = new double[PlugIn.ModelCore.Ecoregions.Count];
            double[] avgDefoliation = new double[PlugIn.ModelCore.Ecoregions.Count];
            double[] avgLitterB     = new double[PlugIn.ModelCore.Ecoregions.Count];


            foreach (IEcoregion ecoregion in PlugIn.ModelCore.Ecoregions)
            {
                avgLiveB[ecoregion.Index]       = 0.0;
                avgAG_NPP[ecoregion.Index]      = 0.0;
                avgDefoliation[ecoregion.Index] = 0.0;
                avgLitterB[ecoregion.Index]     = 0.0;
            }



            foreach (ActiveSite site in PlugIn.ModelCore.Landscape)
            {
                IEcoregion ecoregion = PlugIn.ModelCore.Ecoregion[site];
                int        youngBiomass; //ignored

                avgLiveB[ecoregion.Index]       += Cohorts.ComputeBiomass(SiteVars.Cohorts[site], out youngBiomass);
                avgAG_NPP[ecoregion.Index]      += SiteVars.AGNPP[site];
                avgDefoliation[ecoregion.Index] += SiteVars.Defoliation[site];
                avgLitterB[ecoregion.Index]     += SiteVars.Litter[site].Mass;
            }

            foreach (IEcoregion ecoregion in PlugIn.ModelCore.Ecoregions)
            {
                if (EcoregionData.ActiveSiteCount[ecoregion] > 0)
                {
                    PlugIn.summaryLog.Clear();
                    SummaryLog sl = new SummaryLog();
                    sl.Time           = CurrentTime;
                    sl.EcoName        = ecoregion.Name;
                    sl.ActiveCount    = EcoregionData.ActiveSiteCount[ecoregion];
                    sl.AvgAG_NPP      = (avgAG_NPP[ecoregion.Index] / (double)EcoregionData.ActiveSiteCount[ecoregion]);
                    sl.AvgDefoliation = (avgDefoliation[ecoregion.Index] / (double)EcoregionData.ActiveSiteCount[ecoregion]);
                    sl.AvgLitterB     = (avgLitterB[ecoregion.Index] / (double)EcoregionData.ActiveSiteCount[ecoregion]);
                    sl.AvgLiveB       = (avgLiveB[ecoregion.Index] / (double)EcoregionData.ActiveSiteCount[ecoregion]);

                    PlugIn.summaryLog.AddObject(sl);
                    PlugIn.summaryLog.WriteToFile();
                }
            }

            string path = MapNames.ReplaceTemplateVars(@"biomass-succession\biomass-anpp-{timestep}.img", PlugIn.ModelCore.CurrentTime);

            using (IOutputRaster <IntPixel> outputRaster = PlugIn.ModelCore.CreateRaster <IntPixel>(path, PlugIn.ModelCore.Landscape.Dimensions))
            {
                IntPixel pixel = outputRaster.BufferPixel;
                foreach (Site site in PlugIn.ModelCore.Landscape.AllSites)
                {
                    if (site.IsActive)
                    {
                        pixel.MapCode.Value = (int)SiteVars.AGNPP[site];
                    }
                    else
                    {
                        //  Inactive site
                        pixel.MapCode.Value = 0;
                    }
                    outputRaster.WriteBufferPixel();
                }
            }
        }
예제 #21
0
        public void GrowCohorts(DateTime date,
                                DateTime ToTime,
                                bool issuccessionTimestep)
        {
            if (Cohorts == null)
            {
                return;
            }


            while (date.CompareTo(ToTime) < 0)
            {
                PlugIn.SetYear(date.Year);

                if (date.Month == (int)Months.January || canopy == null)
                {
                    canopylaimax = 0;

                    if (cohorts == null)
                    {
                        return;
                    }
                }
                if (date.Month == (int)Months.June)
                {
                    Defoliate(site);
                }

                hydrology.UpdateSiteHydrology(date);

                canopy.Grow(date, site, hydrology, forestfloor, cohorts, siteoutput);

                canopylaimax = canopy.CanopyLAImax;

                foreach (Cohort cohort in canopy.DeadCohorts)
                {
                    DeadCohortAges[cohort.Species].Add(cohort.Age);
                    deadcohorts[cohort.Species]++;
                    Cohorts[cohort.Species].RemoveCohort(cohort, site, null);

                    canopy.ResetDeadCohorts();
                }

                if (issuccessionTimestep)
                {
                    Establishment.ComputeEstablishment(date, this);

                    if (HasSiteOutput)
                    {
                        estoutput.UpdateEstData(date, this);
                    }
                }

                if (HasSiteOutput)
                {
                    siteoutput.UpdateSiteData(date, this);
                    siteoutput.WriteSiteData();
                }
                if (date.Month == (int)Months.December)
                {
                    Cohorts.IncrementCohortsAge();

                    forestfloor.Decompose();
                    forestfloor.Decompose();
                }
                date = date.AddMonths(1);
            }
            if (CohortBiomass.HasDeadCohorts)
            {
                CohortBiomass.HasDeadCohorts = false;
            }
        }
예제 #22
0
        public void Init(Cohorts cohorts)
        {
            DataTable        tpsTable;
            List <DataTable> tpsTables = new List <DataTable>();

            foreach (var chType in chTypes)
            {
                stringBuilder.Clear();
                stringBuilder.Append(agent).Append('_').Append(chType).Append("_TPS");

                tpsTable = dataService.GetTable(stringBuilder.ToString());
                if (tpsTable != null)
                {
                    tpsTables.Add(tpsTable);
                }
                else
                {
                    throw new Exception($"Cannot find the TPS table in the database for the {agent} - {chType} pair.");
                }

                foreach (DataRow row in tpsTable.Rows)
                {
                    stringBuilder.Clear();
                    stringBuilder
                    .Append(agent).Append('_').Append(chType).Append('_').Append(row.Field <string>("InjuryProfileLabel"));

                    cohorts.Add(stringBuilder.ToString(), 0);
                }
            }

            if (chTypes.Count > 1)
            {
                foreach (DataRow row0 in tpsTables[0].Rows)
                {
                    foreach (DataRow row1 in tpsTables[1].Rows)
                    {
                        stringBuilder.Clear();
                        stringBuilder
                        .Append(agent).Append('_').Append(chTypes[0]).Append('_').Append(row0.Field <string>("InjuryProfileLabel"))
                        .Append(":")
                        .Append(agent).Append('_').Append(chTypes[1]).Append('_').Append(row1.Field <string>("InjuryProfileLabel"));

                        cohorts.Add(stringBuilder.ToString(), 0);
                    }
                }
            }

            if (chTypes.Count == 3)
            {
                foreach (DataRow row0 in tpsTables[0].Rows)
                {
                    foreach (DataRow row1 in tpsTables[1].Rows)
                    {
                        foreach (DataRow row2 in tpsTables[2].Rows)
                        {
                            stringBuilder.Clear();
                            stringBuilder
                            .Append(agent).Append('_').Append(chTypes[0]).Append('_').Append(row0.Field <string>("InjuryProfileLabel"))
                            .Append(":")
                            .Append(agent).Append('_').Append(chTypes[1]).Append('_').Append(row1.Field <string>("InjuryProfileLabel"))
                            .Append(":")
                            .Append(agent).Append('_').Append(chTypes[2]).Append('_').Append(row2.Field <string>("InjuryProfileLabel"));

                            cohorts.Add(stringBuilder.ToString(), 0);
                        }
                    }
                }
            }
        }
예제 #23
0
 private long GetNextCohortId() => Cohorts.Count == 0 ? 1 : Cohorts.Max(x => x.Id) + 1;
예제 #24
0
        /// <summary>Loop through each cohort in this LifeCyclePhase to calculate development, mortality, graduation and reproduciton</summary>
        public void Process()
        {
            if (Cohorts?.Count > 13000)  //Check cohort number are not becomming silly
            {
                throw new Exception(FullPath + " has over 1500 cohorts which is to many really.  This is why your simulation is slow and the data store is about to chuck it in.  Check your " + this.Parent.Name.ToString() + " model to ensure development and mortality are sufficient.");
            }

            ZeorDeltas(); //Zero reporting properties for daily summing

            if (Cohorts != null)
            {
                // Calculate daily deltas
                foreach (Cohort c in Cohorts)
                {
                    CurrentCohort       = c;
                    c.ChronologicalAge += 1;
                    //Do development for each cohort
                    c.PhysiologicalAge = Math.Min(1.0, c.PhysiologicalAge + development.Value());
                    //Do mortality for each cohort
                    c.Mortalities = mortality.Value();
                    Mortalities  += c.Mortalities;
                    c.Population  = Math.Max(0.0, c.Population - c.Mortalities);
                    //Do reproduction for each cohort
                    c.Progeny = reproduction.Value();
                    Progeny  += c.Progeny;
                    //Do migration for each cohort
                    c.Emigrants  = migration.Value();
                    Emigrants   += c.Emigrants;
                    c.Population = Math.Max(0.0, c.Population - c.Emigrants);
                }

                //Add Migrants into destination phase
                if (Emigrants > 0)
                {
                    double SumMigrantAge  = 0;
                    double SumMigrantPAge = 0;

                    foreach (Cohort c in Cohorts)
                    {
                        if (c.Emigrants > 0)
                        {
                            SumMigrantAge  += c.Emigrants * c.ChronologicalAge;
                            SumMigrantPAge += c.Emigrants * c.PhysiologicalAge;
                        }
                    }
                    double MeanMigrantAge  = SumMigrantAge / Emigrants;
                    double MeanMigrantPAge = SumMigrantPAge / Emigrants;
                    if (MigrantDestinations.Count == 0)
                    {
                        throw new Exception(FullPath + " is predicting values for migration but has no MigrationDestinationPhase specified");
                    }
                    double MtotalProportion = 0;
                    foreach (MigrantDestinationPhase mdest in MigrantDestinations)
                    {
                        double destEmigrants = Emigrants * mdest.ProportionOfMigrants;
                        if ((MigrantDestinations.Count == 0) && (destEmigrants > 0))
                        {
                            throw new Exception(FullPath + " is predicting values for migration but has not MigrantDestinationPhase specified");
                        }
                        if (destEmigrants > 0)
                        {
                            IModel    zone = Parent.FindAncestor <Zone>();
                            LifeCycle mDestinationCycle = zone.FindInScope <LifeCycle>(mdest.NameOfLifeCycleForMigrants);
                            if (mDestinationCycle == null)
                            {
                                throw new Exception(FullPath + " could not find a destination LifeCycle for migrants called " + mdest.NameOfLifeCycleForMigrants);
                            }
                            LifeCyclePhase mDestinationPhase = mDestinationCycle.FindChild <LifeCyclePhase>(mdest.NameOfPhaseForMigrants);
                            if (mDestinationPhase == null)
                            {
                                throw new Exception(FullPath + " could not find a destination LifeCyclePhase for migrants called " + mdest.NameOfPhaseForMigrants);
                            }

                            SourceInfo ImigrantInfo = new SourceInfo();
                            ImigrantInfo.LifeCycle        = Parent.Name;
                            ImigrantInfo.LifeCyclePhase   = this.Name;
                            ImigrantInfo.Type             = SourceInfo.TypeOptions.Reproduction;
                            ImigrantInfo.Population       = Emigrants;
                            ImigrantInfo.ChronologicalAge = MeanMigrantAge;
                            ImigrantInfo.PhysiologicalAge = MeanMigrantPAge;
                            mDestinationPhase?.NewCohort(ImigrantInfo);
                            MtotalProportion += mdest.ProportionOfMigrants;
                        }
                    }
                    if ((MtotalProportion > 1.001) && (Emigrants > 0))
                    {
                        throw new Exception("The sum of ProportionOfMigrants values in " + FullPath + " ProgenyDestinationPhases is greater than 1.0");
                    }
                }

                // Add progeny into destination phases
                if (Progeny > 0)
                {
                    if ((ProgenyDestinations.Count == 0) && (Progeny > 0))
                    {
                        throw new Exception(FullPath + " is predicting values for reproduction but has no ProgenyDestinationPhase specified");
                    }
                    double PtotalProportion = 0;
                    foreach (ProgenyDestinationPhase pdest in ProgenyDestinations)
                    {
                        double arrivals = Progeny * pdest.ProportionOfProgeny;

                        if (arrivals > 0)
                        {
                            IModel    zone = Parent.FindAncestor <Zone>();
                            LifeCycle pDestinationCylce = zone.FindInScope <LifeCycle>(pdest.NameOfLifeCycleForProgeny);
                            if (pDestinationCylce == null)
                            {
                                throw new Exception(FullPath + " could not find a destination LifeCycle for progeny called " + pdest.NameOfLifeCycleForProgeny);
                            }
                            LifeCyclePhase pDestinationPhase = pDestinationCylce.FindChild <LifeCyclePhase>(pdest.NameOfPhaseForProgeny);
                            if (pDestinationPhase == null)
                            {
                                throw new Exception(FullPath + " could not find a destination LifeCyclePhase for progeny called " + pdest.NameOfPhaseForProgeny);
                            }

                            SourceInfo ArivalsInfo = new SourceInfo();
                            ArivalsInfo.LifeCycle        = Parent.Name;
                            ArivalsInfo.LifeCyclePhase   = this.Name;
                            ArivalsInfo.Type             = SourceInfo.TypeOptions.Reproduction;
                            ArivalsInfo.Population       = arrivals;
                            ArivalsInfo.ChronologicalAge = 0;
                            ArivalsInfo.PhysiologicalAge = 0;
                            pDestinationPhase?.NewCohort(ArivalsInfo);
                            PtotalProportion += pdest.ProportionOfProgeny;
                        }
                    }
                    if (((PtotalProportion < 0.999) || (PtotalProportion > 1.001)) && (Progeny > 0))
                    {
                        throw new Exception("The sum of ProportionOfProgeny values in " + FullPath + " ProgenyDestinationPhases does not equal 1.0");
                    }
                }

                // Move garduates to destination phase
                foreach (Cohort c in Cohorts.ToArray())
                {
                    if (c.PhysiologicalAge >= 1.0) //Members ready to graduate or die
                    {
                        if (LifeCyclePhaseForGraduates != null)
                        {
                            Graduates += c.Population; //Members graduate
                        }
                        else
                        {
                            Mortalities += c.Population; //Members die
                        }
                        Cohorts.Remove(c);               //Remove mature cohort
                    }

                    if (c.Population < 0.001)  //Remove cohort if all members dead
                    {
                        Cohorts.Remove(c);
                    }
                }

                if (Graduates > 0)  //Promote graduates to cohort in next LifeCyclePhase
                {
                    SourceInfo GraduateInfo = new SourceInfo();
                    GraduateInfo.LifeCycle        = Parent.Name;
                    GraduateInfo.LifeCyclePhase   = this.Name;
                    GraduateInfo.Type             = SourceInfo.TypeOptions.Graduation;
                    GraduateInfo.Population       = Graduates;
                    GraduateInfo.ChronologicalAge = 0;
                    GraduateInfo.PhysiologicalAge = 0;
                    LifeCyclePhaseForGraduates?.NewCohort(GraduateInfo);
                }
            }
        }
예제 #25
0
 /// <summary>
 /// Empty the cohort list
 /// </summary>
 public void Clear()
 {
     Cohorts.Clear();
 }
예제 #26
0
 /// <summary>
 /// Remove a specified cohort item
 /// </summary>
 /// <param name="aCohort">The cohort object to be removed</param>
 public void Remove(Cohort aCohort)
 {
     Cohorts.Remove(aCohort);
 }
예제 #27
0
 /// <summary>
 /// Remove the cohort at the end of the list
 /// </summary>
 public void RemoveLastCohort()
 {
     Cohorts.RemoveAt(Cohorts.Count - 1);
 }
예제 #28
0
        /// <summary>Loop through each cohort in this LifeCyclePhase to calculate development, mortality, graduation and reproduciton</summary>
        public void Process()
        {
            if (Cohorts?.Count > 500)  //Check cohort number are not becomming silly
            {
                throw new Exception(Apsim.FullPath(this) + " has over 500 cohorts which is to many really.  This is why your simulation is slow and the data store is about to chuck it in.  Check your " + this.Parent.Name.ToString() + " model to ensure development and mortality are sufficient.");
            }

            ZeorDeltas(); //Zero reporting properties for daily summing

            foreach (ProgenyDestinationPhase pdest in ProgenyDestinations)
            {
                pdest.ProgenyToDestination = 0;
            }

            if (Cohorts != null)
            {
                // Calculate daily deltas
                foreach (Cohort c in Cohorts)
                {
                    CurrentCohort       = c;
                    c.ChronologicalAge += 1;
                    //Do development for each cohort
                    c.PhysiologicalAge = Math.Min(1.0, c.PhysiologicalAge + development.Value());
                    //Do mortality for each cohort
                    c.Mortalities = mortality.Value();
                    Mortalities  += c.Mortalities;
                    c.Population  = Math.Max(0.0, c.Population - c.Mortalities);
                    //Do reproduction for each cohort
                    Progeny += reproduction.Value();
                    foreach (ProgenyDestinationPhase dest in ProgenyDestinations)
                    {
                        dest.ProgenyToDestination += reproduction.Value() * dest.ProportionOfProgeny;
                    }
                    //Do migration for each cohort
                    Migrants += migration.Value();
                    if (Migrants > 0)
                    {
                        if (MigrantDestinations.Count == 0)
                        {
                            throw new Exception(Apsim.FullPath(this) + " is predicting values for migration but has no MigrationDestinationPhase specified");
                        }
                        double MtotalProportion = 0;
                        foreach (MigrantDestinationPhase mdest in MigrantDestinations)
                        {
                            double cohortMigrants = migration.Value() * mdest.ProportionOfMigrants;
                            if ((MigrantDestinations.Count == 0) && (cohortMigrants > 0))
                            {
                                throw new Exception(Apsim.FullPath(this) + " is predicting values for migration but has not MigrantDestinationPhase specified");
                            }
                            if (cohortMigrants > 0)
                            {
                                IModel    zone = Apsim.Parent(this.Parent, typeof(Zone));
                                LifeCycle mDestinationCycle = Apsim.Find(zone, mdest.NameOfLifeCycleForMigrants) as LifeCycle;
                                if (mDestinationCycle == null)
                                {
                                    throw new Exception(Apsim.FullPath(this) + " could not find a destination LifeCycle for migrants called " + mdest.NameOfLifeCycleForMigrants);
                                }
                                LifeCyclePhase mDestinationPhase = Apsim.Child(mDestinationCycle, mdest.NameOfPhaseForMigrants) as LifeCyclePhase;
                                if (mDestinationPhase == null)
                                {
                                    throw new Exception(Apsim.FullPath(this) + " could not find a destination LifeCyclePhase for migrants called " + mdest.NameOfPhaseForMigrants);
                                }
                                mDestinationPhase.NewCohort(cohortMigrants, c.ChronologicalAge, c.PhysiologicalAge);
                                MtotalProportion += mdest.ProportionOfMigrants;
                            }
                        }
                        if ((MtotalProportion > 1.001) && (Migrants > 0))
                        {
                            throw new Exception("The sum of ProportionOfMigrants values in " + Apsim.FullPath(this) + " ProgenyDestinationPhases is greater than 1.0");
                        }
                    }
                }

                // Add progeny into destination phase
                if ((ProgenyDestinations.Count == 0) && (Progeny > 0))
                {
                    throw new Exception(Apsim.FullPath(this) + " is predicting values for reproduction but has no ProgenyDestinationPhase specified");
                }
                double PtotalProportion = 0;
                foreach (ProgenyDestinationPhase pdest in ProgenyDestinations)
                {
                    if (pdest.ProgenyToDestination > 0)
                    {
                        IModel    zone = Apsim.Parent(this.Parent, typeof(Zone));
                        LifeCycle pDestinationCylce = Apsim.Find(zone, pdest.NameOfLifeCycleForProgeny) as LifeCycle;
                        if (pDestinationCylce == null)
                        {
                            throw new Exception(Apsim.FullPath(this) + " could not find a destination LifeCycle for progeny called " + pdest.NameOfLifeCycleForProgeny);
                        }
                        LifeCyclePhase pDestinationPhase = Apsim.Child(pDestinationCylce, pdest.NameOfPhaseForProgeny) as LifeCyclePhase;
                        if (pDestinationPhase == null)
                        {
                            throw new Exception(Apsim.FullPath(this) + " could not find a destination LifeCyclePhase for progeny called " + pdest.NameOfPhaseForProgeny);
                        }
                        pDestinationPhase.NewCohort(pdest.ProgenyToDestination, 0, 0);
                        PtotalProportion += pdest.ProportionOfProgeny;
                    }
                }
                if (((PtotalProportion < 0.999) || (PtotalProportion > 1.001)) && (Progeny > 0))
                {
                    throw new Exception("The sum of ProportionOfProgeny values in " + Apsim.FullPath(this) + " ProgenyDestinationPhases does not equal 1.0");
                }


                // Move garduates to destination phase
                foreach (Cohort c in Cohorts.ToArray())
                {
                    if (c.PhysiologicalAge >= 1.0) //Members ready to graduate or die
                    {
                        if (LifeCyclePhaseForGraduates != null)
                        {
                            Graduates += c.Population; //Members graduate
                        }
                        else
                        {
                            Mortalities += c.Population; //Members die
                        }
                        Cohorts.Remove(c);               //Remove mature cohort
                    }

                    if (c.Population < 0.001)  //Remove cohort if all members dead
                    {
                        Cohorts.Remove(c);
                    }
                }

                if (Graduates > 0)  //Promote graduates to cohort in next LifeCyclePhase
                {
                    LifeCyclePhaseForGraduates?.NewCohort(Graduates, 0.0, 0.0);
                }
            }
        }