// *********************** protected members **************************************** /// <summary> /// Checks to see if the name of the cell data source matches the cell data /// source name stored in the animals data source. An InvalidOperationException /// exception is raised if the datasource is not connected. /// </summary> /// <param name="Cells"> /// The list of cells containg the name to check. An ArgumentNullException /// exception is raised if Cells is null. /// </param> /// <returns>True if the names match.</returns> protected override bool CheckCellsName(cCellList Cells) { if (mvarConnection == null) { ThrowConnectionException(); } if (Cells == null) { ThrowCellsException(); } // create a dataset DataSet CellsNameDataSet = new DataSet("CellsNameDataSet"); // get CellsName table OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM [CellsName]", mvarConnection); da.Fill(CellsNameDataSet, "CellsName"); // now get the new table DataTable dt = CellsNameDataSet.Tables[0]; // get the datarow at the current read position DataRow dr = dt.Rows[0]; // check the cells name bool CheckValue = (Convert.ToString(dr["CellsName"]) == Cells.Name); CellsNameDataSet.Clear(); return(CheckValue); }
/// <summary> /// Create a new stategy based on passed settings /// </summary> /// <param name="ModelBackground">The background</param> /// <param name="StrategyCells">The cells affected by the strategy</param> /// <param name="ActualLevel">The level of the strategy</param> /// <param name="Year">The year the strategy is applied</param> /// <param name="Week">The week the strategy is applied</param> /// <returns>A newly created cull strategy</returns> protected override cStrategy CreateStrategy(cBackground ModelBackground, cCellList StrategyCells, int ActualLevel, int Year, int Week) { // extract the current fertility control effective period from the dataset int EffectivePeriod; try { if (mvarTrialSettings.Tables.Contains("FertilityControlInformation")) { //YM: //DataRow drFertility = mvarTrialSettings.Tables["FertilityControlInformation"].Rows[0]; //EffectivePeriod = Convert.ToInt32(drFertility["EffectivePeriod"]); DataRow drFertility = mvarTrialSettings.Tables[2].Rows[1]; EffectivePeriod = Convert.ToInt32(drFertility[1]); } else { // not found - must be an older dataset EffectivePeriod = 52; } } catch { // not found - must be an older dataset EffectivePeriod = 52; } // return a cull strategy return(new cFertilityStrategy(ModelBackground, StrategyCells, ActualLevel, Year, Week, EffectivePeriod)); }
// *************************************** Constructors ********************************************* /// <summary> /// Constructor /// </summary> /// <param name="Cells">The list of cells to output</param> /// <param name="FileName">The name of the file to output</param> public cCellPopulationOutput(cCellList Cells, string FileName, bool TabDelimited, bool NoOutputExceptions, cAppReport AppReport) : base(FileName, TabDelimited, NoOutputExceptions, AppReport) { mvarCells = Cells; mvarOutputStrings = new Dictionary <string, StringBuilder>(); WriteHeader(); }
/// <summary> /// Create a new stategy based on passed settings /// </summary> /// <param name="ModelBackground">The background</param> /// <param name="StrategyCells">The cells affected by the strategy</param> /// <param name="ActualLevel">The level of the strategy</param> /// <param name="Year">The year the strategy is applied</param> /// <param name="Week">The week the strategy is applied</param> /// <returns>A newly created cull strategy</returns> protected override cStrategy CreateStrategy(cBackground ModelBackground, cCellList StrategyCells, int ActualLevel, int Year, int Week) { // extract the current vaccine effective period from the dataset //YM: //DataRow drDisease = mvarTrialSettings.Tables["DiseaseInformation"].Rows[0]; //int EffectivePeriod = Convert.ToInt32(drDisease["VaccineEffectivePeriod"]); DataRow drDisease = mvarTrialSettings.Tables[2].Rows[0]; int EffectivePeriod = Convert.ToInt32(drDisease[1]); // return a vaccine strategy return(new cRabiesVaccineStrategy(ModelBackground, StrategyCells, ActualLevel, Year, Week, EffectivePeriod)); }
/// <summary> /// Writes the name of the cells data source that these animals are associated /// with. An InvalidOperationException exception is raised if the datasource /// is not connected or if the datasource is open as read-only. /// </summary> /// <param name="Cells"> /// The list of cells who's name shall be written. An ArgumentNullException /// exception is raised if Cells is null. /// </param> protected override void WriteCellsName(cCellList Cells) { if (mvarConnection == null) { ThrowConnectionException(); } if (Cells == null) { ThrowCellsException(); } if (mvarReadOnly) { ThrowReadOnlyException(); } // start by eliminating any existing data OleDbCommand cmd = new OleDbCommand("DELETE * FROM [CellsName]", mvarConnection); cmd.ExecuteNonQuery(); // create the query to write the data cmd.CommandText = "INSERT INTO [CellsName] VALUES('" + Cells.Name + "');"; cmd.ExecuteNonQuery(); }
/// <summary> /// Create a new stategy based on passed settings /// </summary> /// <param name="ModelBackground">The background</param> /// <param name="StrategyCells">The cells affected by the strategy</param> /// <param name="ActualLevel">The level of the strategy</param> /// <param name="Year">The year the strategy is applied</param> /// <param name="Week">The week the strategy is applied</param> /// <returns>A newly created cull strategy</returns> protected override cStrategy CreateStrategy(cBackground ModelBackground, cCellList StrategyCells, int ActualLevel, int Year, int Week) { // return a cull strategy return(new cCullStrategy(ModelBackground, StrategyCells, ActualLevel, Year, Week)); }
/// <summary> /// Define movement behaviour for independent (yearling and adult) foxes. /// </summary> /// <param name="CurrentWeek"> /// The current week of the year. An ArgumentOutOfRangeException exception is /// raised if CurrentWeek is not in the range of 1-52. /// </param> /// <returns>True if the fox changes cell.</returns> protected override bool Move(int CurrentWeek) { if (CurrentWeek < 1 || CurrentWeek > 52) { ThrowWeekException("CurrentWeek"); } // see if this is week 0, if it is, reset has moved ///////////////////////////////EER: the next line has been commented to enable >1 movement per year //if (CurrentWeek == 1) HasMoved = false; if (CurrentWeek > 0 || CurrentWeek < 53) { HasMoved = false; //EER } // next, if this animal has moved, leave now //EER: the next line has been commented out to enable >1 movement per year //if (HasMoved) return false; //EER: Do not all Adam & Eve to move, to help grow the population if (this.ID == "0" | this.ID == "1") { //System.Diagnostics.Debug.WriteLine("cFox.cs: Move(): Adam or Eve, ID = " + this.ID + "; don't move"); return(false); } // now load the appropriate movement arrays depending upon what type of animal // you are bool[] MovementArray; double[] MovementDistribution; if (this.AgeClass == enumAgeClass.YoungOfTheYear) { if (this.Gender == enumGender.female) { MovementArray = (this.Background as cFoxBackground).FoxYoungFemaleWeeklyMovement; MovementDistribution = (this.Background as cFoxBackground).FoxYoungFemaleMovementDistribution; } else { MovementArray = (this.Background as cFoxBackground).FoxYoungMaleWeeklyMovement; MovementDistribution = (this.Background as cFoxBackground).FoxYoungMaleMovementDistribution; } } else { if (this.Gender == enumGender.female) { MovementArray = (this.Background as cFoxBackground).FoxJuvAdultFemaleWeeklyMovement; MovementDistribution = (this.Background as cFoxBackground).FoxJuvAdultFemaleMovementDistribution; } else { MovementArray = (this.Background as cFoxBackground).FoxJuvAdultMaleWeeklyMovement; MovementDistribution = (this.Background as cFoxBackground).FoxJuvAdultMaleMovementDistribution; } } // can the animal even move this week? If not, leave now!! if (!MovementArray[CurrentWeek - 1]) { return(false); } // if it can, work out the current odds of moving for the current week double MovementOdds = 0; double OddsDenominator = 0; for (int j = 0; j < 52; j++) { if (MovementArray[j]) { OddsDenominator += 1; if (j <= CurrentWeek) { MovementOdds += 1; } } } // if odds denominator is 0, then no movement is defined, leave now if (OddsDenominator == 0) { // set the HasMoved flag to true and exit as if movement has happened HasMoved = true; return(true); } // calculate current movement odds // EER: this is needed to calculate the odds of moving for the current permissible week, given that there may be // more than one permissible weeks, and for the raccoon model, only 1 movement allowed per year // EER: For ARM, the animal is allowed >1 movement per year, so this code is not needed /* * MovementOdds = MovementOdds / OddsDenominator * 100; * // now determine if the animal will move * if (MovementOdds < 100) { * // if the random number is greater than the movement odds, the animal does not move * double RanValue = this.Background.RandomNum.RealValue(0, 100); * if (RanValue > MovementOdds) return false; * } */ // if we get here, we are going to move!! // generate a random number double MoveRandom = this.Background.RandomNum.RealValue(0, 100); // loop until movement distance is found // EER: This loops, interating i, until the sum of the movement probabilities, defined by array MovementDistribution // are greater than the random number, to randomly define the probability of moving i cells // So, the final i defines the number of cells to move // I think the limit of i should be set at the max allowable cells to move // Dave had this at 26, but I changed it to 49 to align with the ORM ArcGIS interface double sum = 0; int i; for (i = 0; i < 49; i++) { sum += MovementDistribution[i] * 100; //System.Diagnostics.Debug.WriteLine("cFox.cs: Move(): MovementDistribution[" + i + "] = " + MovementDistribution[i]); //System.Diagnostics.Debug.WriteLine("cFox.cs: Move(): sum = " + sum); //System.Diagnostics.Debug.WriteLine("cFox.cs: Move(): MoveRandom = " + MoveRandom); if (sum >= MoveRandom) { break; } } //System.Diagnostics.Debug.WriteLine("cFox.cs: Move(): HERE 5 Move this many cells = " + i); // at this point, i is the dispersal distance // call the calculate path of the MasterCell object belonging to the // background to find a path through the cells. Remember that the path // returned may not be the distance requested because it may stop at // a supercell boundary //EER: string lastCell; lastCell = null; if (i > 0) { // calculate a random direction bias //NOTE: Generating integer value now in range of 0 to 5. For this call we WANT the range 0 to 5 since the values // 0, 1, 2, 3, 4, 5 are all equally probable. D. Ball February 8, 2010 enumNeighbourPosition DirectionBias = (enumNeighbourPosition)this.Background.RandomNum.IntValue(0, 5); cCellList Path = this.Background.Cells.CalculatePath(this.CurrentCell.ID, i, DirectionBias); // move this animal to the last cell in this path if (Path.Count > 0) { this.MoveAnimal(Path[Path.Count - 1]); } } // set the HasMoved flag to true HasMoved = true; return(true); }
public void btn_LoadSettingsFile_Click(object sender, EventArgs e) { //System.Diagnostics.Debug.WriteLine(""); //System.Diagnostics.Debug.WriteLine("Form1.cs: btn_LoadSettingsFile_Click()"); DataSet returnSettingsData = null; string filePath = string.Empty; string fileExt = string.Empty; settingsFile = null; OpenFileDialog file = new OpenFileDialog(); //open dialog to choose file if (file.ShowDialog() == System.Windows.Forms.DialogResult.OK) //if there is a file choosen by the user { filePath = file.FileName; //get the path and name of the file settingsFile = filePath; /*Debug.WriteLine("settingsFile = " + settingsFile); * Debug.WriteLine("filePath = " + filePath);*/ fileExt = Path.GetExtension(filePath); //get the file extension if (fileExt.CompareTo(".xls") == 0 || fileExt.CompareTo(".xlsx") == 0) { try { //Code to put Excel worksheets in datatables and then 1 dataset alphabetically //Make excel settings file into dataset object returnSettingsData = cCSVSettingsTemplate.Parse(filePath); //Retrieve setttings values in the dataset: Table(worksheet), row and column String parameterSetName = returnSettingsData.Tables[4].Rows[0][1].ToString(); //YM //String parameterSetName = returnSettingsData.Tables[6].Rows[0][1].ToString(); //YM textBoxParameterSet.Text = parameterSetName; outputFolder = returnSettingsData.Tables[4].Rows[2][1].ToString();//YM //outputFolder = returnSettingsData.Tables[6].Rows[2][1].ToString(); //YM textBoxOutputFolder.Text = outputFolder; String landscapeFile = returnSettingsData.Tables[4].Rows[3][1].ToString();//YM //String landscapeFile = returnSettingsData.Tables[6].Rows[3][1].ToString();//YM Char[] delimiters = { '\\', '/' }; String[] landscapeFileItems = landscapeFile.Split(delimiters); String landscapeFileItemsLast = landscapeFileItems.Last(); textBoxLandscapeFile.Text = landscapeFileItemsLast; String growPop = returnSettingsData.Tables[4].Rows[4][1].ToString();//YM //String growPop = returnSettingsData.Tables[6].Rows[4][1].ToString();//YM //Debug.WriteLine("growPop = " + growPop); if (growPop == "TRUE") { textBoxPopulationFile.Text = "No file provided. A population is being grown."; } else { String populationFile = returnSettingsData.Tables[4].Rows[7][1].ToString();//YM //String populationFile = returnSettingsData.Tables[6].Rows[7][1].ToString();//YM //Debug.WriteLine("populationFile = " + populationFile); //Char delimiter = '\\'; String[] populationFileItems = populationFile.Split(delimiters); String populationFileItemsLast = populationFileItems.Last(); //Debug.WriteLine("populationFileItemsLast = " + populationFileItemsLast); textBoxPopulationFile.Text = populationFileItemsLast; } String numbIterations = returnSettingsData.Tables[4].Rows[12][1].ToString();//YM //String numbIterations = returnSettingsData.Tables[6].Rows[12][1].ToString();//YM textBoxNumbIterations.Text = numbIterations; String numbYears = returnSettingsData.Tables[4].Rows[8][1].ToString();//YM //String numbYears = returnSettingsData.Tables[6].Rows[8][1].ToString();//YM textBoxNumbYears.Text = numbYears; //Connect to landscape XML file to get supercell and K information cXMLCellDataSource landscapeXMLFile = new cXMLCellDataSource(true); int totalPathLength = landscapeFile.Length; int landNameLength = landscapeFileItemsLast.Length; string landPath = landscapeFile.Substring(0, totalPathLength - landNameLength); //Debug.WriteLine("Form1.cs: btn_LoadSettingsFile_Click(): landPath = " + landPath); //Debug.WriteLine("Form1.cs: btn_LoadSettingsFile_Click(): landscapeFileItemsLast = " + landscapeFileItemsLast); landscapeXMLFile.DataSourcePath = landPath; landscapeXMLFile.DataSourceName = landscapeFileItemsLast; landscapeXMLFile.Connect(); //Getting set up to get supercell values cSuperCellList listSuperCells = new cSuperCellList(); landscapeXMLFile.GetSuperCellData(listSuperCells); int numbSupCells = listSuperCells.Count; //Debug.WriteLine("Form1.cs: btn_LoadSettingsFile_Click(): numbSupCells = " + numbSupCells); string superCellFormEntry; superCellFormEntry = null; //Getting set up to get K values cUniformRandom rand = new cUniformRandom(); cCellList listCells = new cCellList(rand); landscapeXMLFile.GetCellData(listCells, listSuperCells); cCellData CellData = new cCellData(); int numbCells = listCells.Count; //Debug.WriteLine("Form1.cs: btn_LoadSettingsFile_Click(): numbCells = " + numbCells); double mvarK; // Get the supercell and K combinations var superK = new ListWithDuplicates(); for (int i = 0; i < numbCells; i++) { //landscapeKValues[i] = listCells.ToString() //values = listCells.ToString(); mvarK = listCells[i].K; superCellFormEntry = listCells[i].SuperCell.ID; //Debug.WriteLine("Form1.cs: btn_LoadSettingsFile_Click(): i = " + i + " mvarK = " + mvarK + "; supercell = " + superCellFormEntry); superK.Add(superCellFormEntry, mvarK); } // Disconnect from the landscape XML file landscapeXMLFile.Disconnect(); //With the data loaded in, activate the run button btnRun.Enabled = true; } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); } } else { MessageBox.Show("Please choose .xls or .xlsx file only.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Error); //custom messageBox to show error } } }
//*************************************************************************************************************************************** //mothode : Load Files ** for ORM console ** public void LoadSettingsFile(string[] args) { //System.Diagnostics.Debug.WriteLine(""); //System.Diagnostics.Debug.WriteLine("Form1.cs: btn_LoadSettingsFile_Click()"); pathArg[0] = "."; Debug.WriteLine("settingsFile =++++++++++++++++++++++++++++++++++++++++++++++++++++++++ " + pathArg[0]); DataSet returnSettingsData = null; string filePath = string.Empty; string fileExt = string.Empty; settingsFile = null; //filePath = pathArg[0]; //get the path and name of the file settingsFile = pathArg[0]; /*Debug.WriteLine("settingsFile = " + settingsFile); * Debug.WriteLine("filePath = " + filePath);*/ //fileExt = pathArg[0]; //get the file extension if (pathArg[0] != "") { try { //Code to put Excel worksheets in datatables and then 1 dataset alphabetically //Make excel settings file into dataset object returnSettingsData = cCSVSettingsTemplate.Parse(pathArg[0]); //Retrieve setttings values in the dataset: Table(worksheet), row and column String parameterSetName = returnSettingsData.Tables[4].Rows[0][1].ToString(); // textBoxParameterSet.Text = parameterSetName; outputFolder = returnSettingsData.Tables[4].Rows[2][1].ToString(); // textBoxOutputFolder.Text = outputFolder; Debug.WriteLine(" outputFolder =++++++++++++++++++++++++++++++++++++++++++++++++++++++++ " + outputFolder); String landscapeFile = returnSettingsData.Tables[4].Rows[3][1].ToString(); Char[] delimiters = { '\\', '/' }; String[] landscapeFileItems = landscapeFile.Split(delimiters); String landscapeFileItemsLast = landscapeFileItems.Last(); // textBoxLandscapeFile.Text = landscapeFileItemsLast; String growPop = returnSettingsData.Tables[4].Rows[4][1].ToString(); //Debug.WriteLine("growPop = " + growPop); if (growPop == "TRUE") { // textBoxPopulationFile.Text = "No file provided. A population is being grown."; } else { String populationFile = returnSettingsData.Tables[4].Rows[7][1].ToString(); //Debug.WriteLine("populationFile = " + populationFile); //Char delimiter = '\\'; String[] populationFileItems = populationFile.Split(delimiters); String populationFileItemsLast = populationFileItems.Last(); //Debug.WriteLine("populationFileItemsLast = " + populationFileItemsLast); // textBoxPopulationFile.Text = populationFileItemsLast; } String numbIterations = returnSettingsData.Tables[4].Rows[12][1].ToString(); // textBoxNumbIterations.Text = numbIterations; String numbYears = returnSettingsData.Tables[4].Rows[8][1].ToString(); // textBoxNumbYears.Text = numbYears; //Connect to landscape XML file to get supercell and K information cXMLCellDataSource landscapeXMLFile = new cXMLCellDataSource(true); int totalPathLength = landscapeFile.Length; int landNameLength = landscapeFileItemsLast.Length; string landPath = landscapeFile.Substring(0, totalPathLength - landNameLength); //Debug.WriteLine("Form1.cs: btn_LoadSettingsFile_Click(): landPath = " + landPath); //Debug.WriteLine("Form1.cs: btn_LoadSettingsFile_Click(): landscapeFileItemsLast = " + landscapeFileItemsLast); landscapeXMLFile.DataSourcePath = landPath; landscapeXMLFile.DataSourceName = landscapeFileItemsLast; landscapeXMLFile.Connect(); //Getting set up to get supercell values cSuperCellList listSuperCells = new cSuperCellList(); landscapeXMLFile.GetSuperCellData(listSuperCells); int numbSupCells = listSuperCells.Count; //Debug.WriteLine("Form1.cs: btn_LoadSettingsFile_Click(): numbSupCells = " + numbSupCells); string superCellFormEntry; superCellFormEntry = null; //Getting set up to get K values cUniformRandom rand = new cUniformRandom(); cCellList listCells = new cCellList(rand); landscapeXMLFile.GetCellData(listCells, listSuperCells); cCellData CellData = new cCellData(); int numbCells = listCells.Count; //Debug.WriteLine("Form1.cs: btn_LoadSettingsFile_Click(): numbCells = " + numbCells); double mvarK; // Get the supercell and K combinations var superK = new ListWithDuplicates(); for (int i = 0; i < numbCells; i++) { //landscapeKValues[i] = listCells.ToString() //values = listCells.ToString(); mvarK = listCells[i].K; superCellFormEntry = listCells[i].SuperCell.ID; //Debug.WriteLine("Form1.cs: btn_LoadSettingsFile_Click(): i = " + i + " mvarK = " + mvarK + "; supercell = " + superCellFormEntry); superK.Add(superCellFormEntry, mvarK); } // Disconnect from the landscape XML file landscapeXMLFile.Disconnect(); //With the data loaded in, activate the run button // btnRun.Enabled = true; } catch (Exception ex) { Console.Error.WriteLine(ex.Message.ToString()); } } else { Console.Error.WriteLine("Please choose .xls or .xlsx file only."); } }
/// <summary> /// Abstract methos for creating an actual strategy. Overridden by sub-classes to create specific strategy types /// </summary> /// <param name="ModelBackground">The background</param> /// <param name="StrategyCells">The cells the strategy applies to</param> /// <param name="ActualLevel">The level for the strategy</param> /// <param name="Year">The year of the strategy</param> /// <param name="Week">The week of the strategy</param> /// <returns>A newly created combned stategy</returns> protected abstract cStrategy CreateStrategy(cBackground ModelBackground, cCellList StrategyCells, int ActualLevel, int Year, int Week);
/// <summary> /// Read vaccination strategies from the Trial Settings dataset /// </summary> /// <param name="ModelBackground"></param> public void GetStrategies(cBackground ModelBackground) { //System.Diagnostics.Debug.WriteLine(""); //System.Diagnostics.Debug.WriteLine("Runs with no strategies???? cStrategyReader.cs: GetStrategies()"); int i = 0; int j = 0; int Level = 0; int ActualLevel = 0; int Year = 0; int Week = 0; // get required data tables and datarow DataTable dtStrategyTimes = mvarTrialSettings.Tables[mvarStrategyName + "_StrategyTimes"]; DataTable dtStrategies = mvarTrialSettings.Tables[mvarStrategyName + "_Strategies"]; DataTable dtCellIDs = mvarTrialSettings.Tables[mvarStrategyName + "_CellIDs"]; List <string> StrategyCellIDs = new List <string>(); string StrategyFieldName = null; DataRow dr = null; // get the strategy cell ids - these are stored in the same order as the strategy values foreach (DataRow drCell in dtCellIDs.Rows) { //System.Diagnostics.Debug.WriteLine(" No data in drCell"); StrategyCellIDs.Add(drCell["CellID"].ToString()); } // loop through the number of defined strategies (the count of records in the StrategyTimes table) int numbdefs = dtStrategyTimes.Rows.Count; //System.Diagnostics.Debug.WriteLine(" number of defined strategies = " + numbdefs); for (i = 0; i <= dtStrategyTimes.Rows.Count - 1; i++) { //System.Diagnostics.Debug.WriteLine(" here01"); // get the year and week for this strategy dr = dtStrategyTimes.Rows[i]; Year = Convert.ToInt32(dr["Year"]); Week = Convert.ToInt32(dr["Week"]); // field name in Strategies table for this strategy StrategyFieldName = "S" + i; // create a list of cells affected by this strategy cCellList StrategyCells = new cCellList(null); ActualLevel = 0; for (j = 0; j <= StrategyCellIDs.Count - 1; j++) { //System.Diagnostics.Debug.WriteLine(" here02"); dr = dtStrategies.Rows[j]; // get the level for each cell Level = Convert.ToInt32(dr[StrategyFieldName]); if (Level > ActualLevel) { ActualLevel = Level; } // add a cell to the list if the level value for that cell is greater than 0 if (Level > 0) { StrategyCells.Add(ModelBackground.Cells[StrategyCellIDs[j]]); } } // now create a strategy object cStrategy NewStrategy = CreateStrategy(ModelBackground, StrategyCells, ActualLevel, Year, Week); // add this strategy to the list of strategies ModelBackground.Strategies.Add(NewStrategy); } }
/// <summary> /// YM: /// Read control strategies from the CSV settings file /// </summary> /// <param name="ModelBackground"></param>The background /// <param name="StrategiesCtrlPath"></param> the path to the strategies control file public void GetStrategiesCsvTemplate(string StrategiesCtrlPath, cBackground ModelBackground) { int i = 0; int j = 0; int Level = 0; int ActualLevel = 0; int Year = 0; int Week = 0; char Delimiter = ';'; // Get csv data DataTable dtStrategiesCtrl = new DataTable(); DataRow Rowdt; using (StreamReader StrategiesCtrlData = new StreamReader(StrategiesCtrlPath)) { string StrategiesCtrlLine = StrategiesCtrlData.ReadLine(); string[] Header = StrategiesCtrlLine.Split(Delimiter); foreach (string dc in Header) { dtStrategiesCtrl.Columns.Add(new DataColumn(dc)); } while (!StrategiesCtrlData.EndOfStream) { StrategiesCtrlLine = StrategiesCtrlData.ReadLine(); string[] Rows = StrategiesCtrlLine.Split(Delimiter); if (Rows.Length == dtStrategiesCtrl.Columns.Count) { Rowdt = dtStrategiesCtrl.NewRow(); Rowdt.ItemArray = Rows; dtStrategiesCtrl.Rows.Add(Rowdt); } } StrategiesCtrlData.Close(); } // Use the RowFilter method to find all rows matching the strategy type. dtStrategiesCtrl.DefaultView.RowFilter = "Type='" + mvarStrategyName + "'"; DataTable dtStrategiesCtrlFilterType = (dtStrategiesCtrl.DefaultView).ToTable(); dtStrategiesCtrl.Clear(); List <string> StrategiesNameList = new List <string>(); foreach (DataRow row in dtStrategiesCtrlFilterType.Rows) { StrategiesNameList.Add(row["StrategyName"].ToString()); } int StrategiesNameCount = StrategiesNameList.Distinct().Count(); IEnumerable <string> StrategiesNameListDistinct = StrategiesNameList.Distinct(); // loop through the number of defined strategies foreach (string StrategyNameStr in StrategiesNameListDistinct) { // filter strategies by name dtStrategiesCtrlFilterType.DefaultView.RowFilter = "StrategyName='" + StrategyNameStr + "'"; DataTable dtStrategiesCtrlFilterStrgName = (dtStrategiesCtrlFilterType.DefaultView).ToTable(); // get required data tables and datarow List <string> StrategyCellIDs = new List <string>(); DataRow dr; // get the strategy cell ids for (i = 0; i <= dtStrategiesCtrlFilterStrgName.Rows.Count - 1; i++) { StrategyCellIDs.Add(dtStrategiesCtrlFilterStrgName.Rows[i]["HexCellID"].ToString()); } // create a list of cells affected by this strategy cCellList StrategyCells = new cCellList(null); StrategyCells.Name = "StrategiesCells"; cStrategy NewStrategy = null; for (j = 0; j <= StrategyCellIDs.Count - 1; j++) { //System.Diagnostics.Debug.WriteLine(" here02"); dr = dtStrategiesCtrlFilterStrgName.Rows[j]; //get the year and the week for this strategy Year = Convert.ToInt32(dr["Year"]); Week = Convert.ToInt32(dr["Week"]); // get the level for each cell Level = Convert.ToInt32(dr["Level"]); if (Level > ActualLevel) { ActualLevel = Level; } // add a cell to the list if the level value for that cell is greater than 0 if (Level > 0) { ActualLevel = Level; StrategyCells.Add(ModelBackground.Cells[StrategyCellIDs[j]]); } } // now create a strategy object NewStrategy = CreateStrategy(ModelBackground, StrategyCells, ActualLevel, Year, Week); // add this strategy to the list of strategies ModelBackground.Strategies.Add(NewStrategy); } dtStrategiesCtrlFilterType.Clear(); }
/// <summary> /// Define movement behaviour for independent (yearling and adult) raccoons. /// </summary> /// <param name="CurrentWeek"> /// The current week of the year. An ArgumentOutOfRangeException exception is /// raised if CurrentWeek is not in the range of 1-52. /// </param> /// <returns>True if the raccoon changes cell.</returns> protected override bool Move(int CurrentWeek) { if (CurrentWeek < 1 || CurrentWeek > 52) { ThrowWeekException("CurrentWeek"); } // see if this is week 0, if it is, reset has moved if (CurrentWeek == 1) { HasMoved = false; } //if (this.ID == "3683630" && CurrentWeek == 12 && this.Background.Years.CurrentYearNum == 81) //{ // int Stopper = 1; //} // next, if this animal has moved, leave now if (HasMoved) { return(false); } // now load the appropriate movement arrays depending upon what type of animal // you are bool[] MovementArray; double[] MovementDistribution; if (this.AgeClass == enumAgeClass.YoungOfTheYear) { if (this.Gender == enumGender.female) { MovementArray = (this.Background as cRaccoonBackground).RaccoonYoungFemaleWeeklyMovement; MovementDistribution = (this.Background as cRaccoonBackground).RaccoonYoungFemaleMovementDistribution; } else { MovementArray = (this.Background as cRaccoonBackground).RaccoonYoungMaleWeeklyMovement; MovementDistribution = (this.Background as cRaccoonBackground).RaccoonYoungMaleMovementDistribution; } } else { if (this.Gender == enumGender.female) { MovementArray = (this.Background as cRaccoonBackground).RaccoonJuvAdultFemaleWeeklyMovement; MovementDistribution = (this.Background as cRaccoonBackground).RaccoonJuvAdultFemaleMovementDistribution; } else { MovementArray = (this.Background as cRaccoonBackground).RaccoonJuvAdultMaleWeeklyMovement; MovementDistribution = (this.Background as cRaccoonBackground).RaccoonJuvAdultMaleMovementDistribution; } } // can the animal even move this week? If not, leave now!! if (!MovementArray[CurrentWeek - 1]) { return(false); } // if it can, work out the current odds of moving double MovementOdds = 0; double OddsDenominator = 0; for (int j = 0; j < 52; j++) { if (MovementArray[j]) { OddsDenominator += 1; if (j <= CurrentWeek) { MovementOdds += 1; } } } // if odds denominator is 0, then no movement is defined, leave now if (OddsDenominator == 0) { // set the HasMoved flag to true and exit as if movement has happened HasMoved = true; return(true); } // calculate current movement odds MovementOdds = MovementOdds / OddsDenominator * 100; // now detirmine if the animal will move if (MovementOdds < 100) { // if the random number is greater than the movement odds, the animal does not move double RanValue = this.Background.RandomNum.RealValue(0, 100); if (RanValue > MovementOdds) { return(false); } } // if we get here, we are going to move!! // generate a random number double MoveRandom = this.Background.RandomNum.RealValue(0, 100); // loop until movement distance is found double sum = 0; int i; for (i = 0; i < 26; i++) { sum += MovementDistribution[i]; if (sum >= MoveRandom) { break; } } // at this point, i is the dispersal distance // call the calculate path of the MasterCell object belonging to the // background to find a path through the cells. Remember that the path // returned may not be the distance requested because it may stop at // a supercell boundary if (i > 0) { // calculate a random direction bias //NOTE: Generating integer value now in range of 0 to 5. For this call we WANT the range 0 to 5 since the values // 0, 1, 2, 3, 4, 5 are all equally probable. D. Ball February 8, 2010 enumNeighbourPosition DirectionBias = (enumNeighbourPosition)this.Background.RandomNum.IntValue(0, 5); cCellList Path = this.Background.Cells.CalculatePath(this.CurrentCell.ID, i, DirectionBias); // move this animal to the last cell in this path if (Path.Count > 0) { this.MoveAnimal(Path[Path.Count - 1]); } } // set the HasMoved flag to true HasMoved = true; return(true); }
/// <summary> /// Constructor. Create a strategy for applying a combined vaccination and fertility control strategy /// </summary> /// <param name="BG">The background</param> /// <param name="Cells">The list of cells affected by the strategy</param> /// <param name="Level">The level of the strategy</param> /// <param name="Year">The year the strategy is applied</param> /// <param name="Week">The week the strategy is applied</param> /// <param name="VaccineEffectivePeriod">The effective period of the vaccine</param> /// <param name="FertilityEffectivePeriod">The effective period of the fertility control</param> public cRabiesCombinedStrategy(cBackground BG, cCellList Cells, int Level, int Year, int Week, int VaccineEffectivePeriod, int FertilityEffectivePeriod) : base(BG, Cells, Level, Year, Week, "Rabies", VaccineEffectivePeriod, FertilityEffectivePeriod) { }
/// <summary> /// Create the strategy being read /// </summary> /// <param name="ModelBackground">The background</param> /// <param name="StrategyCells">The cells the strategy applies to</param> /// <param name="ActualLevel">The level for the strategy</param> /// <param name="Year">The year of the strategy</param> /// <param name="Week">The week of the strategy</param> /// <returns>A newly created combned stategy</returns> protected override cStrategy CreateStrategy(cBackground ModelBackground, cCellList StrategyCells, int ActualLevel, int Year, int Week) { // extract the current fertility control effective period from the dataset int VaccineEffectivePeriod = 0; int FertilityEffectivePeriod = 0; // extract the current vaccine effective period from the dataset var drDisease = mvarTrialSettings.Tables["DiseaseInformation"].Rows[0]; VaccineEffectivePeriod = Convert.ToInt32(drDisease["VaccineEffectivePeriod"]); try { var drFertility = mvarTrialSettings.Tables["FertilityControlInformation"].Rows[0]; FertilityEffectivePeriod = Convert.ToInt32(drFertility["EffectivePeriod"]); } catch { // not found - must be an older dataset FertilityEffectivePeriod = 52; } // return a fertility strategy return(new cRabiesCombinedStrategy(ModelBackground, StrategyCells, ActualLevel, Year, Week, VaccineEffectivePeriod, FertilityEffectivePeriod)); }
/// <summary> /// Constructor /// </summary> /// <param name="BG">The background</param> /// <param name="Cells">The cells affected by the strategy</param> /// <param name="Level">The level of the strategy</param> /// <param name="Year">The year the strategy is applied</param> /// <param name="Week">The week the strategy is applied</param> /// <param name="EffectivePeriod">The effecive period of the vaccine</param> public cRabiesVaccineStrategy(cBackground BG, cCellList Cells, int Level, int Year, int Week, int EffectivePeriod) : base(BG, Cells, Level, Year, Week, "Rabies", EffectivePeriod) { }