Goose Management Model ODdox  1.02
farm.cpp
Go to the documentation of this file.
1 
14 //
15 // farm.cpp
16 //
17 /*
18 *******************************************************************************************************
19 Copyright (c) 2011, Christopher John Topping, University of Aarhus
20 All rights reserved.
21 
22 Redistribution and use in source and binary forms, with or without modification, are permitted provided
23 that the following conditions are met:
24 
25 Redistributions of source code must retain the above copyright notice, this list of conditions and the
26 following disclaimer.
27 Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
28 the following disclaimer in the documentation and/or other materials provided with the distribution.
29 
30 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
31 IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
32 FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
33 BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
34 BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
35 BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36 LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
37 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38 ********************************************************************************************************
39 */
40 
41 //
42 #define _CRT_SECURE_NO_DEPRECATE
43 
44 #include <string.h>
45 #include <algorithm>
46 #include <vector>
47 #include <iostream>
48 #include <fstream>
49 #include "../BatchALMaSS/BoostRandomGenerators.h"
50 #include "../ALMaSSDefines.h"
51 #include <math.h> //for optimisation
52 #include <time.h> //for dec. making
53 
54 
55 #define _CRTDBG_MAP_ALLOC
56 
57 using namespace std;
58 
59 #define _CRT_SECURE_NO_DEPRECATE
60 #include <random> //for dec. making - draw from a dist.
61 #include "../BatchALMaSS/ALMaSS_Setup.h"
62 #include "../Landscape/ls.h"
63 #include "../Landscape/cropprogs/BroadBeans.h"
64 #include "../Landscape/cropprogs/Carrots.h"
65 #include "../Landscape/cropprogs/CloverGrassGrazed1.h"
66 #include "../Landscape/cropprogs/CloverGrassGrazed2.h"
67 #include "../Landscape/cropprogs/FieldPeas.h"
68 #include "../Landscape/cropprogs/FieldPeasSilage.h"
69 #include "../Landscape/cropprogs/Fodderbeet.h"
70 #include "../Landscape/cropprogs/Sugarbeet.h"
71 #include "../Landscape/cropprogs/FodderGrass.h"
72 #include "../Landscape/cropprogs/Maize.h"
73 #include "../Landscape/cropprogs/MaizeSilage.h"
74 #include "../Landscape/cropprogs/OFodderbeet.h"
75 #include "../Landscape/cropprogs/OMaizeSilage.h"
76 #include "../Landscape/cropprogs/OBarleyPeaCloverGrass.h"
77 #include "../Landscape/cropprogs/OSBarleySilage.h"
78 #include "../Landscape/cropprogs/OCarrots.h"
79 #include "../Landscape/cropprogs/OCloverGrassGrazed1.h"
80 #include "../Landscape/cropprogs/OCloverGrassGrazed2.h"
81 #include "../Landscape/cropprogs/OCloverGrassSilage1.h"
82 #include "../Landscape/cropprogs/OFirstYearDanger.h"
83 #include "../Landscape/cropprogs/OGrazingPigs.h"
84 #include "../Landscape/cropprogs/OPermanentGrassGrazed.h"
85 #include "../Landscape/cropprogs/OSeedGrass1.h"
86 #include "../Landscape/cropprogs/OSeedGrass2.h"
87 #include "../Landscape/cropprogs/OSpringBarleyPigs.h"
88 #include "../Landscape/cropprogs/OFieldPeas.h"
89 #include "../Landscape/cropprogs/OFieldPeasSilage.h"
90 #include "../Landscape/cropprogs/OrchardCrop.h"
91 #include "../Landscape/cropprogs/OOats.h"
92 #include "../Landscape/cropprogs/Oats.h"
93 #include "../Landscape/cropprogs/OPotatoes.h"
94 #include "../Landscape/cropprogs/OSpringBarley.h"
95 #include "../Landscape/cropprogs/OSpringBarleyExt.h"
96 #include "../Landscape/cropprogs/OWinterBarley.h"
97 #include "../Landscape/cropprogs/OWinterBarleyExt.h"
98 #include "../Landscape/cropprogs/OWinterRape.h"
99 #include "../Landscape/cropprogs/OWinterRye.h"
100 #include "../Landscape/cropprogs/OWinterWheat.h"
101 #include "../Landscape/cropprogs/OWinterWheatUndersown.h"
102 #include "../Landscape/cropprogs/OWinterWheatUndersownExt.h"
103 #include "../Landscape/cropprogs/PermanentGrassGrazed.h"
104 #include "../Landscape/cropprogs/PermanentGrassLowYield.h"
105 #include "../Landscape/cropprogs/PermanentGrassTussocky.h"
106 #include "../Landscape/cropprogs/PermanentSetAside.h"
107 #include "../Landscape/cropprogs/Potatoes.h"
108 #include "../Landscape/cropprogs/PotatoesIndustry.h"
109 #include "../Landscape/cropprogs/seedgrass1.h"
110 #include "../Landscape/cropprogs/seedgrass2.h"
111 #include "../Landscape/cropprogs/setaside.h"
112 #include "../Landscape/cropprogs/SpringBarley.h"
113 #include "../Landscape/cropprogs/SpringBarleySpr.h"
114 #include "../Landscape/cropprogs/SpringBarleyPTreatment.h"
115 #include "../Landscape/cropprogs/SpringBarleySKManagement.h"
116 #include "../Landscape/cropprogs/SpringBarleyCloverGrass.h"
117 #include "../Landscape/cropprogs/SpringBarleySeed.h"
118 #include "../Landscape/cropprogs/SpringBarleySilage.h"
119 #include "../Landscape/cropprogs/SpringRape.h"
120 #include "../Landscape/cropprogs/Triticale.h"
121 #include "../Landscape/cropprogs/OTriticale.h"
122 #include "../Landscape/cropprogs/WinterBarley.h"
123 #include "../Landscape/cropprogs/winterrape.h"
124 #include "../Landscape/cropprogs/WinterRye.h"
125 #include "../Landscape/cropprogs/WinterWheat.h"
126 #include "../Landscape/cropprogs/WWheatPControl.h"
127 #include "../Landscape/cropprogs/WWheatPTreatment.h"
128 #include "../Landscape/cropprogs/WWheatPToxicControl.h"
129 #include "../Landscape/cropprogs/AgroChemIndustryCereal.h"
130 
131 #include "../Landscape/cropprogs/WinterWheatStrigling.h"
132 #include "../Landscape/cropprogs/WinterWheatStriglingCulm.h"
133 #include "../Landscape/cropprogs/WinterWheatStriglingSingle.h"
134 #include "../Landscape/cropprogs/SpringBarleyCloverGrassStrigling.h"
135 #include "../Landscape/cropprogs/SpringBarleyStrigling.h"
136 #include "../Landscape/cropprogs/SpringBarleyStriglingCulm.h"
137 #include "../Landscape/cropprogs/SpringBarleyStriglingSingle.h"
138 #include "../Landscape/cropprogs/MaizeStrigling.h"
139 #include "../Landscape/cropprogs/winterrapestrigling.h"
140 #include "../Landscape/cropprogs/WinterRyeStrigling.h"
141 #include "../Landscape/cropprogs/WinterBarleyStrigling.h"
142 #include "../Landscape/cropprogs/FieldPeasStrigling.h"
143 #include "../Landscape/cropprogs/SpringBarleyPeaCloverGrassStrigling.h"
144 #include "../Landscape/cropprogs/YoungForest.h"
145 #include "../Landscape/cropprogs/NorwegianPotatoes.h"
146 #include "../Landscape/cropprogs/NorwegianOats.h"
147 #include "../Landscape/cropprogs/NorwegianSpringBarley.h"
148 
149 #include "../Landscape/cropprogs/PLWinterWheat.h"
150 #include "../Landscape/cropprogs/PLWinterRape.h"
151 #include "../Landscape/cropprogs/PLWinterBarley.h"
152 #include "../Landscape/cropprogs/PLWinterTriticale.h"
153 #include "../Landscape/cropprogs/PLWinterRye.h"
154 #include "../Landscape/cropprogs/PLSpringWheat.h"
155 #include "../Landscape/cropprogs/PLSpringBarley.h"
156 #include "../Landscape/cropprogs/PLMaize.h"
157 #include "../Landscape/cropprogs/PLMaizeSilage.h"
158 #include "../Landscape/cropprogs/PLPotatoes.h"
159 #include "../Landscape/cropprogs/PLBeet.h"
160 #include "../Landscape/cropprogs/PLFodderLucerne1.h"
161 #include "../Landscape/cropprogs/PLFodderLucerne2.h"
162 #include "../Landscape/cropprogs/PLCarrots.h"
163 #include "../Landscape/cropprogs/PLSpringBarleySpr.h"
164 #include "../Landscape/cropprogs/PLWinterWheatLate.h"
165 #include "../Landscape/cropprogs/PLBeetSpr.h"
166 #include "../Landscape/cropprogs/PLBeans.h"
167 
168 #include "../Landscape/cropprogs/NLBeet.h"
169 #include "../Landscape/cropprogs/NLCarrots.h"
170 #include "../Landscape/cropprogs/NLMaize.h"
171 #include "../Landscape/cropprogs/NLPotatoes.h"
172 #include "../Landscape/cropprogs/NLSpringBarley.h"
173 #include "../Landscape/cropprogs/NLWinterWheat.h"
174 #include "../Landscape/cropprogs/NLCabbage.h"
175 #include "../Landscape/cropprogs/NLTulips.h"
176 #include "../Landscape/cropprogs/NLGrassGrazed1.h"
177 #include "../Landscape/cropprogs/NLGrassGrazed1Spring.h"
178 #include "../Landscape/cropprogs/NLGrassGrazed2.h"
179 #include "../Landscape/cropprogs/NLGrassGrazedLast.h"
180 #include "../Landscape/cropprogs/NLPermanentGrassGrazed.h"
181 #include "../Landscape/cropprogs/NLBeetSpring.h"
182 #include "../Landscape/cropprogs/NLCarrotsSpring.h"
183 #include "../Landscape/cropprogs/NLMaizeSpring.h"
184 #include "../Landscape/cropprogs/NLPotatoesSpring.h"
185 #include "../Landscape/cropprogs/NLSpringBarleySpring.h"
186 #include "../Landscape/cropprogs/NLCabbageSpring.h"
187 #include "../Landscape/cropprogs/NLCatchPeaCrop.h"
188 
189 #include "../Landscape/cropprogs/DummyCropPestTesting.h"
190 
191 
192 #include "../Landscape/map_cfg.h"
193 #include "../BatchALMaSS/BoostRandomGenerators.h"
194 
195 extern boost::variate_generator<base_generator_type&, boost::uniform_real<> > g_rand_uni;
196 
197 extern Landscape * g_landscape_p;
198 
199 CfgBool cfg_organic_extensive( "FARM_ORGANIC_EXTENSIVE", CFG_CUSTOM, false );
200 // Enable this for reading the farm reference file instead of the
201 // automated (not at all random) farm generation. Should not really
202 // be set to false, ever.
203 static CfgBool l_map_read_farmfile( "MAP_READ_FARMFILE", CFG_PRIVATE, true );
204 static CfgStr l_map_farmref_file( "MAP_FARMREF_FILE", CFG_CUSTOM, "farmrefs.txt" );
205 
206 static CfgStr l_emaize_price_file( "EMAIZE_PRICE_FILE", CFG_CUSTOM, "EM_price.txt" );
207 
209 CfgBool cfg_OptimisingFarms("OPTIMISING_FARMS",CFG_CUSTOM, false);
212 CfgBool cfg_OptimiseBedriftsmodelCrops("OPTIMISE_BEDRIFTSMODEL_CROPS",CFG_CUSTOM, false); //12.03.13, set it to true to run the optimisation like in the Bedriftsmodel (with the same crops)
214 CfgBool cfg_DumpFarmAreas ("DUMP_FARM_AREAS", CFG_CUSTOM, false);
217 CfgBool cfg_UseBedriftsmodelFarmAreas ("USE_BEDRIFTSMODEL_FARM_AREAS", CFG_CUSTOM, false);
219 CfgBool cfg_OnlyDeliberation ("ONLY_DELIBERATION", CFG_CUSTOM, true); //041213 if true, farmers will always choose to deliberate (see function ChooseDecisionMode)
220 
222 CfgFloat cfg_Neighbor_dist ("NEIGHBOR_DIST",CFG_CUSTOM,1.5);
224 CfgFloat cfg_Min_certainty("MIN_CERTAINTY",CFG_CUSTOM,0);
226 CfgFloat cfg_Min_need_satisfaction1 ("MIN_NEED_SATISFACTION_ONE",CFG_CUSTOM, 100); //profit, %
228 CfgFloat cfg_Min_need_satisfaction2 ("MIN_NEED_SATISFACTION_TWO",CFG_CUSTOM, 100); //yield, %
230 CfgFloat cfg_Profit_max_proportion ("PROFIT_MAX_PROPORTION",CFG_CUSTOM, 100);//proportion in the population
232 CfgFloat cfg_Yield_max_proportion ("YIELD_MAX_PROPORTION",CFG_CUSTOM, 0);
234 CfgFloat cfg_Environmentalist_proportion ("ENVIRONMENTALIST_PROPORTION",CFG_CUSTOM, 0);
238 CfgFloat cfg_Yield_max_pest_prob_multiplier ("YIELD_MAX_PEST_PROB_MULITPLIER",CFG_CUSTOM, 1.5);
241 CfgFloat cfg_Env_pest_multiplier ("ENV_PEST_MULTIPLIER",CFG_CUSTOM, 1.25); //>1
244 CfgFloat cfg_Env_fert_multiplier ("ENV_FERT_MULTIPLIER",CFG_CUSTOM, 0.8);//<1
245 CfgBool cfg_Sensitivity_analysis ("SENSITIVITY_ANALYSIS", CFG_CUSTOM, false);
247 CfgBool cfg_Areas_Based_on_Distribution ("AREAS_BASED_ON_DISTRIBUTION", CFG_CUSTOM, false);
249 CfgBool cfg_MaizeEnergy ("MAIZE_ENERGY", CFG_CUSTOM, false);
250 
252  CfgFloat cfg_AnimalsThreshold ("ANIMALS_THRESHOLD",CFG_CUSTOM, 0);
254  CfgFloat cfg_PriceChangeThreshold ("PRICE_CHANGE_THRESHOLD",CFG_CUSTOM, 0.2);
256  CfgInt cfg_LifeStage ("LIFE_STAGE", CFG_CUSTOM, 0);
258  CfgInt cfg_Animals_number_test_day ("ANIMALS_NUMBER_TEST_DAY", CFG_CUSTOM, 152);
259 
261 CfgFloat cfg_Price_FU ("PRICE_FU",CFG_CUSTOM, 1.157);
263 CfgFloat cfg_Price_Nt ("PRICE_NT",CFG_CUSTOM, 1.93);
264 CfgFloat cfg_Price_SBarley ("PRICE_SBARLEY",CFG_CUSTOM, 83);
265 CfgFloat cfg_Price_Oats ("PRICE_OATS",CFG_CUSTOM, 75);
266 CfgFloat cfg_Price_WBarley ("PRICE_WBARLEY",CFG_CUSTOM, 93);
267 CfgFloat cfg_Price_WWheat ("PRICE_WWHEAT",CFG_CUSTOM, 94);
268 CfgFloat cfg_Price_Triticale ("PRICE_TRITICALE",CFG_CUSTOM, 80);
269 CfgFloat cfg_Price_WRape ("PRICE_WRAPE",CFG_CUSTOM, 163);
270 CfgFloat cfg_Price_SRape ("PRICE_SRAPE",CFG_CUSTOM, 163);
271 
273 CfgFloat cfg_Min_fodder_prod_pig ("MIN_FODDER_PROD_PIG", CFG_CUSTOM, 20);
275 CfgFloat cfg_Min_fodder_prod_cattle ("MIN_FODDER_PROD_CATTLE", CFG_CUSTOM, 35);
276 
277 
279 CfgFloat cfg_ClosestFarmProbParam1( "CLOSESTFARMPROBPARAMONE", CFG_CUSTOM, 0.005 );
281 CfgFloat cfg_FarmSizeProbParam1( "FARMSIZEPROBPARAMONE", CFG_CUSTOM, 1.5 );
283 CfgFloat cfg_ClosestFarmProbParam2("CLOSESTFARMPROBPARAMTWO", CFG_CUSTOM, 1.0);
284 FarmManager * g_farmmanager; //added 19.03.13
286 CfgFloat cfg_RoostDistProbParam1( "ROOSTDISTPROBPARAMONE", CFG_CUSTOM, 1.5 );
287 
290 CfgInt cfg_grain_distribution("GOOSE_GRAIN_DISTRIBUTION", CFG_CUSTOM, 0, 0, 2);
291 
292 
294 bool CompPcts (tpct i,tpct j) { return (i.pct<j.pct); }
295 
296 
298 {
299  m_ddegstoharvest = -1; // Set to -1 to indicate that this is not using ddegs to harvest, this will be reset in descendent classes as needed
300  SetCropClassification(tocc_Winter); // Defualt classification is Winter - change this if necessary in the derived crop constructor
301 }
302 
303 bool Crop::Do( Farm * /* a_farm */, LE * /* a_field */, FarmEvent* /* a_ev */ ) {
304  return true;
305 }
306 
307 void Crop::SimpleEvent(long a_date, int a_todo, bool a_lock) {
308 
309  m_farm->AddNewEvent(m_field->GetVegType(), a_date, m_field, a_todo, m_field->GetRunNum(), a_lock, 0, false, (TTypesOfVegetation)0);
310 }
311 
312 void Crop::SimpleEvent_(long a_date, int a_todo, bool a_lock, Farm* a_farm, LE* a_field) {
313 
314  a_farm->AddNewEvent(a_field->GetVegType(), a_date, a_field, a_todo, a_field->GetRunNum(), a_lock, 0, false, (TTypesOfVegetation)0);
315 }
316 
317 
318 void Crop::ChooseNextCrop (int a_no_dates){
319 
323  if(cfg_OptimisingFarms.value()){ // do this only if we have optimising farms
324  if(!cfg_OptimiseBedriftsmodelCrops.value()){ // do this only if we use almass crops!!
325 
326  if (g_date->GetYearNumber()>0){ //changed 030713 since we dont use m_rotation anymore - but we do in the hidden year!
327  OptimisingFarm * opf;
328  if(m_farm->GetType() == tof_OptimisingFarm){ //take only optimising farms
329  opf = dynamic_cast<OptimisingFarm*>(m_farm);
330  opf->Match_crop_to_field (m_field);
331  //move MDates if necessary, use the new_startdate:
332  if (m_ev->m_startday > g_date->DayInYear(1,7)) {
333  if (m_field->GetMDates(0,0) >=m_ev->m_startday)
334  {
335  g_msg->Warn( WARN_BUG, "Crop::ChooseNextCrop(): ","Harvest too late for the next crop to start!!!" );
336  exit( 1 );
337  }
338  // Now fix any late finishing problems
339  for (int i=0; i<a_no_dates; i++) {
340  if(m_field->GetMDates(0,i)>=m_ev->m_startday) {
341  m_field->SetMDates(0,i,m_ev->m_startday-1); //move the starting date
342  }
343  if(m_field->GetMDates(1,i)>=m_ev->m_startday){
344  m_field->SetMConstants(i,0); //change the default value of the MConst (=1) to 0 (necessary to correctly execute farm events in case the finishing date (MDate) was moved)
345  m_field->SetMDates(1,i,m_ev->m_startday-1); //move the finishing date
346  }
347  }
348  }
349 
350  }
351  }
352  }
353  }
354 
355 }
356 
361 void Farm::Management( void ) {
362  HandleEvents();
363  for ( unsigned int i = 0; i < m_fields.size(); i++ ) {
364  // Check for infinite loop in management plan.
365  int count = m_fields[ i ]->GetVegStore();
366  if ( count >= 0 )
367  m_fields[ i ]->SetVegStore( ++count );
368  if ( count > 800 ) {
369  // More than two years where nothing happened.
370  // Raise 'Merry Christmas'!
371  char error_num[ 20 ];
372  sprintf( error_num, "%d", m_fields[ i ]->GetVegType() );
373  g_msg->Warn( WARN_BUG, "I the Farm Manager caught infinite loop in tov type:", error_num );
374  sprintf( error_num, "%d", m_fields[ i ]->m_tried_to_do );
375  g_msg->Warn( WARN_BUG, "It was last seen trying to perform action # ""(or thereabouts):", error_num );
376  exit( 1 );
377  }
378  }
379 }
380 
381 
386 bool Farm::LeSwitch( FarmEvent * ev ) {
387  // Ignore this event if it is from the execution of
388  // a previous management plan.
389  if (ev->m_field->GetRunNum() > ev->m_run)
390  return false;
391  // Store what we are trying to do this time.
392  // ***FN*** To be cleaned up later.
393  ev->m_field->m_tried_to_do = ev->m_todo;
394  bool done;
395 
396  switch (ev->m_event) {
397  case tov_Carrots:
398  done = m_carrots->Do( this, ev->m_field, ev );
399  break;
400  case tov_BroadBeans:
401  done = m_broadbeans->Do( this, ev->m_field, ev );
402  break;
403  case tov_FodderGrass:
404  done = m_foddergrass->Do( this, ev->m_field, ev );
405  break;
407  done = m_CGG1->Do( this, ev->m_field, ev );
408  break;
410  done = m_CGG2->Do( this, ev->m_field, ev );
411  break;
412  case tov_FieldPeas:
413  done = m_fieldpeas->Do( this, ev->m_field, ev );
414  break;
415  case tov_FieldPeasSilage:
416  done = m_fieldpeassilage->Do( this, ev->m_field, ev );
417  break;
418  case tov_FodderBeet:
419  done = m_fodderbeet->Do( this, ev->m_field, ev );
420  break;
421  case tov_SugarBeet:
422  done = m_sugarbeet->Do( this, ev->m_field, ev );
423  break;
424  case tov_OFodderBeet:
425  done = m_ofodderbeet->Do( this, ev->m_field, ev );
426  break;
427  case tov_Maize:
428  done = m_maize->Do( this, ev->m_field, ev );
429  break;
431  done = m_OBarleyPCG->Do( this, ev->m_field, ev );
432  break;
433  case tov_OCarrots:
434  done = m_ocarrots->Do( this, ev->m_field, ev );
435  break;
437  done = m_OCGS1->Do( this, ev->m_field, ev );
438  break;
440  done = m_OCGG1->Do( this, ev->m_field, ev );
441  break;
443  done = m_OCGG2->Do( this, ev->m_field, ev );
444  break;
445  case tov_OFieldPeas:
446  done = m_ofieldpeas->Do( this, ev->m_field, ev );
447  break;
449  done = m_ofieldpeassilage->Do( this, ev->m_field, ev );
450  break;
451  case tov_OGrazingPigs:
452  done = m_ograzingpigs->Do( this, ev->m_field, ev );
453  break;
454  case tov_OrchardCrop:
455  done = m_orchardcrop->Do( this, ev->m_field, ev );
456  break;
457  case tov_OOats:
458  done = m_ooats->Do( this, ev->m_field, ev );
459  break;
460  case tov_Oats:
461  done = m_oats->Do( this, ev->m_field, ev );
462  break;
464  done = m_opermgrassgrazed->Do( this, ev->m_field, ev );
465  break;
466  case tov_OPotatoes:
467  done = m_opotatoes->Do( this, ev->m_field, ev );
468  break;
469  case tov_OSpringBarley:
470  done = m_ospringbarley->Do( this, ev->m_field, ev );
471  break;
472  case tov_OSBarleySilage:
473  done = m_osbarleysilage->Do( this, ev->m_field, ev );
474  break;
475  case tov_OSeedGrass1:
476  done = m_oseedgrass1->Do( this, ev->m_field, ev );
477  break;
478  case tov_OSeedGrass2:
479  done = m_oseedgrass2->Do( this, ev->m_field, ev );
480  break;
482  done = m_ospringbarleyext->Do( this, ev->m_field, ev );
483  break;
485  done = m_ospringbarleypigs->Do( this, ev->m_field, ev );
486  break;
487  case tov_OWinterBarley:
488  done = m_owinterbarley->Do( this, ev->m_field, ev );
489  break;
491  done = m_owinterbarleyext->Do( this, ev->m_field, ev );
492  break;
494  done = m_owinterwheatundersown->Do( this, ev->m_field, ev );
495  break;
496  case tov_OWinterWheat:
497  done = m_owinterwheat->Do( this, ev->m_field, ev );
498  break;
500  done = m_owinterwheatundersownext->Do( this, ev->m_field, ev );
501  break;
502  case tov_OWinterRape:
503  done = m_owinterrape->Do( this, ev->m_field, ev );
504  break;
505  case tov_OWinterRye:
506  done = m_owinterrye->Do( this, ev->m_field, ev );
507  break;
509  done = m_permgrassgrazed->Do( this, ev->m_field, ev );
510  break;
512  done = m_permgrasslowyield->Do( this, ev->m_field, ev );
513  break;
515  done = m_permgrasstussocky->Do( this, ev->m_field, ev );
516  break;
518  done = m_permanentsetaside->Do( this, ev->m_field, ev );
519  break;
520  case tov_Potatoes:
521  done = m_potatoes->Do( this, ev->m_field, ev );
522  break;
524  done = m_potatoesindustry->Do( this, ev->m_field, ev );
525  break;
526  case tov_SeedGrass1:
527  done = m_seedgrass1->Do( this, ev->m_field, ev );
528  break;
529  case tov_SeedGrass2:
530  done = m_seedgrass2->Do( this, ev->m_field, ev );
531  break;
532  case tov_Setaside:
533  done = m_setaside->Do( this, ev->m_field, ev );
534  break;
535  case tov_SpringBarley:
536  done = m_springbarley->Do( this, ev->m_field, ev );
537  break;
538  case tov_SpringBarleySpr:
539  done = m_springbarleyspr->Do( this, ev->m_field, ev );
540  break;
542  done = m_springbarleyptreatment->Do( this, ev->m_field, ev );
543  break;
545  done = m_springbarleyskmanagement->Do( this, ev->m_field, ev );
546  break;
548  done = m_sbarleyclovergrass->Do( this, ev->m_field, ev );
549  break;
551  done = m_springbarleyseed->Do( this, ev->m_field, ev );
552  break;
554  done = m_springbarleysilage->Do( this, ev->m_field, ev );
555  break;
556  case tov_SpringRape:
557  done = m_springrape->Do( this, ev->m_field, ev );
558  break;
559  case tov_Triticale:
560  done = m_triticale->Do( this, ev->m_field, ev );
561  break;
562  case tov_OTriticale:
563  done = m_otriticale->Do( this, ev->m_field, ev );
564  break;
565  case tov_WinterBarley:
566  done = m_winterbarley->Do( this, ev->m_field, ev );
567  break;
568  case tov_WinterRape:
569  done = m_winterrape->Do( this, ev->m_field, ev );
570  break;
571  case tov_WinterRye:
572  done = m_winterrye->Do( this, ev->m_field, ev );
573  break;
574  case tov_WinterWheat:
575  done = m_winterwheat->Do( this, ev->m_field, ev );
576  break;
577  case tov_WWheatPControl:
578  done = m_wwheatpcontrol->Do( this, ev->m_field, ev );
579  break;
581  done = m_wwheatptoxiccontrol->Do( this, ev->m_field, ev );
582  break;
584  done = m_wwheatptreatment->Do( this, ev->m_field, ev );
585  break;
587  done = m_agrochemindustrycereal->Do( this, ev->m_field, ev );
588  break;
590  done = m_winterwheatstrigling->Do( this, ev->m_field, ev );
591  break;
593  done = m_winterwheatstriglingsingle->Do( this, ev->m_field, ev );
594  break;
596  done = m_winterwheatstriglingculm->Do( this, ev->m_field, ev );
597  break;
599  done = m_springbarleyclovergrassstrigling->Do( this, ev->m_field, ev );
600  break;
602  done = m_springbarleystrigling->Do( this, ev->m_field, ev );
603  break;
605  done = m_springbarleystriglingsingle->Do( this, ev->m_field, ev );
606  break;
608  done = m_springbarleystriglingculm->Do( this, ev->m_field, ev );
609  break;
610  case tov_MaizeStrigling:
611  done = m_maizestrigling->Do( this, ev->m_field, ev );
612  break;
613  case tov_MaizeSilage:
614  done = m_maizesilage->Do( this, ev->m_field, ev );
615  break;
616  case tov_OMaizeSilage:
617  done = m_omaizesilage->Do( this, ev->m_field, ev );
618  break;
620  done = m_winterrapestrigling->Do( this, ev->m_field, ev );
621  break;
623  done = m_winterryestrigling->Do( this, ev->m_field, ev );
624  break;
626  done = m_winterbarleystrigling->Do( this, ev->m_field, ev );
627  break;
629  done = m_fieldpeasstrigling->Do( this, ev->m_field, ev );
630  break;
632  done = m_springbarleypeaclovergrassstrigling->Do( this, ev->m_field, ev );
633  break;
634  case tov_PlantNursery:
635  // uses youngforest management because this effectively does nothing, but stops the crop management creating looping error
636  case tov_YoungForest:
637  done = m_youngforest->Do(this, ev->m_field, ev);
638  break;
640  done = m_norwegianpotatoes->Do(this, ev->m_field, ev);
641  break;
642  case tov_NorwegianOats:
643  done = m_norwegianoats->Do(this, ev->m_field, ev);
644  break;
646  done = m_norwegianspringbarley->Do(this, ev->m_field, ev);
647  break;
648 
649  case tov_PLWinterWheat:
650  done = m_plwinterwheat->Do(this, ev->m_field, ev);
651  break;
652  case tov_PLWinterRape:
653  done = m_plwinterrape->Do(this, ev->m_field, ev);
654  break;
655  case tov_PLWinterBarley:
656  done = m_plwinterbarley->Do(this, ev->m_field, ev);
657  break;
659  done = m_plwintertriticale->Do(this, ev->m_field, ev);
660  break;
661  case tov_PLWinterRye:
662  done = m_plwinterrye->Do(this, ev->m_field, ev);
663  break;
664  case tov_PLSpringWheat:
665  done = m_plspringwheat->Do(this, ev->m_field, ev);
666  break;
667  case tov_PLSpringBarley:
668  done = m_plspringbarley->Do(this, ev->m_field, ev);
669  break;
670  case tov_PLMaize:
671  done = m_plmaize->Do(this, ev->m_field, ev);
672  break;
673  case tov_PLMaizeSilage:
674  done = m_plmaizesilage->Do(this, ev->m_field, ev);
675  break;
676  case tov_PLPotatoes:
677  done = m_plpotatoes->Do(this, ev->m_field, ev);
678  break;
679  case tov_PLBeet:
680  done = m_plbeet->Do(this, ev->m_field, ev);
681  break;
683  done = m_plfodderlucerne1->Do(this, ev->m_field, ev);
684  break;
686  done = m_plfodderlucerne2->Do(this, ev->m_field, ev);
687  break;
688  case tov_PLCarrots:
689  done = m_plcarrots->Do(this, ev->m_field, ev);
690  break;
692  done = m_plspringbarleyspr->Do(this, ev->m_field, ev);
693  break;
695  done = m_plwinterwheatlate->Do(this, ev->m_field, ev);
696  break;
697  case tov_PLBeetSpr:
698  done = m_plbeetspr->Do(this, ev->m_field, ev);
699  break;
700  case tov_PLBeans:
701  done = m_plbeans->Do(this, ev->m_field, ev);
702  break;
703 
704  case tov_NLBeet:
705  done = m_nlbeet->Do(this, ev->m_field, ev);
706  break;
707  case tov_NLCarrots:
708  done = m_nlcarrots->Do(this, ev->m_field, ev);
709  break;
710  case tov_NLMaize:
711  done = m_nlmaize->Do(this, ev->m_field, ev);
712  break;
713  case tov_NLPotatoes:
714  done = m_nlpotatoes->Do(this, ev->m_field, ev);
715  break;
716  case tov_NLSpringBarley:
717  done = m_nlspringbarley->Do(this, ev->m_field, ev);
718  break;
719  case tov_NLWinterWheat:
720  done = m_nlwinterwheat->Do(this, ev->m_field, ev);
721  break;
722  case tov_NLCabbage:
723  done = m_nlcabbage->Do(this, ev->m_field, ev);
724  break;
725  case tov_NLTulips:
726  done = m_nltulips->Do(this, ev->m_field, ev);
727  break;
728  case tov_NLGrassGrazed1:
729  done = m_nlgrassgrazed1->Do(this, ev->m_field, ev);
730  break;
732  done = m_nlgrassgrazed1spring->Do(this, ev->m_field, ev);
733  break;
734  case tov_NLGrassGrazed2:
735  done = m_nlgrassgrazed2->Do(this, ev->m_field, ev);
736  break;
738  done = m_nlgrassgrazedlast->Do(this, ev->m_field, ev);
739  break;
741  done = m_nlpermanentgrassgrazed->Do(this, ev->m_field, ev);
742  break;
743  case tov_NLBeetSpring:
744  done = m_nlbeetspring->Do(this, ev->m_field, ev);
745  break;
746  case tov_NLCarrotsSpring:
747  done = m_nlcarrotsspring->Do(this, ev->m_field, ev);
748  break;
749  case tov_NLMaizeSpring:
750  done = m_nlmaizespring->Do(this, ev->m_field, ev);
751  break;
753  done = m_nlpotatoesspring->Do(this, ev->m_field, ev);
754  break;
756  done = m_nlspringbarleyspring->Do(this, ev->m_field, ev);
757  break;
758  case tov_NLCabbageSpring:
759  done = m_nlcabbagespring->Do(this, ev->m_field, ev);
760  break;
761  case tov_NLCatchPeaCrop:
762  done = m_nlcatchpeacrop->Do(this, ev->m_field, ev);
763  break;
764 
766  done = m_dummycroppesttesting->Do(this, ev->m_field, ev);
767  break;
768 
769  case tov_Lawn:
770  // No current actions
771  done = true;
772  break;
773  /* case tov_OFirstYearDanger: done = m_ofirstyeardanger->Do( this, ev->m_field, ev ); break; */
774  default:
775  char veg_type[ 20 ];
776  sprintf( veg_type, "%d", ev->m_event );
777  g_msg->Warn( WARN_FILE, "Farm::LeSwitch(): ""Unknown crop type: ", veg_type );
778  exit( 1 );
779 
780  }
781  return done;
782 }
783 
784 
789 void Farm::AddNewEvent( TTypesOfVegetation a_event, long a_date, LE * a_field, int a_todo, long a_run, bool a_lock,
790  int a_start, bool a_first_year, TTypesOfVegetation a_crop ) {
791  FarmEvent * ev = new FarmEvent( a_event, a_field, a_todo, a_run, a_lock, a_start, a_first_year, a_crop );
792  m_queue.Push( ev, a_date );
793 }
794 
795 
800 bool Farm::DoIt( double a_probability ) {
801  return (g_rand_uni() < (a_probability/100.0));
802 }
803 
808 bool Farm::DoIt_prob(double a_probability) {
809  return (g_rand_uni() < a_probability);
810 }
811 
816 void Farm::ReadRotation(std::string str)
817 {
818  ifstream ifile;
819  ifile.open(str.c_str(),ios::in);
820  if ( !ifile.is_open() ) {
821  g_msg->Warn( "Cannot open file: ", str.c_str() );
822  exit( 1 );
823  }
824  int nocrops;
825  ifile >> nocrops;
826  m_rotation.resize( nocrops );
827  std::string cropref;
828  for ( int i = 0; i < nocrops; i++ ) {
829  ifile >> cropref;
831  m_rotation[ i ] = tov;
832  }
833  ifile.close();
834 }
835 
840  if ( ev->m_field->GetMgtLoopDetectDate() == g_date->Date() ) {
841  // The last crop managment plan stopped on the same day as
842  // it was started.
843 
844  // Bump loop counter.
845  ev->m_field->SetMgtLoopDetectCount( ev->m_field->GetMgtLoopDetectCount() + 1 );
846 
847  if ( ev->m_field->GetMgtLoopDetectCount() > ( long )( m_rotation.size() + 2 ) ) {
848  // We have a loop.
849  char errornum[ 20 ];
850  sprintf( errornum, "%d", m_farmtype );
851  g_msg->Warn( WARN_BUG, "Rotation management loop detected in farmtype ", errornum );
852  exit( 1 );
853  }
854  } else {
855  ev->m_field->SetMgtLoopDetectCount( 0 );
856  }
857 }
858 
859 
864 int Farm::GetNextCropStartDate( LE * a_field, TTypesOfVegetation & a_curr_veg ) {
865  TTypesOfVegetation l_tov2;
866 
867  if ( a_field->GetRotIndex() < 0 || g_farm_fixed_crop_enable.value() //|| g_farm_test_crop.value()
868  ) {
869  l_tov2 = a_curr_veg; // don't do it if no rotation
870  } else {
871  l_tov2 = m_rotation[ GetNextCropIndex( a_field->GetRotIndex() ) ];
872  }
873  a_curr_veg = l_tov2;
874  return GetFirstDate( l_tov2 );
875 }
876 
877 
882 void Farm::HandleEvents( void ) {
883  if ( m_queue.Empty() )
884  return;
885 
886  LowPriPair < FarmEvent * > pair = m_queue.Bottom();
887  FarmEvent * ev = pair.m_element;
888  while ( pair.m_pri <= g_date->Date() ) {
889  m_queue.Pop();
891  if ( LeSwitch( ev ) ) {
892  // This crop management plan has terminated.
893 
894  // First check for an infinite loop in the rotation scheme,
895  // ie. a scenario where all crops decide not to run given
896  // the date.
897  CheckRotationManagementLoop( ev );
898 
899  // Outdate any remaining events for this field.
900  ev->m_field->BumpRunNum();
901 
902  // Crop treatment done, select and initiate new crop if in rotation.
903  TTypesOfVegetation new_veg = ev->m_field->GetVegType();
904 
905  if ( ev->m_field->GetRotIndex() >= 0 ) {
906  int new_index = GetNextCropIndex( ev->m_field->GetRotIndex() );
907  new_veg = m_rotation[ new_index ];
908  // Running in fixed crop mode?
911  }
913  ev->m_field->SetRotIndex( new_index );
915  ev->m_field->SetVegType(new_veg, tov_Undefined);
916  }
917 
918  // Reset the event list for this field.
919  ev->m_field->ResetTrace();
920  // Reset event timeout counter.
921  ev->m_field->SetVegStore( 0 );
922 
923  // The next bit simply determines the start date of the next crop in
924  // the rotation and passes this to the start crop event.
925  // The crop is responsible for raising an error if the next crop is
926  // not possible or otherwise handling the problem
927 
928  // 19/5-2003: Note: This code was moved out into a dedicated
929  // method of the Farm class, GetNextCropStartDate(), as precisely
930  // the same piece of code needs to be run during initialization of
931  // farm management.
932  TTypesOfVegetation l_tov = new_veg;
933  int l_nextcropstartdate = GetNextCropStartDate( ev->m_field, l_tov );
934 
935  // Create 'start' event for today and put it on the queue.
936  AddNewEvent( new_veg, g_date->Date(), ev->m_field, PROG_START, ev->m_field->GetRunNum(), false, l_nextcropstartdate, false, l_tov );
937 
938  // Set starting date for rotation mgmt loop detection.
939  ev->m_field->SetMgtLoopDetectDate( g_date->Date() );
940  }
941 
942  delete ev;
943 
944  if ( m_queue.Empty() )
945  return;
946  pair = m_queue.Bottom();
947  ev = pair.m_element;
948  }
949 }
950 
951 
953  if ( m_queue.Empty() )
954  return;
955 
956  LowPriPair < FarmEvent * > pair = m_queue.Bottom();
957  FarmEvent * ev = pair.m_element;
958  while ( pair.m_pri <= g_date->Date() ) {
959  m_queue.Pop();
960 
961  if ( LeSwitch( ev ) ) {
962  // This crop management plan has terminated.
963 
964  // First check for an infinite loop in the rotation scheme,
965  // ie. a scenario where all crops decide not to run given
966  // the date.
967  CheckRotationManagementLoop( ev );
968 
969  // Outdate any remaining events for this field.
970  ev->m_field->BumpRunNum();
971 
972  // Crop treatment done, select and initiate new crop if in rotation.
973  TTypesOfVegetation new_veg = ev->m_field->GetVegType();
974 
975  if ( ev->m_field->GetRotIndex() >= 0 ) {
976  int new_index = GetNextCropIndex( ev->m_field->GetRotIndex() );
977  new_veg = m_rotation[ new_index ];
978  // Running in fixed crop mode?
981  }
982  /*
983  if ( g_farm_test_crop.value() ) {
984  new_veg = g_letype->TranslateVegTypes( g_farm_test_crop_type.value() );
985  }
986  */
987  ev->m_field->SetRotIndex( new_index );
988  ev->m_field->SetVegType( new_veg, tov_Undefined );
989  // ***CJT*** Testing removal 3/2/2015 ev->m_field->ForceGrowthTest();
990  }
991 
992 
993  //------------05.03.12 AM - tell a field the crop has changed - here the OptimisingFarm part---------------------------------------
994  if(!cfg_OptimiseBedriftsmodelCrops.value()){ //don't do this if you simulate the bedriftsmodel (original farm optimization model) crops
995  //switch the previous crop (if it is still there) to position 1 in an array m_CropDataStorage; put a new crop at position 0
996  VegElement * pf = dynamic_cast<VegElement*>(ev->m_field);
997  if(pf->Get_taken(0)){ //there is a crop at position 0 - so need to copy it to position 1 and clear all values at position 0
998  if(pf->Get_taken(1)){ //problem - we have 3rd crop when two previous crops were not calculated yet - it shouldn't happen!
999  char error_num[ 20 ];
1000  sprintf( error_num, "%d", new_veg );
1001  g_msg->Warn( WARN_FILE, "Farm::HandleEvents(): there is 3rd crop starting when 2 previous were not calculated yet, the 3rd crop is", error_num );
1002  exit( 1 );
1003  }
1004  pf->Set_CropDataStorage(1, pf->Get_CropDataStorage(0)); //copy the content of a struct at position 0 of the m_CropDataStorage array to position 1
1005  pf->Set_taken(true, 1); //mark the struct at position 1 as taken by a crop
1006  pf->Clean_CropDataStorage(0); //clear struct at position 0
1007 
1008  }
1009  //now save the new crop at position zero - whether there was a crop here or not
1010  pf->Clean_CropDataStorage(0); //clear struct at position 0 //do it cause the previous crop's operations could have been saved here - if there was some time between accoutning and start of this new crop
1011  pf->Set_taken(true, 0); // the new crop is at position 0
1012  pf->Set_tov_type(new_veg, 0); //save the tov_type of a new crop
1013  pf->Set_area_in_crop_data(pf->GetArea());
1014  }
1015  //---------------------end 05.03.13----------------------------------------------------------------
1016 
1017 
1018  // Reset the event list for this field.
1019  ev->m_field->ResetTrace();
1020  // Reset event timeout counter.
1021  ev->m_field->SetVegStore( 0 );
1022 
1023  // The next bit simply determines the start date of the next crop in
1024  // the rotation and passes this to the start crop event.
1025  // The crop is responsible for raising an error if the next crop is
1026  // not possible or otherwise handling the problem
1027 
1028  // 19/5-2003: Note: This code was moved out into a dedicated
1029  // method of the Farm class, GetNextCropStartDate(), as precisely
1030  // the same piece of code needs to be run during initialization of
1031  // farm management.
1032  TTypesOfVegetation l_tov = new_veg;
1033  int l_nextcropstartdate = GetNextCropStartDate( ev->m_field, l_tov );
1034 
1035  // Create 'start' event for today and put it on the queue.
1036  AddNewEvent( new_veg, g_date->Date(), ev->m_field, PROG_START, ev->m_field->GetRunNum(), false, l_nextcropstartdate, false, l_tov );
1037 
1038  // Set starting date for rotation mgmt loop detection.
1039  ev->m_field->SetMgtLoopDetectDate( g_date->Date() );
1040  }
1041 
1042  delete ev;
1043 
1044  if ( m_queue.Empty() )
1045  return;
1046  pair = m_queue.Bottom();
1047  ev = pair.m_element;
1048  }
1049 }
1050 
1051 
1052 
1053 
1058 Farm::Farm( FarmManager* a_manager )
1059 {
1060  m_OurManager = a_manager;
1061  m_carrots = new Carrots;
1062  m_broadbeans = new BroadBeans;
1063  m_CGG1 = new CloverGrassGrazed1;
1064  m_CGG2 = new CloverGrassGrazed2;
1065  m_fieldpeas = new FieldPeas;
1066  m_fieldpeassilage = new FieldPeasSilage;
1067  m_fodderbeet = new Fodderbeet;
1068  m_sugarbeet = new Sugarbeet;
1069  m_ofodderbeet = new OFodderbeet;
1070  m_foddergrass = new FodderGrass;
1071  m_maize = new Maize;
1072  m_maizesilage = new MaizeSilage;
1073  m_omaizesilage = new OMaizeSilage;
1074  m_OBarleyPCG = new OBarleyPeaCloverGrass;
1075  m_ocarrots = new OCarrots;
1076  m_OCGG1 = new OCloverGrassGrazed1;
1077  m_OCGG2 = new OCloverGrassGrazed2;
1078  m_OCGS1 = new OCloverGrassSilage1;
1079  m_ofieldpeas = new OFieldPeas;
1080  m_ofieldpeassilage = new OFieldPeasSilage;
1081  m_ofirstyeardanger = new OFirstYearDanger;
1082  m_ograzingpigs = new OGrazingPigs;
1083  m_orchardcrop = new OrchardCrop;
1084  m_oats = new Oats;
1085  m_ooats = new OOats;
1086  m_opermgrassgrazed = new OPermanentGrassGrazed;
1087  m_opotatoes = new OPotatoes;
1088  m_oseedgrass1 = new OSeedGrass1;
1089  m_oseedgrass2 = new OSeedGrass2;
1090  m_ospringbarley = new OSpringBarley;
1091  m_osbarleysilage = new OSBarleySilage;
1092  m_ospringbarleyext = new OSpringBarleyExt;
1093  m_ospringbarleypigs = new OSpringBarleyPigs;
1094  m_owinterbarley = new OWinterBarley;
1095  m_owinterbarleyext = new OWinterBarleyExt;
1096  m_owinterrape = new OWinterRape;
1097  m_owinterrye = new OWinterRye;
1098  m_owinterwheat = new OWinterWheat;
1099  m_owinterwheatundersown = new OWinterWheatUndersown;
1100  m_owinterwheatundersownext = new OWinterWheatUndersownExt;
1101  m_permanentsetaside = new PermanentSetAside;
1102  m_permgrassgrazed = new PermanentGrassGrazed;
1103  m_permgrasslowyield = new PermanentGrassLowYield;
1104  m_permgrasstussocky = new PermanentGrassTussocky;
1105  m_potatoes = new Potatoes;
1106  m_potatoesindustry = new PotatoesIndustry;
1107  m_sbarleyclovergrass = new SpringBarleyCloverGrass;
1108  m_seedgrass1 = new SeedGrass1;
1109  m_seedgrass2 = new SeedGrass2;
1110  m_setaside = new SetAside;
1111  m_springbarley = new SpringBarley;
1112  m_springbarleyspr = new SpringBarleySpr;
1113  m_springbarleyptreatment = new SpringBarleyPTreatment;
1114  m_springbarleyskmanagement = new SpringBarleySKManagement;
1115  m_springbarleyseed = new SpringBarleySeed;
1116  m_springbarleysilage = new SpringBarleySilage;
1117  m_springrape = new SpringRape;
1118  m_triticale = new Triticale;
1119  m_otriticale = new OTriticale;
1120  m_winterbarley = new WinterBarley;
1121  m_winterrape = new WinterRape;
1122  m_winterrye = new WinterRye;
1123  m_winterwheat = new WinterWheat;
1124  m_wwheatpcontrol = new WWheatPControl;
1125  m_wwheatptoxiccontrol = new WWheatPToxicControl;
1126  m_wwheatptreatment = new WWheatPTreatment;
1127  m_agrochemindustrycereal = new AgroChemIndustryCereal;
1128  m_winterwheatstrigling = new WinterWheatStrigling;
1129  m_winterwheatstriglingsingle = new WinterWheatStriglingSingle;
1130  m_winterwheatstriglingculm = new WinterWheatStriglingCulm;
1131  m_springbarleyclovergrassstrigling = new SpringBarleyCloverGrassStrigling;
1132  m_springbarleystrigling = new SpringBarleyStrigling;
1133  m_springbarleystriglingsingle = new SpringBarleyStriglingSingle;
1134  m_springbarleystriglingculm = new SpringBarleyStriglingCulm;
1135  m_maizestrigling = new MaizeStrigling;
1136  m_winterrapestrigling = new WinterRapeStrigling;
1137  m_winterryestrigling = new WinterRyeStrigling;
1138  m_winterbarleystrigling = new WinterBarleyStrigling;
1139  m_fieldpeasstrigling = new FieldPeasStrigling;
1140  m_springbarleypeaclovergrassstrigling = new SpringBarleyPeaCloverGrassStrigling;
1141  m_youngforest = new YoungForestCrop;
1142  m_norwegianpotatoes = new NorwegianPotatoes;
1143  m_norwegianoats = new NorwegianOats;
1144  m_norwegianspringbarley = new NorwegianSpringBarley;
1145  m_plwinterwheat = new PLWinterWheat;
1146  m_plwinterrape = new PLWinterRape;
1147  m_plwinterbarley = new PLWinterBarley;
1148  m_plwintertriticale = new PLWinterTriticale;
1149  m_plwinterrye = new PLWinterRye;
1150  m_plspringwheat = new PLSpringWheat;
1151  m_plspringbarley = new PLSpringBarley;
1152  m_plmaize = new PLMaize;
1153  m_plmaizesilage = new PLMaizeSilage;
1154  m_plpotatoes = new PLPotatoes;
1155  m_plbeet = new PLBeet;
1156  m_plfodderlucerne1 = new PLFodderLucerne1;
1157  m_plfodderlucerne2 = new PLFodderLucerne2;
1158  m_plcarrots = new PLCarrots;
1159  m_plspringbarleyspr = new PLSpringBarleySpr;
1160  m_plwinterwheatlate = new PLWinterWheatLate;
1161  m_plbeetspr = new PLBeetSpr;
1162  m_plbeans = new PLBeans;
1163 
1164  m_nlbeet = new NLBeet;
1165  m_nlcarrots = new NLCarrots;
1166  m_nlmaize = new NLMaize;
1167  m_nlpotatoes = new NLPotatoes;
1168  m_nlspringbarley = new NLSpringBarley;
1169  m_nlwinterwheat = new NLWinterWheat;
1170  m_nlcabbage = new NLCabbage;
1171  m_nltulips = new NLTulips;
1172  m_nlgrassgrazed1 = new NLGrassGrazed1;
1173  m_nlgrassgrazed1spring = new NLGrassGrazed1Spring;
1174  m_nlgrassgrazed2 = new NLGrassGrazed2;
1175  m_nlgrassgrazedlast = new NLGrassGrazedLast;
1176  m_nlpermanentgrassgrazed = new NLPermanentGrassGrazed;
1177  m_nlbeetspring = new NLBeetSpring;
1178  m_nlcarrotsspring = new NLCarrotsSpring;
1179  m_nlmaizespring = new NLMaizeSpring;
1180  m_nlpotatoesspring = new NLPotatoesSpring;
1181  m_nlspringbarleyspring = new NLSpringBarleySpring;
1182  m_nlcabbagespring = new NLCabbageSpring;
1183  m_nlcatchpeacrop = new NLCatchPeaCrop;
1184 
1185  m_dummycroppesttesting = new DummyCropPestTesting;
1186 
1187  m_rotation_sync_index = -1;
1188  // Defaults that need to be overridden when necessary
1189  m_stockfarmer = false;
1190  m_intensity = 0;
1191  m_HuntersList.resize(0); // Set the number of hunters to zero at the start.
1192 }
1193 
1194 
1200  delete m_carrots;
1201  delete m_broadbeans;
1202  delete m_CGG2;
1203  delete m_CGG1;
1204  delete m_fieldpeas;
1205  delete m_fieldpeassilage;
1206  delete m_fodderbeet;
1207  delete m_sugarbeet;
1208  delete m_ofodderbeet;
1209  delete m_foddergrass;
1210  delete m_maizesilage;
1211  delete m_omaizesilage;
1212  delete m_maize;
1213  delete m_ocarrots;
1214  delete m_OCGG1;
1215  delete m_OCGG2;
1216  delete m_OCGS1;
1217  delete m_ofieldpeas;
1218  delete m_ofieldpeassilage;
1219  delete m_ofirstyeardanger;
1220  delete m_ograzingpigs;
1221  delete m_orchardcrop;
1222  delete m_ooats;
1223  delete m_oats;
1224  delete m_opermgrassgrazed;
1225  delete m_opotatoes;
1226  delete m_ospringbarley;
1227  delete m_ospringbarleyext;
1228  delete m_osbarleysilage;
1229  delete m_ospringbarleypigs;
1230  delete m_owinterbarley;
1231  delete m_owinterbarleyext;
1232  delete m_owinterrape;
1233  delete m_owinterrye;
1234  delete m_owinterwheatundersown;
1235  delete m_owinterwheatundersownext;
1236  delete m_OBarleyPCG;
1237  delete m_permanentsetaside;
1238  delete m_permgrassgrazed;
1239  delete m_permgrasstussocky;
1240  delete m_permgrasslowyield;
1241  delete m_potatoes;
1242  delete m_potatoesindustry;
1243  delete m_sbarleyclovergrass;
1244  delete m_seedgrass2;
1245  delete m_seedgrass1;
1246  delete m_setaside;
1247  delete m_springbarley;
1248  delete m_springbarleyptreatment;
1249  delete m_springbarleyskmanagement;
1250  delete m_springbarleyseed;
1251  delete m_springrape;
1252  delete m_springbarleysilage;
1253  delete m_agrochemindustrycereal;
1254  delete m_triticale;
1255  delete m_winterbarley;
1256  delete m_winterrape;
1257  delete m_winterrye;
1258  delete m_winterwheat;
1259  delete m_wwheatpcontrol;
1260  delete m_wwheatptoxiccontrol;
1261  delete m_wwheatptreatment;
1262  delete m_winterwheatstrigling;
1263  delete m_winterwheatstriglingsingle;
1264  delete m_winterwheatstriglingculm;
1265  delete m_springbarleyclovergrassstrigling;
1266  delete m_springbarleystrigling;
1267  delete m_springbarleystriglingsingle;
1268  delete m_springbarleystriglingculm;
1269  delete m_maizestrigling;
1270  delete m_winterrapestrigling;
1271  delete m_winterryestrigling;
1272  delete m_winterbarleystrigling;
1273  delete m_fieldpeasstrigling;
1274  delete m_springbarleypeaclovergrassstrigling;
1275  delete m_youngforest;
1276  delete m_norwegianoats;
1277  delete m_norwegianspringbarley;
1278 
1279  delete m_plwinterwheat;
1280  delete m_plwinterrape;
1281  delete m_plwinterbarley;
1282  delete m_plwintertriticale;
1283  delete m_plwinterrye;
1284  delete m_plspringwheat;
1285  delete m_plspringbarley;
1286  delete m_plmaize;
1287  delete m_plmaizesilage;
1288  delete m_plpotatoes;
1289  delete m_plbeet;
1290  delete m_plfodderlucerne1;
1291  delete m_plfodderlucerne2;
1292  delete m_plcarrots;
1293  delete m_plspringbarleyspr;
1294  delete m_plwinterwheatlate;
1295  delete m_plbeetspr;
1296  delete m_plbeans;
1297 
1298  delete m_nlbeet;
1299  delete m_nlcarrots;
1300  delete m_nlmaize;
1301  delete m_nlpotatoes;
1302  delete m_nlspringbarley;
1303  delete m_nlwinterwheat;
1304  delete m_nlcabbage;
1305  delete m_nltulips;
1306  delete m_nlgrassgrazed1;
1307  delete m_nlgrassgrazed1spring;
1308  delete m_nlgrassgrazed2;
1309  delete m_nlgrassgrazedlast;
1310  delete m_nlpermanentgrassgrazed;
1311  delete m_nlbeetspring;
1312  delete m_nlcarrotsspring;
1313  delete m_nlmaizespring;
1314  delete m_nlpotatoesspring;
1315  delete m_nlspringbarleyspring;
1316  delete m_nlcabbagespring;
1317  delete m_nlcatchpeacrop;
1318 
1319  delete m_dummycroppesttesting;
1320 
1322 
1323  while (!m_queue.Empty()) {
1324  pair = m_queue.Bottom();
1325  m_queue.Pop();
1326  delete pair.m_element;
1327  }
1328 }
1329 
1332  int area = 0;
1333  for (unsigned int i = 0; i < m_fields.size(); i++) {
1334  if (m_fields[i]->GetElementType() == tole_Field) area += (int)m_fields[i]->GetArea();
1335  }
1336  return area;
1337 }
1338 
1341  int area = 0;
1342  for (unsigned int i = 0; i < m_fields.size(); i++)
1343  {
1344  area += (int)m_fields[i]->GetArea();
1345  }
1346  return area;
1347 }
1348 
1351  double area = 0;
1352  for ( unsigned int i = 0; i < m_fields.size(); i++ ) {
1353  if (m_fields[i]->GetElementType()==tole_Field) area += m_fields[i]->GetArea();
1354  }
1355  return area;
1356 }
1357 
1359 int Farm::GetNoOpenFields(int a_openness)
1360 {
1361  int num = 0;
1362  for (unsigned int i = 0; i < m_fields.size(); i++) {
1363  if (m_fields[i]->GetOpenness() > a_openness) num++;
1364  }
1365  return num;
1366 }
1367 
1369 int Farm::GetAreaOpenFields(int a_openness)
1370 {
1371  int area = 0;
1372  for (unsigned int i = 0; i < m_fields.size(); i++) {
1373  if (m_fields[i]->GetOpenness() > a_openness) area += int(m_fields[i]->GetArea());
1374  }
1375  return area;
1376 }
1377 
1386  // If g_farm_fixed_rotation, then determine the first
1387  // crop number in the rotation rotation number.
1389 
1391  // We are running all the farms synchronized, so
1392  // simply set the first crop to run on all farm fields.
1393  return 0;
1394  }
1395 
1396  // Each farm runs its fields sync'ed but independently from
1397  // the other farmers.
1398 
1399  // Determine if this farm has selected its own start index
1400  // and set it if not. m_rotation_sync_index is initialized
1401  // to -1 by the Farm::Farm() constructor.
1402  if ( -1 == m_rotation_sync_index ) {
1403  m_rotation_sync_index = (int) (rand() % m_rotation.size());
1404  }
1405  // Return farm localized rotation index.
1406  return m_rotation_sync_index;
1407  }
1408 
1409  // Not synchronised, but we want to follow our rotation sequence, so check
1410  // if we have started this process, if not set the sync value.
1411  // afterwards just increment this.
1412  if ( -1 == m_rotation_sync_index ) {
1413  if (m_rotation.size() > 0) m_rotation_sync_index = (int)(rand() % m_rotation.size()); else m_rotation_sync_index = 0;
1414  }
1415  else m_rotation_sync_index = (int) ((m_rotation_sync_index+1) % m_rotation.size());
1416  return m_rotation_sync_index;
1417 }
1418 
1419 
1427 int Farm::GetNextCropIndex( int a_rot_index ) {
1429  // Rotation not enabled.
1430  return a_rot_index;
1431  }
1432 
1433  if ( a_rot_index == -1 )
1434  return -1;
1435 
1436  if ( ( unsigned int ) ( ++a_rot_index ) == m_rotation.size() ) //AM comm: the last crop was the last element of the vector - so go back to the element zero; otherwise just add 1 to the index
1437  a_rot_index = 0;
1438 
1439  return a_rot_index;
1440 }
1441 
1442 
1447 void Farm::AddField( LE * a_newfield ) {
1448  int i = (int) m_fields.size();
1449 
1450  m_fields.resize( i + 1 );
1451  m_fields[ i ] = a_newfield;
1452  // Must set the rot index to something other than -1, but identify it as not usefully set as yet.
1453  TTypesOfLandscapeElement ele = a_newfield->GetElementType();
1454  switch (ele) {
1456  case tole_YoungForest:
1457  case tole_PermPasture:
1460  case tole_Orchard:
1461  case tole_PlantNursery:
1462  m_fields[i]->SetRotIndex(-2);
1463  break;
1464  default:
1465  m_fields[ i ]->SetRotIndex(-1);
1466  }
1467 }
1468 
1473 void Farm::RemoveField( LE * a_field ) {
1474  int nf = (int) m_fields.size();
1475  for ( int i = 0; i < nf; i++ ) {
1476  if ( m_fields[ i ] == a_field ) {
1477  m_fields.erase( m_fields.begin() + i );
1478  return;
1479  }
1480  }
1481  // If we reach here there is something wrong because the field is not a
1482  // member of this farm
1483  g_msg->Warn( WARN_BUG, "Farm::RemoveField(LE* a_field): ""Unknown field! ", "" );
1484  exit( 1 );
1485 }
1486 
1487 
1488 void Farm::Assign_rotation(vector<TTypesOfVegetation>a_new_rotation) {
1489 
1490  m_rotation.clear();
1491  m_rotation = a_new_rotation;
1492 
1493 }
1494 
1500  // First we need to assign the permanent crops if any.
1501  if (m_PermCrops.size()>0) {
1502  // We have something to do
1503  for (int i=0; i<(int)m_PermCrops.size(); i++) {
1504  AssignPermanentCrop(m_PermCrops[i].Tov, m_PermCrops[i].Pct);
1505  }
1506  }
1508 }
1509 
1515  for ( unsigned int i = 0; i < m_fields.size(); i++ ) {
1516  int rot_index = m_fields[ i ]->GetRotIndex();
1518  // If the field has been designated as non-rotating and therefore already has its veg type, then skip it.
1519  if ( rot_index < -1 ) {
1520  // Check for any type of permanent element type with management plan.
1521  TTypesOfLandscapeElement ele = m_fields[ i ]->GetElementType();
1522  switch (ele) {
1524  new_veg = tov_PermanentGrassLowYield;
1525  break;
1526  case tole_YoungForest:
1527  new_veg = tov_YoungForest;
1528  break;
1529  case tole_PermPasture:
1530  new_veg = tov_PermanentGrassGrazed;
1531  break;
1533  new_veg = tov_PermanentGrassTussocky;
1534  break;
1536  new_veg = tov_PermanentSetaside;
1537  break;
1538  case tole_Orchard:
1539  new_veg = tov_OrchardCrop;
1540  break;
1541  case tole_PlantNursery:
1542  new_veg = tov_PlantNursery;
1543  break;
1544  default:
1545  if (rot_index != -4) {
1546  // Error
1547  g_msg->Warn("Unexpected negative value in Farm::InitiateManagement","");
1548  exit(0);
1549  }
1550  else
1551  {
1552  new_veg = m_fields[i]->GetVegType();
1553  }
1554  }
1555  }
1556  else {
1557  rot_index = GetFirstCropIndex( m_fields[ i ]->GetElementType() );
1558  new_veg = m_rotation[ rot_index ];
1559  }
1560  // Running in fixed crop mode?
1561  if ( g_farm_fixed_crop_enable.value() ) {
1562  int fv = g_farm_fixed_crop_type.value();
1563  new_veg = g_letype->TranslateVegTypes( fv );
1564  }
1565  m_fields[ i ]->SetVegType( new_veg, tov_Undefined );
1566  m_fields[ i ]->SetRotIndex( rot_index );
1567  m_fields[ i ]->SetGrowthPhase( janfirst );
1568  // Reset event timeout counter. We are now 800 days from
1569  // oblivion.
1570  long prog_start_date = g_date->Date();
1571  m_fields[ i ]->SetVegStore( 0 );
1572  TTypesOfVegetation l_tov = new_veg;
1573  int l_nextcropstartdate = GetNextCropStartDate( m_fields[ i ], l_tov );
1574  AddNewEvent( new_veg, prog_start_date, m_fields[ i ], PROG_START, 0, false, l_nextcropstartdate, true, l_tov );
1575  }
1576 }
1577 
1583  switch (a_tov2) {
1584  case tov_Carrots:
1585  return m_carrots->GetFirstDate();
1586  case tov_BroadBeans:
1587  return m_broadbeans->GetFirstDate();
1588  case tov_FodderGrass:
1589  return m_foddergrass->GetFirstDate();
1591  return m_CGG1->GetFirstDate();
1593  return m_CGG2->GetFirstDate();
1594  case tov_FieldPeas:
1595  return m_fieldpeas->GetFirstDate();
1596  case tov_FieldPeasSilage:
1597  return m_fieldpeassilage->GetFirstDate();
1598  case tov_FodderBeet:
1599  return m_fodderbeet->GetFirstDate();
1600  case tov_SugarBeet:
1601  return m_sugarbeet->GetFirstDate();
1602  case tov_OFodderBeet:
1603  return m_ofodderbeet->GetFirstDate();
1604  case tov_Maize:
1605  return m_maize->GetFirstDate();
1606  case tov_OMaizeSilage:
1607  return m_omaizesilage->GetFirstDate();
1608  case tov_MaizeSilage:
1609  return m_maizesilage->GetFirstDate();
1611  return m_OBarleyPCG->GetFirstDate();
1612  case tov_OCarrots:
1613  return m_ocarrots->GetFirstDate();
1615  return m_OCGG1->GetFirstDate();
1617  return m_OCGG2->GetFirstDate();
1619  return m_OCGS1->GetFirstDate();
1620  case tov_OFieldPeas:
1621  return m_ofieldpeas->GetFirstDate();
1622  case tov_OFirstYearDanger:
1623  return m_ofirstyeardanger->GetFirstDate();
1624  case tov_OGrazingPigs:
1625  return m_ograzingpigs->GetFirstDate();
1626  case tov_OrchardCrop:
1627  return m_orchardcrop->GetFirstDate();
1628  case tov_OOats:
1629  return m_ooats->GetFirstDate();
1630  case tov_Oats:
1631  return m_oats->GetFirstDate();
1633  return m_opermgrassgrazed->GetFirstDate();
1634  case tov_OPotatoes:
1635  return m_opotatoes->GetFirstDate();
1636  case tov_OSpringBarley:
1637  return m_ospringbarley->GetFirstDate();
1638  case tov_OSBarleySilage:
1639  return m_osbarleysilage->GetFirstDate();
1640  case tov_OSpringBarleyExt:
1641  return m_ospringbarleyext->GetFirstDate();
1642  case tov_OSpringBarleyPigs:
1643  return m_ospringbarleypigs->GetFirstDate();
1644  case tov_OWinterBarley:
1645  return m_owinterbarley->GetFirstDate();
1646  case tov_OWinterBarleyExt:
1647  return m_owinterbarleyext->GetFirstDate();
1648  case tov_OWinterRape:
1649  return m_owinterrape->GetFirstDate();
1650  case tov_OWinterRye:
1651  return m_owinterrye->GetFirstDate();
1653  return m_owinterwheatundersown->GetFirstDate();
1654  case tov_OWinterWheat:
1655  return m_owinterwheat->GetFirstDate();
1657  return m_owinterwheatundersownext->GetFirstDate();
1659  return m_permgrassgrazed->GetFirstDate();
1661  return m_permgrasslowyield->GetFirstDate();
1662  case tov_PermanentGrassTussocky: // Only used for tole_PermPastureTussocky
1663  return m_permgrasstussocky->GetFirstDate();
1664  case tov_PermanentSetaside:
1665  return m_permanentsetaside->GetFirstDate();
1666  case tov_Potatoes:
1667  return m_potatoes->GetFirstDate();
1668  case tov_SeedGrass1:
1669  return m_seedgrass1->GetFirstDate();
1670  case tov_SeedGrass2:
1671  return m_seedgrass2->GetFirstDate();
1672  case tov_Setaside:
1673  return m_setaside->GetFirstDate();
1674  case tov_SpringBarley:
1675  return m_springbarley->GetFirstDate();
1676  case tov_SpringBarleySpr:
1677  return m_springbarleyspr->GetFirstDate();
1679  return m_springbarleyptreatment->GetFirstDate();
1681  return m_springbarleyskmanagement->GetFirstDate();
1683  return m_sbarleyclovergrass->GetFirstDate();
1684  case tov_SpringBarleySeed:
1685  return m_springbarleyseed->GetFirstDate();
1687  return m_springbarleysilage->GetFirstDate();
1689  return m_springbarleystrigling->GetFirstDate();
1691  return m_springbarleystriglingsingle->GetFirstDate();
1693  return m_springbarleystriglingculm->GetFirstDate();
1694  case tov_SpringRape:
1695  return m_springrape->GetFirstDate();
1696  case tov_Triticale:
1697  return m_triticale->GetFirstDate();
1698  case tov_OTriticale:
1699  return m_otriticale->GetFirstDate();
1700  case tov_WinterBarley:
1701  return m_winterbarley->GetFirstDate();
1702  case tov_WinterRape:
1703  return m_winterrape->GetFirstDate();
1704  case tov_WinterRye:
1705  return m_winterrye->GetFirstDate();
1706  case tov_WinterWheat:
1707  return m_winterwheat->GetFirstDate();
1709  return m_winterwheatstrigling->GetFirstDate();
1711  return m_winterwheatstriglingsingle->GetFirstDate();
1713  return m_winterwheatstriglingculm->GetFirstDate();
1714  case tov_WWheatPControl:
1715  return m_wwheatpcontrol->GetFirstDate();
1717  return m_wwheatptoxiccontrol->GetFirstDate();
1718  case tov_WWheatPTreatment:
1719  return m_wwheatptreatment->GetFirstDate();
1721  return m_agrochemindustrycereal->GetFirstDate();
1722  case tov_YoungForest:
1723  return m_youngforest->GetFirstDate();
1724  case tov_NorwegianPotatoes:
1725  return m_norwegianpotatoes->GetFirstDate();
1726  case tov_NorwegianOats:
1727  return m_norwegianoats->GetFirstDate();
1729  return m_norwegianspringbarley->GetFirstDate();
1730 
1731  case tov_PLWinterWheat:
1732  return m_plwinterwheat->GetFirstDate();
1733  case tov_PLWinterRape:
1734  return m_plwinterrape->GetFirstDate();
1735  case tov_PLWinterBarley:
1736  return m_plwinterbarley->GetFirstDate();
1737  case tov_PLWinterTriticale:
1738  return m_plwintertriticale->GetFirstDate();
1739  case tov_PLWinterRye:
1740  return m_plwinterrye->GetFirstDate();
1741  case tov_PLSpringWheat:
1742  return m_plspringwheat->GetFirstDate();
1743  case tov_PLSpringBarley:
1744  return m_plspringbarley->GetFirstDate();
1745  case tov_PLMaize:
1746  return m_plmaize->GetFirstDate();
1747  case tov_PLMaizeSilage:
1748  return m_plmaizesilage->GetFirstDate();
1749  case tov_PLPotatoes:
1750  return m_plpotatoes->GetFirstDate();
1751  case tov_PLBeet:
1752  return m_plbeet->GetFirstDate();
1753  case tov_PLFodderLucerne1:
1754  return m_plfodderlucerne1->GetFirstDate();
1755  case tov_PLFodderLucerne2:
1756  return m_plfodderlucerne2->GetFirstDate();
1757  case tov_PLCarrots:
1758  return m_plcarrots->GetFirstDate();
1759  case tov_PLSpringBarleySpr:
1760  return m_plspringbarleyspr->GetFirstDate();
1761  case tov_PLWinterWheatLate:
1762  return m_plwinterwheatlate->GetFirstDate();
1763  case tov_PLBeetSpr:
1764  return m_plbeetspr->GetFirstDate();
1765  case tov_PLBeans:
1766  return m_plbeans->GetFirstDate();
1767 
1768  case tov_NLBeet:
1769  return m_nlbeet->GetFirstDate();
1770  case tov_NLCarrots:
1771  return m_nlcarrots->GetFirstDate();
1772  case tov_NLMaize:
1773  return m_nlmaize->GetFirstDate();
1774  case tov_NLPotatoes:
1775  return m_nlpotatoes->GetFirstDate();
1776  case tov_NLSpringBarley:
1777  return m_nlspringbarley->GetFirstDate();
1778  case tov_NLWinterWheat:
1779  return m_nlwinterwheat->GetFirstDate();
1780  case tov_NLCabbage:
1781  return m_nlcabbage->GetFirstDate();
1782  case tov_NLTulips:
1783  return m_nltulips->GetFirstDate();
1784  case tov_NLGrassGrazed1:
1785  return m_nlgrassgrazed1->GetFirstDate();
1787  return m_nlgrassgrazed1spring->GetFirstDate();
1788  case tov_NLGrassGrazed2:
1789  return m_nlgrassgrazed2->GetFirstDate();
1790  case tov_NLGrassGrazedLast:
1791  return m_nlgrassgrazedlast->GetFirstDate();
1793  return m_nlpermanentgrassgrazed->GetFirstDate();
1794  case tov_NLBeetSpring:
1795  return m_nlbeetspring->GetFirstDate();
1796  case tov_NLCarrotsSpring:
1797  return m_nlcarrotsspring->GetFirstDate();
1798  case tov_NLMaizeSpring:
1799  return m_nlmaizespring->GetFirstDate();
1800  case tov_NLPotatoesSpring:
1801  return m_nlpotatoesspring->GetFirstDate();
1803  return m_nlspringbarleyspring->GetFirstDate();
1804  case tov_NLCabbageSpring:
1805  return m_nlcabbagespring->GetFirstDate();
1806  case tov_NLCatchPeaCrop:
1807  return m_nlcatchpeacrop->GetFirstDate();
1808 
1810  return m_dummycroppesttesting->GetFirstDate();
1811 
1812  default:
1813  return 0;
1814  }
1815 }
1816 
1817 
1818 TTypesOfVegetation FarmManager::TranslateCropCodes( std::string& astr ) { //changed to farm manager - was a Farm function, 19.03.13
1819  // This simply checks through the list of legal crop names and returns
1820  // the correct tov type
1821 
1822  string str = astr;
1823 
1824  // Unfortunately switch cannot use string so the long way:
1825  if (str == "SpringBarley") return tov_SpringBarley;
1826  if (str == "SpringBarleySpr") return tov_SpringBarleySpr;
1827  if (str == "SpringBarleyPTreatment") return tov_SpringBarleyPTreatment;
1828  if (str == "WinterBarley") return tov_WinterBarley;
1829  if (str == "SpringWheat") return tov_SpringWheat;
1830  if (str == "WinterWheat") return tov_WinterWheat;
1831  if (str == "WinterRye") return tov_WinterRye;
1832  if (str == "OrchardCrop") return tov_OrchardCrop;
1833  if (str == "Oats") return tov_Oats;
1834  if (str == "OOats") return tov_OOats;
1835  if (str == "Triticale") return tov_Triticale;
1836  if (str == "OTriticale") return tov_OTriticale;
1837  if (str == "Maize") return tov_Maize;
1838  if (str == "MaizeSilage") return tov_MaizeSilage;
1839  if (str == "SpringBarleySeed") return tov_SpringBarleySeed;
1840  if (str == "OSpringRape") return tov_SpringRape;
1841  if (str == "SpringRape") return tov_SpringRape;
1842  if (str == "WinterRape") return tov_WinterRape;
1843  if (str == "BroadBeans") return tov_BroadBeans;
1844  if (str == "FieldPeas") return tov_FieldPeas;
1845  if (str == "FieldPeasSilage") return tov_FieldPeasSilage;
1846  if (str == "Setaside") return tov_Setaside;
1847  if (str == "PermanentSetaside") return tov_PermanentSetaside;
1848  if (str == "SugarBeet") return tov_SugarBeet;
1849  if (str == "FodderBeet") return tov_FodderBeet;
1850  if (str == "OFodderBeet") return tov_OFodderBeet;
1851  if (str == "FodderGrass") return tov_FodderGrass;
1852  if (str == "CloverGrassGrazed1") return tov_CloverGrassGrazed1;
1853  if (str == "PotatoesIndustry") return tov_PotatoesIndustry;
1854  if (str == "Potatoes") return tov_Potatoes;
1855  if (str == "SeedGrass1") return tov_SeedGrass1;
1856  if (str == "OWinterBarley") return tov_OWinterBarley;
1857  if (str == "OWinterBarleyExt") return tov_OWinterBarleyExt;
1858  if (str == "SpringBarleySilage") return tov_SpringBarleySilage;
1859  if (str == "OWinterRye") return tov_OWinterRye;
1860  if (str == "OFieldPeasSilage") return tov_OFieldPeasSilage;
1861  if (str == "SpringBarleyGrass") return tov_SpringBarleyGrass;
1862  if (str == "SpringBarleyCloverGrass") return tov_SpringBarleyCloverGrass;
1863  if (str == "OBarleyPeaCloverGrass") return tov_OBarleyPeaCloverGrass;
1864  if (str == "OWinterRape") return tov_OWinterRape;
1865  if (str == "PermanentGrassGrazed") return tov_PermanentGrassGrazed;
1866  if (str == "PermanentGrassLowYield") return tov_PermanentGrassLowYield;
1867  if (str == "PermanentGrassTussocky") return tov_PermanentGrassTussocky;
1868  if (str == "CloverGrassGrazed2") return tov_CloverGrassGrazed2;
1869  if (str == "SeedGrass2") return tov_SeedGrass2;
1870  if (str == "OSpringWheat") return tov_OSpringBarley;
1871  if (str == "OSpringBarley") return tov_OSpringBarley;
1872  if (str == "OSpringBarleyExt") return tov_OSpringBarleyExt;
1873  if (str == "OWinterWheat") return tov_OWinterWheat;
1874  if (str == "OWinterWheatUndersown") return tov_OWinterWheatUndersown;
1875  if (str == "OWinterWheatUndersownExt") return tov_OWinterWheatUndersownExt;
1876  if (str == "OOats") return tov_OOats;
1877  if (str == "OFieldPeas") return tov_OFieldPeas;
1878  if (str == "OCloverGrassGrazed1") return tov_OCloverGrassGrazed1;
1879  if (str == "OGrazingPigs") return tov_OGrazingPigs;
1880  if (str == "OCarrots") return tov_OCarrots;
1881  if (str == "Carrots") return tov_Carrots;
1882  if (str == "OPotatoes") return tov_OPotatoes;
1883  if (str == "OSeedGrass1") return tov_OSeedGrass1;
1884  if (str == "OSpringBarleyGrass") return tov_OSpringBarleyGrass;
1885  if (str == "OSpringBarleyClover") return tov_OSpringBarleyClover;
1886  if (str == "OPermanentGrassGrazed") return tov_OPermanentGrassGrazed;
1887  if (str == "OCloverGrassSilage1") return tov_OCloverGrassSilage1;
1888  if (str == "OCloverGrassGrazed2") return tov_OCloverGrassGrazed2;
1889  if (str == "OSeedGrass2") return tov_OSeedGrass2;
1890  if (str == "WWheatPControl") return tov_WWheatPControl;
1891  if (str == "WWheatPToxicControl") return tov_WWheatPToxicControl;
1892  if (str == "WWheatPTreatment") return tov_WWheatPTreatment;
1893  if (str == "AgroChemIndustryCereal") return tov_AgroChemIndustryCereal;
1894  if (str == "WinterWheatShort") return tov_WinterWheatShort;
1895  if (str == "WinterWheatStrigling") return tov_WinterWheatStrigling;
1896  if (str == "WinterWheatStriglingCulm") return tov_WinterWheatStriglingCulm;
1897  if (str == "WinterWheatStriglingSgl") return tov_WinterWheatStriglingSingle;
1898  if (str == "SpringBarleyCloverGrassStrigling") return tov_SpringBarleyCloverGrassStrigling;
1899  if (str == "SpringBarleyStrigling") return tov_SpringBarleyStrigling;
1900  if (str == "SpringBarleyStriglingSingle") return tov_SpringBarleyStriglingSingle;
1901  if (str == "SpringBarleyStriglingCulm") return tov_SpringBarleyStriglingCulm;
1902  if (str == "MaizeStrigling") return tov_MaizeStrigling;
1903  if (str == "WinterRapeStrigling") return tov_WinterRapeStrigling;
1904  if (str == "WinterRyeStrigling") return tov_WinterRyeStrigling;
1905  if (str == "WinterBarleyStrigling") return tov_WinterBarleyStrigling;
1906  if (str == "FieldPeasStrigling") return tov_FieldPeasStrigling;
1907  if (str == "SpringBarleyPeaCloverGrassStrigling") return tov_SpringBarleyPeaCloverGrassStrigling;
1908  if (str == "YoungForest") return tov_YoungForest;
1909  if (str == "OMaizeSilage") return tov_OMaizeSilage;
1910  if (str == "OSpringBarleySilage") return tov_OSBarleySilage;
1911  if (str == "OSpringBarleyPigs") return tov_OSpringBarleyPigs;
1912  if (str == "NorwegianPotatoes") return tov_NorwegianPotatoes;
1913  if (str == "NorwegianOats") return tov_NorwegianOats;
1914  if (str == "NorwegianSpringBarley") return tov_NorwegianSpringBarley;
1915  if (str == "PlantNursery") return tov_PlantNursery;
1916  if (str == "PLWinterWheat") return tov_PLWinterWheat;
1917  if (str == "PLWinterRape") return tov_PLWinterRape;
1918  if (str == "PLWinterBarley") return tov_PLWinterBarley;
1919  if (str == "PLWinterTriticale") return tov_PLWinterTriticale;
1920  if (str == "PLWinterRye") return tov_PLWinterRye;
1921  if (str == "PLSpringWheat") return tov_PLSpringWheat;
1922  if (str == "PLSpringBarley") return tov_PLSpringBarley;
1923  if (str == "PLMaize") return tov_PLMaize;
1924  if (str == "PLMaizeSilage") return tov_PLMaizeSilage;
1925  if (str == "PLPotatoes") return tov_PLPotatoes;
1926  if (str == "PLBeet") return tov_PLBeet;
1927  if (str == "PLFodderLucerne1") return tov_PLFodderLucerne1;
1928  if (str == "PLFodderLucerne2") return tov_PLFodderLucerne2;
1929  if (str == "PLCarrots") return tov_PLCarrots;
1930  if (str == "PLSpringBarleySpr") return tov_PLSpringBarleySpr;
1931  if (str == "PLWinterWheatLate") return tov_PLWinterWheatLate;
1932  if (str == "PLBeetSpr") return tov_PLBeetSpr;
1933  if (str == "PLBeans") return tov_PLBeans;
1934 
1935  if (str == "NLBeet") return tov_NLBeet;
1936  if (str == "NLCarrots") return tov_NLCarrots;
1937  if (str == "NLMaize") return tov_NLMaize;
1938  if (str == "NLPotatoes") return tov_NLPotatoes;
1939  if (str == "NLSpringBarley") return tov_NLSpringBarley;
1940  if (str == "NLWinterWheat") return tov_NLWinterWheat;
1941  if (str == "NLCabbage") return tov_NLCabbage;
1942  if (str == "NLTulips") return tov_NLTulips;
1943  if (str == "NLGrassGrazed1") return tov_NLGrassGrazed1;
1944  if (str == "NLGrassGrazed1Spring") return tov_NLGrassGrazed1Spring;
1945  if (str == "NLGrassGrazed2") return tov_NLGrassGrazed2;
1946  if (str == "NLGrassGrazedLast") return tov_NLGrassGrazedLast;
1947  if (str == "NLPermanentGrassGrazed") return tov_NLPermanentGrassGrazed;
1948  if (str == "NLBeetSpring") return tov_NLBeetSpring;
1949  if (str == "NLCarrotsSpring") return tov_NLCarrotsSpring;
1950  if (str == "NLMaizeSpring") return tov_NLMaizeSpring;
1951  if (str == "NLPotatoesSpring") return tov_NLPotatoesSpring;
1952  if (str == "NLSpringBarleySpring") return tov_NLSpringBarleySpring;
1953  if (str == "NLCabbageSpring") return tov_NLCabbageSpring;
1954  if (str == "NLCatchPeaCrop") return tov_NLCatchPeaCrop;
1955 
1956  if (str == "DummyCropPestTesting") return tov_DummyCropPestTesting;
1957 
1958  // No match so issue a warning and quit
1959  g_msg->Warn( WARN_FILE, "FarmManager::TranslateCropCodes():"" Unknown Crop Code ", str.c_str() );
1960  exit( 1 );
1961 }
1962 
1963 
1965 
1966  //create a text file with the farms
1967  ofstream ofile ("FarmTotalAreas_almass.txt", ios::out);
1968  ofile << "Farm no" << '\t' << "Area" << endl;
1969 
1970  //print each farms no and then the numbers of its neighbours
1971  for(int i=0; i<(int)m_farms.size(); i++){
1972  OptimisingFarm * opf_i;
1973  if(m_farms[i]->GetType() == tof_OptimisingFarm){ //take only optimising farms
1974  opf_i = dynamic_cast<OptimisingFarm*>(m_farms[i]);
1975  ofile << opf_i->Get_almass_no() << '\t';
1976  ofile << opf_i->GetArea() <<'\t';
1977  ofile << endl;
1978  }
1979  }
1980 }
1981 
1983 {
1985  m_stockfarmer = true;
1986  // Adjust as needed.
1987  m_rotation.resize( 9 );
1991  m_rotation[ 3 ] = tov_WinterWheat;
1995  m_rotation[ 7 ] = tov_Maize; // was FodderBeet until 23/12/03
1997 }
1998 
1999 
2001 {
2003  m_stockfarmer = true;
2004 
2005  // Adjust as needed.
2006  m_rotation.resize( 9 );
2007  m_rotation[ 0 ] = tov_WinterRape;
2008  m_rotation[ 1 ] = tov_WinterWheat;
2011  m_rotation[ 4 ] = tov_Setaside;
2012  m_rotation[ 5 ] = tov_FieldPeas;
2013  m_rotation[ 6 ] = tov_WinterWheat;
2014  m_rotation[ 7 ] = tov_WinterRye;
2016 }
2017 
2018 
2020 {
2022  m_stockfarmer = false;
2023 
2024  // Adjust as needed.
2025  m_rotation.resize( 9 );
2026  m_rotation[ 0 ] = tov_WinterRape;
2027  m_rotation[ 1 ] = tov_WinterWheat;
2030  m_rotation[ 4 ] = tov_Setaside;
2031  m_rotation[ 5 ] = tov_FieldPeas;
2032  m_rotation[ 6 ] = tov_WinterWheat;
2033  m_rotation[ 7 ] = tov_WinterRye;
2035 }
2036 
2037 
2038 OrganicCattle::OrganicCattle(FarmManager* a_manager) : Farm(a_manager) // 3
2039 {
2041  m_stockfarmer = true;
2042  ReadRotation("OrganicCattle.rot");
2043  }
2044 
2045 OrganicPig::OrganicPig(FarmManager* a_manager) : Farm(a_manager) // 4
2046 {
2048  m_stockfarmer = true;
2049  ReadRotation("OrganicPig.rot");
2050 }
2051 
2052 OrganicPlant::OrganicPlant(FarmManager* a_manager) : Farm(a_manager) // 5
2053 {
2055  m_stockfarmer = false;
2056  ReadRotation("OrganicPlant.rot");
2057 }
2058 
2060 {
2062  m_stockfarmer = false;
2063  m_rotation.resize( 1 );
2065 }
2066 
2068 {
2070  m_stockfarmer = false;
2071  m_rotation.resize( 1 );
2073 }
2074 
2076 {
2078  m_stockfarmer = false;
2079  // This farm type reads its rotation from a special file PesticideTrialTreatment.rot
2080  ReadRotation("PesticideTrialTreatment.rot");
2081 }
2082 
2084 {
2086  m_stockfarmer = true;
2087 
2088  m_rotation.resize( 6 );
2094  m_rotation[ 5 ] = tov_FodderBeet;
2095 }
2096 
2098 {
2100  m_stockfarmer = true;
2101  // Adjust as needed.
2102  m_rotation.resize( 9 );
2109  m_rotation[ 6 ] = tov_FodderBeet;
2112 }
2113 
2115 {
2117  m_stockfarmer = true;
2118 
2119  // Adjust as needed.
2120  m_rotation.resize( 3 );
2121  m_rotation[ 0 ] = tov_WinterRape;
2124  /* m_rotation[ 3] = tov_AgroChemIndustryCereal; m_rotation[ 4] = tov_Setaside; m_rotation[ 5] = tov_FieldPeas;
2125  m_rotation[ 6] = tov_AgroChemIndustryCereal; m_rotation[ 7] = tov_WinterRye; m_rotation[ 8] = tov_AgroChemIndustryCereal; */
2126 }
2127 
2128 
2129 
2131 {
2133  m_stockfarmer = false;
2134 
2135  // Adjust as needed.
2136  m_rotation.resize( 9 );
2137  m_rotation[ 0 ] = tov_Setaside;
2138  m_rotation[ 1 ] = tov_FieldPeas;
2140  m_rotation[ 3 ] = tov_WinterRye;
2142  m_rotation[ 5 ] = tov_WinterRape;
2146 }
2147 
2149 {
2151  m_stockfarmer = false;
2152 
2153  // Adjust as needed.
2154  m_rotation.resize( 36 );
2158  m_rotation[ 3 ] = tov_WinterWheat;
2162  m_rotation[ 7 ] = tov_FodderBeet;
2164  m_rotation[ 9 ] = tov_WinterRape;
2165  m_rotation[ 10 ] = tov_WinterWheat;
2166  m_rotation[ 11 ] = tov_SpringBarley;
2167  m_rotation[ 12 ] = tov_SpringBarley;
2168  m_rotation[ 13 ] = tov_Setaside;
2169  m_rotation[ 14 ] = tov_FieldPeas;
2170  m_rotation[ 15 ] = tov_WinterWheat;
2171  m_rotation[ 16 ] = tov_WinterRye;
2172  m_rotation[ 17 ] = tov_WinterBarley;
2173  m_rotation[ 18 ] = tov_WinterRape;
2174  m_rotation[ 19 ] = tov_WinterWheat;
2175  m_rotation[ 20 ] = tov_SpringBarley;
2176  m_rotation[ 21 ] = tov_SpringBarley;
2177  m_rotation[ 22 ] = tov_Setaside;
2178  m_rotation[ 23 ] = tov_FieldPeas;
2179  m_rotation[ 24 ] = tov_WinterWheat;
2180  m_rotation[ 25 ] = tov_WinterRye;
2181  m_rotation[ 26 ] = tov_WinterBarley;
2182  m_rotation[ 27 ] = tov_WinterRape;
2183  m_rotation[ 28 ] = tov_WinterWheat;
2184  m_rotation[ 29 ] = tov_SpringBarley;
2185  m_rotation[ 30 ] = tov_SpringBarley;
2186  m_rotation[ 31 ] = tov_Setaside;
2187  m_rotation[ 32 ] = tov_FieldPeas;
2188  m_rotation[ 33 ] = tov_WinterWheat;
2189  m_rotation[ 34 ] = tov_WinterRye;
2190  m_rotation[ 35 ] = tov_WinterBarley;
2191 }
2192 
2194 {
2196  m_stockfarmer = false;
2197 
2198  // Adjust as needed.
2199  m_rotation.resize( 17 );
2203  m_rotation[ 3 ] = tov_OWinterRape;
2204  m_rotation[ 4 ] = tov_OFieldPeas;
2210  m_rotation[ 10 ] = tov_OFieldPeas;
2213  m_rotation[ 13 ] = tov_Setaside;
2214  m_rotation[ 14 ] = tov_OFieldPeas;
2215  m_rotation[ 15 ] = tov_OWinterRye;
2216  m_rotation[ 16 ] = tov_OFieldPeas;
2217 }
2218 
2219 
2220 UserDefinedFarm1::UserDefinedFarm1(FarmManager* a_manager ) : Farm(a_manager) // 15
2221 {
2223  m_stockfarmer = true;
2224  // This farm type reads its rotation from a special file UserDefinedFarm1.rot
2225  ReadRotation("UserDefinedFarm1.rot");
2226  }
2227 
2228 UserDefinedFarm2::UserDefinedFarm2(FarmManager* a_manager ) : Farm(a_manager) // 15
2229 {
2231  m_stockfarmer = true;
2232  // This farm type reads its rotation from a special file UserDefinedFarm1.rot
2233  ReadRotation("UserDefinedFarm2.rot");
2234  }
2235 
2236 UserDefinedFarm3::UserDefinedFarm3(FarmManager* a_manager ) : Farm(a_manager) // 17
2237 {
2239  m_stockfarmer = true;
2240  // This farm type reads its rotation from a special file PesticideTrialTreatment.rot
2241  ReadRotation("UserDefinedFarm3.rot");
2242 }
2243 
2244 UserDefinedFarm4::UserDefinedFarm4(FarmManager* a_manager ) : Farm(a_manager) // 18
2245 {
2247  m_stockfarmer = true;
2248  // This farm type reads its rotation from a special file PesticideTrialTreatment.rot
2249  ReadRotation("UserDefinedFarm4.rot");
2250  }
2251 
2252 UserDefinedFarm5::UserDefinedFarm5(FarmManager* a_manager ) : Farm(a_manager) // 19
2253 {
2255  m_stockfarmer = true;
2256  // This farm type reads its rotation from a special file PesticideTrialTreatment.rot
2257  ReadRotation("UserDefinedFarm5.rot");
2258 }
2259 
2260 UserDefinedFarm6::UserDefinedFarm6(FarmManager* a_manager ) : Farm(a_manager) // 20
2261 {
2263  m_stockfarmer = true;
2264  // This farm type reads its rotation from a special file PesticideTrialTreatment.rot
2265  ReadRotation("UserDefinedFarm6.rot");
2266 }
2267 
2268 UserDefinedFarm7::UserDefinedFarm7(FarmManager* a_manager ) : Farm(a_manager) // 21
2269 {
2271  m_stockfarmer = true;
2272  // This farm type reads its rotation from a special file PesticideTrialTreatment.rot
2273  ReadRotation("UserDefinedFarm7.rot");
2274 }
2275 
2276 UserDefinedFarm8::UserDefinedFarm8(FarmManager* a_manager ) : Farm(a_manager) // 22
2277 {
2279  m_stockfarmer = true;
2280  // This farm type reads its rotation from a special file PesticideTrialTreatment.rot
2281  ReadRotation("UserDefinedFarm8.rot");
2282 }
2283 
2284 UserDefinedFarm9::UserDefinedFarm9(FarmManager* a_manager ) : Farm(a_manager) // 23
2285 {
2287  m_stockfarmer = false;
2288  // This farm type reads its rotation from a special file PesticideTrialTreatment.rot
2289  ReadRotation("UserDefinedFarm9.rot");
2290 }
2291 
2293 {
2295  m_stockfarmer = false;
2296  ReadRotation("UserDefinedFarm10.rot");
2297 }
2298 
2300 {
2302  m_stockfarmer = false;
2303  ReadRotation("UserDefinedFarm11.rot");
2304 }
2305 
2307 {
2309  m_stockfarmer = false;
2310  ReadRotation("UserDefinedFarm12.rot");
2311 }
2312 
2314 {
2316  m_stockfarmer = false;
2317  ReadRotation("UserDefinedFarm13.rot");
2318 }
2319 
2321 {
2323  m_stockfarmer = true;
2324  ReadRotation("UserDefinedFarm14.rot");
2325 }
2326 
2328 {
2330  m_stockfarmer = false;
2331  ReadRotation("UserDefinedFarm15.rot");
2332 }
2333 
2335 {
2337  m_stockfarmer = false;
2338  ReadRotation("UserDefinedFarm16.rot");
2339 }
2340 
2341 
2343 {
2345  m_stockfarmer = false;
2346  ReadRotation("UserDefinedFarm17.rot");
2347 }
2348 
2349 UserDefinedFarm::UserDefinedFarm( const char* fname, FarmManager* a_manager ) : Farm(a_manager) // Base class for the real ones
2350 {
2361  ifstream ifile;
2362  ifile.open(fname,ios::in);
2363  if (!ifile.is_open()) {
2364  g_msg->Warn( WARN_FILE, " Unable to open file ", fname );
2365  exit( 1 );
2366  }
2367  int input, intensity;
2368  // First entry - arable/stock
2369  // Second entry - farm intensity. Zero = default, 1 extensive, 2 very extensive
2370  ifile >> input >> intensity;
2371  if (input==1) m_stockfarmer = true; else m_stockfarmer = false;
2372  // Thrid entry - no permanent crops
2373  int permcrops;
2374  std::string cropref ="";
2375  ifile >> permcrops;
2376  // The problem here is that at the time when we reach this code there are no fields attached to the farm - so we need
2377  // to store this information - hence the vector of the vector of PermCropData
2378  PermCropData pcd;
2379  for (int i=0; i<permcrops; i++) {
2380  int pct;
2381  ifile >> cropref;
2383  ifile >> pct; // 0-100%
2384  pcd.Pct=pct;
2385  pcd.Tov=tov;
2386  m_PermCrops.push_back(pcd);
2387  }
2388  // 4th entry
2389  int nocrops;
2390  ifile >> nocrops;
2391  m_rotation.resize( nocrops );
2392  for ( int i = 0; i < nocrops; i++ ) {
2393  ifile >> cropref;
2395  m_rotation[ i ] = tov;
2396  }
2397  ifile.close();
2398 }
2399 
2402  // Assumes that m_fields has all the fields already in it, and those that are occupied by permanent tole types
2403  // are denoted by -2 or -4 in rotindex, -1 is unassigned - can't use enum because positive values have other meanings
2404 
2405  // Here we can save some time if we have to allocate all the fields to one permanent crop
2406  if (a_pct == 100)
2407  {
2408  for (auto cfi = m_fields.begin(); cfi != m_fields.end(); ++cfi)
2409  {
2410  // Set the field as non-rotating
2411  (*cfi)->SetRotIndex(-4);
2412  // Assign the crop, and weeds are assumed to be undefined
2413  (*cfi)->SetVegType(a_tov, tov_Undefined);
2414  }
2415  return;
2416  }
2417 
2418  tpct a_tpct;
2419  // create a copy of the field vector and call it fields_cpy
2420  vector<LE*> fields_cpy;
2421  fields_cpy.resize(m_fields.size());
2422  copy(m_fields.begin(), m_fields.end(), fields_cpy.begin());
2423  vector<tpct> pcts;
2424  double area = 0.0;
2425 
2426 
2427  // First get the areas of all fields and then convert these to percentages
2428  int sz = (int) fields_cpy.size();
2429  // loop through the fields vector and remove any fields already assigned to permanent crops
2430  for (int i = sz - 1; i >= 0; i--) {
2431  if (fields_cpy[i]->GetRotIndex() < -1) {
2432  fields_cpy.erase(fields_cpy.begin() + i);
2433  }
2434  }
2435  // sum up the area
2436  for (auto cfi = fields_cpy.begin(); cfi != fields_cpy.end(); ++cfi) area += (*cfi)->GetArea();
2437 
2438  // Here we can take action if we only have a single field
2439  int fnos = (int) fields_cpy.size();
2440  if (fnos<1) return; // No fields to allocate, jump out
2441  else if (fnos==1) {
2442  // Use the pct as the chance that our single field is assigned
2443  if (random(100)>=a_pct) return;
2444  else {
2445  // Add field by default
2446  fields_cpy[0]->SetRotIndex(-4);
2447  // Assign the crop
2448  fields_cpy[0]->SetVegType(a_tov, tov_Undefined);
2449  return;
2450  }
2451  }
2452  // By here we have more than one field to potentially allocate to
2453  for (int i=0; i<fnos; i++) {
2454  a_tpct.pct = (int) floor(0.5+((fields_cpy[i]->GetArea()/area)*100));
2455  a_tpct.index = i;
2456  pcts.push_back(a_tpct);
2457  }
2458  // We need to look for combinations of fields that are close to our target.
2459  // First we can sort the array and ignore any that are greater than pct
2460  sort (pcts.begin(), pcts.end(), CompPcts); // results in ordering on increasing pct
2461  // now remove all those with pct>target+10% to save loads of time in the inverse integer partition
2462  int index=-1;
2463  int ind=0;
2464  int apct=a_pct+10; // Lets assume we have a tolerance of 10%
2465  while ((index==-1) && (ind< (int)pcts.size())) {
2466  if (pcts[ind++].pct>apct) index=ind;
2467  }
2468  if (index!=-1) pcts.erase(pcts.begin()+index,pcts.end());
2469  // Now find the best combination of fields to get close to our target & set them
2470  int bits = InvIntPartition(&pcts,a_pct);
2471  int mask=1;
2472  ind = 0;
2473  int used=0;
2474  //double pctused = 0.0;
2475  double check = 0.0;
2476  for (int h=0; h< (int)pcts.size(); h++) check+=fields_cpy[pcts[h].index]->GetArea();
2477  while (bits>0) {
2478  if ((bits & mask) > 0) {
2479  // Set the field as non-rotating
2480  fields_cpy[pcts[ind].index]->SetRotIndex(-4);
2481  // Assign the crop
2482  fields_cpy[pcts[ind].index]->SetVegType(a_tov, tov_Undefined);
2483  used += (int) fields_cpy[pcts[ind].index]->GetArea();
2484  //pctused = used/area;
2485  bits -= mask;
2486  }
2487  mask = mask << 1;
2488  ind++;
2489  }
2490 }
2491 
2493 int Farm::InvIntPartition(vector<tpct>* items, int target){
2494  //Figure out how many bitmasks we need...
2495  //4 bits have a maximum value of 15, so we need 15 masks.
2496  //Calculated as:
2497  // (2 ^ ItemCount) - 1
2498  long long int sz = (long long int) items->size();
2499  if (sz>80) {
2500  // This is a warning that we did no consider all combinations of fields but 2^63 combinations should be enough :)
2501  g_msg->Warn("Too many potential fields in UserDefinedFarm::InvIntPartition: ",sz);
2502  g_msg->Warn("Farm Number: ",GetFarmNumber());
2503  sz = 63;
2504  }
2505  long int calcs = (1 << sz);
2506  //Spit out the corresponding calculation for each bitmask
2507  int sum;
2508  int found = 0;
2509  int diff = 100;
2510  for (long int i=1; i<calcs; i++) {
2511  //Get the items from our array that correspond to
2512  //the on bits in our mask
2513  sum = 0;
2514  int mask = 1;
2515  for (int bit=0; bit<sz; bit++) {
2516  if ((i & mask) > 0) {
2517  sum+=(*items)[bit].pct;
2518  }
2519  mask = mask << 1;
2520  }
2521 
2522  if (abs(sum-target) < diff ){
2523  found = i;
2524  diff = abs(sum-target);
2525  if (diff<1) break; //added 01.11.12 to prevent from checking all the combinations when the right one is found
2526  }
2527  }
2528  return found;
2529 }
2530 
2531 UserDefinedFarm18::UserDefinedFarm18( const char* fname, FarmManager* a_manager ) : UserDefinedFarm(fname, a_manager) // 32
2532 {
2534 }
2535 
2536 UserDefinedFarm19::UserDefinedFarm19( const char* fname, FarmManager* a_manager ) : UserDefinedFarm(fname, a_manager) // 33
2537 {
2539 }
2540 
2541 UserDefinedFarm20::UserDefinedFarm20( const char* fname, FarmManager* a_manager ) : UserDefinedFarm(fname, a_manager) // 34
2542 {
2544 }
2545 
2546 UserDefinedFarm21::UserDefinedFarm21( const char* fname, FarmManager* a_manager ) : UserDefinedFarm(fname, a_manager) // 35
2547 {
2549 }
2550 
2551 UserDefinedFarm22::UserDefinedFarm22( const char* fname, FarmManager* a_manager ) : UserDefinedFarm(fname, a_manager) // 36
2552 {
2554 }
2555 
2556 UserDefinedFarm23::UserDefinedFarm23( const char* fname, FarmManager* a_manager ) : UserDefinedFarm(fname, a_manager) // 37
2557 {
2559 }
2560 
2561 UserDefinedFarm24::UserDefinedFarm24( const char* fname, FarmManager* a_manager ) : UserDefinedFarm(fname, a_manager) // 38
2562 {
2564 }
2565 
2566 UserDefinedFarm25::UserDefinedFarm25( const char* fname, FarmManager* a_manager ) : UserDefinedFarm(fname, a_manager) // 39
2567 {
2569 }
2570 
2571 UserDefinedFarm26::UserDefinedFarm26( const char* fname, FarmManager* a_manager ) : UserDefinedFarm(fname, a_manager) // 40
2572 {
2574 }
2575 
2576 UserDefinedFarm27::UserDefinedFarm27( const char* fname, FarmManager* a_manager ) : UserDefinedFarm(fname, a_manager) // 41
2577 {
2579 }
2580 
2581 UserDefinedFarm28::UserDefinedFarm28( const char* fname, FarmManager* a_manager ) : UserDefinedFarm(fname, a_manager) // 42
2582 {
2584 }
2585 
2586 UserDefinedFarm29::UserDefinedFarm29( const char* fname, FarmManager* a_manager ) : UserDefinedFarm(fname, a_manager) // 43
2587 {
2589 }
2590 
2591 UserDefinedFarm30::UserDefinedFarm30( const char* fname, FarmManager* a_manager ) : UserDefinedFarm(fname, a_manager) // 44
2592 {
2594 }
2595 
2596 UserDefinedFarm31::UserDefinedFarm31( const char* fname, FarmManager* a_manager ) : UserDefinedFarm(fname, a_manager) // 45
2597 {
2599 }
2600 
2601 UserDefinedFarm32::UserDefinedFarm32( const char* fname, FarmManager* a_manager ) : UserDefinedFarm(fname, a_manager) // 46
2602 {
2604 }
2605 
2606 UserDefinedFarm33::UserDefinedFarm33( const char* fname, FarmManager* a_manager ) : UserDefinedFarm(fname, a_manager) // 47
2607 {
2609 }
2610 
2611 UserDefinedFarm34::UserDefinedFarm34( const char* fname, FarmManager* a_manager ) : UserDefinedFarm(fname, a_manager) // 48
2612 {
2614 }
2615 
2616 UserDefinedFarm35::UserDefinedFarm35( const char* fname, FarmManager* a_manager ) : UserDefinedFarm(fname, a_manager) // 49
2617 {
2619 }
2620 
2621 
2622 //--------------------------------------------------------------------------------------------
2623 //--------------------------------------------------------------------------------------------
2624 //--------------------------------------------------------------------------------------------
2625 
2627 {
2628 
2629  g_farmmanager = this;
2630 
2631  if ( l_map_read_farmfile.value() ) {
2632  if (cfg_OptimisingFarms.value()){
2633  //make a data object
2635  ReadFarmsData();
2639  //ReadGlobalData();
2640  ReadLookupTable();
2641  ofstream ofile ("Economic_figures.txt", ios::out);
2642  ofile.close();
2643  ofstream ofile1 ("Daydegrees.txt", ios::out);
2644  ofile1.close();
2645  if(cfg_MaizeEnergy.value()){
2646  ofstream ofileEM ("Maize_energy_price_yearly.txt", ios::out);
2647  ofileEM.close();
2648  }
2649 
2652  ReadCropsData();
2657  }
2658  else{
2665  m_crops_summary_BIs.resize(pm_data->Get_noCrops()); //no_crops - from the input file on initial crop areas
2673  m_crop_areas_stages.resize( 2 * pm_data->Get_noCrops()); //use just the results of the baseline and original model
2674  for(int i=0; i<pm_data->Get_noCrops(); i++){
2676  m_crops_summary_BIs[i].BI=0;
2677  m_crops_summary_BIs[i].BIherb=0;
2678  m_crops_summary_BIs[i].BIfi=0;
2679  m_cropTotals_sum[i]=0;
2681  m_cropTotals_pig_sum[i]=0;
2684  m_crops_fertilizer[i]=0;
2686  }
2687 
2688  if(cfg_MaizeEnergy.value()){
2690  }
2691  }
2692  }//if optimising farm
2694  }
2695 
2696 }
2697 
2698 
2700 {
2701 
2702  for ( unsigned int i = 0; i < m_farms.size(); i++ )
2703  delete m_farms[ i ];
2704  if (cfg_OptimisingFarms.value()) delete pm_data;
2705 }
2706 
2708 {
2709  for ( unsigned int i = 0; i < m_farms.size(); i++ )
2710  {
2711  m_farms[ i ]->Management();
2712  }
2713 
2714  //050214
2716  if(g_landscape_p->SupplyDayInYear() == cfg_Animals_number_test_day.value()){ //check if this is the day we want to collect data on animal numbers
2717  for ( unsigned int i = 0; i < m_farms.size(); i++ )
2718  {
2719  OptimisingFarm * opf;
2720  if(m_farms[i]->GetType() == tof_OptimisingFarm){ //take only optimising farms
2721  opf = dynamic_cast<OptimisingFarm*>(m_farms[i]);
2722  if(cfg_AnimalsThreshold.value() > 0 && opf->Get_main_goal() == tofg_environment){ //take only environmentalists and check if we are in the feedback mode (no if the config is zero)
2723  int farm_ref = opf->GetFarmNumber();
2724  int animals_no = g_landscape_p->SupplyFarmAnimalCensus(farm_ref, cfg_LifeStage.value());
2725  opf->Set_animals_no(animals_no);
2726  }
2727  }
2728  }
2729  }
2730  }
2731 }
2732 
2734 {
2735  for ( unsigned int i = 0; i < m_farms.size(); i++ )
2736  {
2737  m_farms[ i ]->InitiateManagement();
2738  }
2739 }
2740 
2741 void FarmManager::AddField(int a_OwnerIndex, LE* a_newland, int a_Owner)
2742 {
2743  m_farms[ a_OwnerIndex ]->AddField( a_newland );
2744  a_newland->SetOwner( m_farms[ a_OwnerIndex ], a_Owner, a_OwnerIndex );
2745 }
2746 
2747 void FarmManager::RemoveField(int a_OwnerIndex, LE* a_field)
2748 {
2749  m_farms[ a_OwnerIndex ]->RemoveField( a_field );
2750 }
2751 
2752 int FarmManager::ConnectFarm( int a_owner )
2753 {
2754  for ( unsigned int i = 0; i < m_farms.size(); i++ )
2755  {
2756  if ( a_owner == m_farms[ i ]->GetFarmNumber() )
2757  {
2758  // Found it. Set mapping and return.
2759  return i;
2760  }
2761  }
2762  // We didn't find the owner in the list of farms,
2763  // pregenerated in CreateFarms() above. Something
2764  // is not correct here, so raise an appropriate
2765  // error and exit.
2766  char error_num[ 20 ];
2767  sprintf( error_num, "%d", a_owner );
2768  g_msg->Warn( WARN_FILE, "FarmManager::ConnectFarm(): Unknown farm number"" referenced in polygon file:", error_num );
2769  exit( 1 );
2770 }
2771 
2772 void FarmManager::CreateFarms( const char * a_farmfile )
2773 {
2774  int No, FType, NoFarms;
2775  FILE * inpf = fopen(a_farmfile, "r" );
2776  if (!inpf) {
2777  g_msg->Warn( WARN_FILE, "Landscape::CreateFarms(): Unable to open file", a_farmfile );
2778  exit( 1 );
2779  }
2780 
2781  fscanf( inpf, "%d", & NoFarms );
2782 
2783  m_farms.resize( NoFarms );
2784 
2785  m_farmmapping_lookup = new int[NoFarms * 2];
2786 
2787  for (int i = 0; i < NoFarms; i++)
2788  {
2789  // File format:
2790  //
2791  // Two colunms of numbers 0..number of farms, 0-number of farmtypes-1
2792  // the second column determines what type of farm we have
2793  fscanf(inpf, "%d %d", &No, &FType);
2794  m_farmmapping_lookup[i * 2] = No;
2795  m_farmmapping_lookup[i * 2 + 1] = FType;
2796  }
2797  fclose(inpf);
2798 
2799  for (int i = 0; i < NoFarms; i++)
2800  {
2801  /*
2802  //If we are testing crop management, then ignore farm type from
2803  // the file and set to fixed one instead.
2804  if ( g_farm_test_crop.value() ) {
2805  FType = g_farm_test_crop_farmtype.value();
2806  }
2807  */
2808  // If we are running in fixed, sync'ed rotation mode, set all farms to
2809  // be of the requested type.
2812  }
2813 
2814  switch (m_farmmapping_lookup[i * 2 + 1]) // FType
2815  {
2816  case 0:
2817  m_farms[i] = new ConventionalCattle(this);
2818  break;
2819  case 1:
2820  m_farms[i] = new ConventionalPig(this);
2821  break;
2822  case 2:
2823  m_farms[i] = new ConventionalPlant(this);
2824  break;
2825  case 3:
2826  m_farms[i] = new OrganicCattle(this);
2827  break;
2828  case 4:
2829  m_farms[i] = new OrganicPig(this);
2830  break;
2831  case 5:
2832  m_farms[i] = new OrganicPlant(this);
2833  break;
2834  case 6:
2835  m_farms[i] = new PesticideTrialControl(this);
2836  break;
2837  case 7:
2838  m_farms[i] = new PesticideTrialToxicControl(this);
2839  break;
2840  case 8:
2841  m_farms[i] = new PesticideTrialTreatment(this);
2842  break;
2843  case 9:
2844  m_farms[i] = new ConvMarginalJord(this);
2845  break;
2846  case 10:
2847  m_farms[i] = new AgroChemIndustryCerealFarm1(this);
2848  break;
2849  case 11:
2850  m_farms[i] = new AgroChemIndustryCerealFarm2(this);
2851  break;
2852  case 12:
2853  m_farms[i] = new AgroChemIndustryCerealFarm3(this);
2854  break;
2855  case 13:
2856  m_farms[i] = new NoPesticideBaseFarm(this);
2857  break;
2858  case 14:
2859  m_farms[i] = new NoPesticideNoPFarm(this);
2860  break;
2861  case 15:
2862  m_farms[i] = new UserDefinedFarm1(this);
2863  break;
2864  case 16:
2865  m_farms[i] = new UserDefinedFarm2(this);
2866  break;
2867  case 17:
2868  m_farms[i] = new UserDefinedFarm3(this);
2869  break;
2870  case 18:
2871  m_farms[i] = new UserDefinedFarm4(this);
2872  break;
2873  case 19:
2874  m_farms[i] = new UserDefinedFarm5(this);
2875  break;
2876  case 20:
2877  m_farms[i] = new UserDefinedFarm6(this);
2878  break;
2879  case 21:
2880  m_farms[i] = new UserDefinedFarm7(this);
2881  break;
2882  case 22:
2883  m_farms[i] = new UserDefinedFarm8(this);
2884  break;
2885  case 23:
2886  m_farms[i] = new UserDefinedFarm9(this);
2887  break;
2888  case 24:
2889  m_farms[i] = new UserDefinedFarm10(this);
2890  break;
2891  case 25:
2892  m_farms[i] = new UserDefinedFarm11(this);
2893  break;
2894  case 26:
2895  m_farms[i] = new UserDefinedFarm12(this);
2896  break;
2897  case 27:
2898  m_farms[i] = new UserDefinedFarm13(this);
2899  break;
2900  case 28:
2901  m_farms[i] = new UserDefinedFarm14(this);
2902  break;
2903  case 29:
2904  m_farms[i] = new UserDefinedFarm15(this);
2905  break;
2906  case 30:
2907  m_farms[i] = new UserDefinedFarm16(this);
2908  break;
2909  case 31:
2910  m_farms[i] = new UserDefinedFarm17(this);
2911  break;
2912  // NB the user defing farms below require an extra parameter in the rotation file denoting the intensity (0 or 1 = high low)
2913  case 32:
2914  m_farms[i] = new UserDefinedFarm18("UserDefinedFarm18.rot", this);
2915  break;
2916  case 33:
2917  m_farms[i] = new UserDefinedFarm19("UserDefinedFarm19.rot", this);
2918  break;
2919  case 34:
2920  m_farms[i] = new UserDefinedFarm20("UserDefinedFarm20.rot", this);
2921  break;
2922  case 35:
2923  m_farms[i] = new UserDefinedFarm21("UserDefinedFarm21.rot", this);
2924  break;
2925  case 36:
2926  m_farms[i] = new UserDefinedFarm22("UserDefinedFarm22.rot", this);
2927  break;
2928  case 37:
2929  m_farms[i] = new UserDefinedFarm23("UserDefinedFarm23.rot", this);
2930  break;
2931  case 38:
2932  m_farms[i] = new UserDefinedFarm24("UserDefinedFarm24.rot", this);
2933  break;
2934  case 39:
2935  m_farms[i] = new UserDefinedFarm25("UserDefinedFarm25.rot", this);
2936  break;
2937  case 40:
2938  m_farms[i] = new UserDefinedFarm26("UserDefinedFarm26.rot", this);
2939  break;
2940  case 41:
2941  m_farms[i] = new UserDefinedFarm27("UserDefinedFarm27.rot", this);
2942  break;
2943  case 42:
2944  m_farms[i] = new UserDefinedFarm28("UserDefinedFarm28.rot", this);
2945  break;
2946  case 43:
2947  m_farms[i] = new UserDefinedFarm29("UserDefinedFarm29.rot", this);
2948  break;
2949  case 44:
2950  m_farms[i] = new UserDefinedFarm30("UserDefinedFarm30.rot", this);
2951  break;
2952  case 45:
2953  m_farms[i] = new UserDefinedFarm31("UserDefinedFarm31.rot", this);
2954  break;
2955  case 46:
2956  m_farms[i] = new UserDefinedFarm32("UserDefinedFarm32.rot", this);
2957  break;
2958  case 47:
2959  m_farms[i] = new UserDefinedFarm33("UserDefinedFarm33.rot", this);
2960  break;
2961  case 48:
2962  m_farms[i] = new UserDefinedFarm34("UserDefinedFarm34.rot", this);
2963  break;
2964  case 49:
2965  m_farms[i] = new UserDefinedFarm35("UserDefinedFarm35.rot", this);
2966  break;
2967  case 50: //optimising farm!
2968  if ((pm_data->Get_farmType(No)) == toof_Pig) {
2969  m_farms[i] = new OptimisingPigFarm(this, No);
2970  }
2971  else if ((pm_data->Get_farmType(No)) == toof_Cattle){
2972  m_farms[i] = new OptimisingCattleFarm(this, No);
2973  }
2974  else if ((pm_data->Get_farmType(No)) == toof_Plant){
2975  m_farms[i] = new OptimisingPlantFarm(this, No);
2976  }
2977  else if ((pm_data->Get_farmType(No)) == toof_Other){
2978  m_farms[i] = new OptimisingOtherFarm(this, No);
2979  }
2980  break;
2981 
2982  default:
2983  g_msg->Warn(WARN_FILE, "Landscape::CreateFarms(): Unknown farm type reference number: ", m_farmmapping_lookup[i * 2 + 1]);
2984  exit(1);
2985  }
2986  m_farms[i]->SetFarmNumber(i); // We use 'i' here because we renumber the farms internally. If the file did not come in this way then a dump file is created - tested in ReadPolys2
2987  }
2988 
2990  {
2991  DistributeFarmerTypes(); //added 240513
2992  }
2993 
2994  if (GetFarmNoLookup(NoFarms - 1) != NoFarms - 1) m_renumbered = false; else m_renumbered = true;
2995 }
2996 
2998 {
2999  ofstream opf("dump_farmrefs.txt");
3000  if (!opf.is_open())
3001  {
3002  g_msg->Warn(WARN_FILE, "Landscape::CreateFarms(): Unable to open file", "dump_farmrefs.txt");
3003  exit(1);
3004  }
3005  int NoFarms = (int) m_farms.size();
3006  opf << NoFarms << endl;
3007  for (int i = 0; i < NoFarms; i++)
3008  {
3009  opf << i << '\t' << m_farmmapping_lookup[i * 2 + 1] << endl;
3010  }
3011  opf.close();
3012 }
3013 
3015 
3016 
3018  Create_Output_file_for_farms(); //needed only for the OpitmisingFarms!
3019 }
3020 
3021 for(unsigned j=0; j<m_farms.size(); j++){
3022  if(m_farms[j]->GetType()==tof_OptimisingFarm){
3023  OptimisingFarm * opf = dynamic_cast<OptimisingFarm*>(m_farms[j]);
3024  opf->Init(pm_output_file);
3025  }
3026  }
3027 
3028 OptimisationOutput(); //03.05 - outputs of the optimisation
3029 
3030 }
3031 
3032 
3034 {
3035  /*
3036  * This data is grain distributions based on 2013 & 2014 data from cereal fields in Jutland counted in September.
3037  * Counts made in squares of 0.0196 m2 and scaled up, hence the decimal numbers.
3038  * The numbers represent number of grains.
3039  */
3040  double graindist2013[26] = {
3041  29.59, 172.68, 60.59, 39.68, 51.02, 81.63, 268.71, 134.84, 57.40, 30.61, 204.08, 683.67, 108.04,
3042  141.29, 505.10, 444.61, 293.37, 355.18, 386.90, 381.83, 372.45, 377.55, 320.70, 392.46, 392.86, 435.17
3043  };
3044  double graindist2014[28] = {
3045  109.33, 382.65, 94.19, 765.31, 29.15, 70.15, 1096.94, 436.51, 309.21, 286.28, 480.44, 249.73, 784.10,
3046  688.78, 2035.45, 920.80, 341.61, 12.24, 113.38, 80.17, 178.57, 480.44, 0.00, 2.83, 1447.12, 1846.94, 1017.86,
3047  477.74
3048  };
3049  int grain_dist_value = cfg_grain_distribution.value();
3050  if (grain_dist_value == 0) // The default - random pick between the two years
3051  {
3052  if (m_SpilledGrain) return graindist2013[(int)(g_rand_uni() * 26)];
3053  else return graindist2014[(int)(g_rand_uni() * 28)];
3054  }
3055  if (grain_dist_value == 1) {
3056  return graindist2013[(int)(g_rand_uni() * 26)];
3057  }
3058  else
3059  {
3060  return graindist2014[(int)(g_rand_uni() * 28)];
3061  }
3062 }
3063 
3065 {
3066  /*
3067  * This data is maize distributions in kJ/m2 based on 2015, 2016 & 2017 field data from maize fields in Jutland
3068  */
3069  double maizedist[15] = {
3070  102.7905327,
3071  58.19878648,
3072  85.65877728,
3073  110.9055748,
3074  30.65682555,
3075  63.11699379,
3076  59.05947276,
3077  41.9277173,
3078  95.57716202,
3079  14.42674144,
3080  6.311699379,
3081  20.73844082,
3082  12.62339876,
3083  25.24679751,
3084  146.070757};
3085  return maizedist[(int)(g_rand_uni() * 15)];
3086 }
3087 
3088 bool FarmManager::InIllegalList( int a_farm_ref, vector<int> * a_farmlist ) {
3092  unsigned sz = (unsigned) a_farmlist->size();
3093  for (unsigned f = 0; f < sz; f++) {
3094  if ((*a_farmlist)[f] == a_farm_ref) return true;
3095  }
3096  return false;
3097 }
3098 
3099 void FarmManager::AddToIllegalList( int a_farm_ref, vector<int> * a_farmlist ) {
3103  bool found = false;
3104  unsigned sz = (unsigned)a_farmlist->size();
3105  for (unsigned f = 0; f < sz; f++) {
3106  if ((*a_farmlist)[f] == a_farm_ref) {
3107  found = true;
3108  break;
3109  }
3110  }
3111  if (!found) {
3112  a_farmlist->push_back( a_farm_ref );
3113  }
3114 }
3115 
3116 bool FarmManager::IsDuplicateRef(int a_ref, HunterInfo* a_hinfo)
3117 {
3118  for (int i = 0; i < int( a_hinfo->FarmHuntRef.size() ); i++)
3119  {
3120 
3121  if (a_ref == a_hinfo->FarmHuntRef[ i ]) return true;
3122  }
3123  return false;
3124 }
3125 
3126 int FarmManager::FindClosestFarm(HunterInfo a_hinfo, vector<int> * a_farmlist) {
3131  double best = 99999999999999999.0;
3132  int bestref = -1;
3133  double dist = best;
3134  for (unsigned i = 0; i < m_farms.size(); i++) {
3135  int fnum = m_farms[i]->GetFarmNumber();
3136  if (!InIllegalList(fnum, a_farmlist)) {
3137  if (!IsDuplicateRef(fnum, &a_hinfo)) {
3138  // Is possible to use this farm, so test it.
3139  APoint FPt = m_farms[i]->GetCentroids();
3140  dist = sqrt((double( FPt.m_x - a_hinfo.homeX ) * double( FPt.m_x - a_hinfo.homeX ) + double( FPt.m_y - a_hinfo.homeY ) * double( FPt.m_y - a_hinfo.homeY )));
3141  if (dist < best) {
3142  best = dist;
3143  bestref = fnum;
3144  }
3145  }
3146  }
3147  }
3148  if (bestref == -1) {
3149  g_msg->Warn( "FarmManager::FindClosestFarm - Cannot find open farm.", "" );
3150  exit( 0 );
3151  }
3152  return bestref;
3153 }
3154 
3155 int FarmManager::FindClosestFarmOpenness( HunterInfo a_hunterinfo, vector<int> * a_farmlist, int a_openness ) {
3156  // Centroid calculation on farms must be called before calling this method for the first time
3157  double best = 99999999999999999.0;
3158  int bestref = -1;
3159  double dist = best;
3160  for (unsigned i = 0; i < m_farms.size(); i++) {
3161  if (m_farms[ i ]->GetMaxOpenness() > a_openness) {
3162  int fref = m_farms[ i ]->GetFarmNumber();
3163  if (!InIllegalList( fref, a_farmlist )) {
3164  if (!IsDuplicateRef( fref, &a_hunterinfo )) {
3165  APoint FPt = m_farms[ i ]->GetCentroids();
3166  dist = sqrt( (double( FPt.m_x - a_hunterinfo.homeX ) * double( FPt.m_x - a_hunterinfo.homeX ) + double( FPt.m_y - a_hunterinfo.homeY ) * double( FPt.m_y - a_hunterinfo.homeY )) );
3167  if (dist < best) {
3168  best = dist;
3169  bestref = fref;
3170  }
3171  }
3172  }
3173  }
3174  }
3175  if (bestref == -1) {
3176  g_msg->Warn( "FarmManager::FindClosestFarmOpenness( ) - Cannot find open farm.", "" );
3177  exit( 0 );
3178  }
3179  return bestref;
3180 }
3181 
3182 int FarmManager::FindClosestFarmOpennessProb( HunterInfo a_hunterinfo, vector<int> * a_farmlist, int a_openness ) {
3191  typedef APoint AFarmDist;
3193  vector <AFarmDist> farmdists;
3195  struct FarmDistSort {
3196  bool operator()( AFarmDist a, AFarmDist b ) {
3197  return a.m_y < b.m_y;
3198  }
3199  };
3200  for (unsigned i = 0; i < m_farms.size(); i++) {
3201  int fnum = m_farms[ i ]->GetFarmNumber();
3202  if (!InIllegalList( fnum, a_farmlist )) {
3203  if (m_farms[ i ]->GetMaxOpenness() > a_openness) {
3204  if (!IsDuplicateRef( fnum, &a_hunterinfo )) {
3205  // Is possible to use this farm, so test it.
3206  APoint FPt = m_farms[ i ]->GetCentroids();
3207  int dist = int(sqrt( (double( FPt.m_x - a_hunterinfo.homeX ) * double( FPt.m_x - a_hunterinfo.homeX ) + double( FPt.m_y - a_hunterinfo.homeY ) * double( FPt.m_y - a_hunterinfo.homeY )) ));
3208  if (dist>40000) dist = 40000;
3209  AFarmDist fd( int( fnum ), dist );
3210  farmdists.push_back( fd );
3211  }
3212  }
3213  }
3214  }
3215  // By here we have a list of farms and their distances - now we have the option to sort it or randomise it - one or other line below should be commented out.
3216  // sort(farmdists.begin(), farmdists.end(), FarmDistSort()); // Sort
3217  random_shuffle( farmdists.begin(), farmdists.end() ); // Randomise
3218  // Now the vector is sorted/randomised we loop through and test probabilities
3219  for (int ch = 1; ch < 100000; ch++) // This loop just makes sure small chances don't mess up the run by tripping out early
3220  {
3221  int sz = int( farmdists.size() );
3222  for (int i = 0; i < sz; i++) {
3223  double chance = g_rand_uni();
3224  // Uses ch from the outer loop to scale probabilities - tripping out here will occur often for farms a long way from the area otherwise
3225  double calc = cfg_ClosestFarmProbParam2.value()* exp( (cfg_ClosestFarmProbParam1.value() / double( ch ))* farmdists[ i ].m_y );
3226  if (chance <= calc) return farmdists[ i ].m_x;
3227  }
3228  }
3229  g_msg->Warn( "FarmManager::FindClosestFarmProb", "- No suitable farm found" );
3230  exit( 0 );
3231 }
3232 
3233 int FarmManager::FindClosestFarmOpennessProbSmallIsBest( HunterInfo a_hunterinfo, vector<int> * a_farmlist, int a_openness, vector<int>* a_farmsizelist ) {
3242  typedef APoint AFarmDist;
3244  vector <AFarmDist> farmdists;
3246  struct FarmDistSort {
3247  bool operator()( AFarmDist a, AFarmDist b ) {
3248  return a.m_y < b.m_y;
3249  }
3250  };
3251  for (unsigned i = 0; i < m_farms.size(); i++) {
3252  int fnum = m_farms[ i ]->GetFarmNumber();
3253  if (!InIllegalList( fnum, a_farmlist )) {
3254  if (m_farms[ i ]->GetMaxOpenness() > a_openness) {
3255  if (!IsDuplicateRef( fnum, &a_hunterinfo )) {
3256  // Is possible to use this farm, so test it.
3257  APoint FPt = m_farms[ i ]->GetCentroids();
3258  int dist = int(sqrt( (double( FPt.m_x - a_hunterinfo.homeX ) * double( FPt.m_x - a_hunterinfo.homeX ) + double( FPt.m_y - a_hunterinfo.homeY ) * double( FPt.m_y - a_hunterinfo.homeY )) ));
3259  if (dist>40000) dist = 40000;
3260  AFarmDist fd( unsigned( fnum ), dist );
3261  farmdists.push_back( fd );
3262  }
3263  }
3264  }
3265  }
3266  // By here we have a list of farms and their distances - now we have the option to sort it or randomise it - one or other line below should be commented out.
3267  // sort(farmdists.begin(), farmdists.end(), FarmDistSort()); // Sort
3268  random_shuffle( farmdists.begin(), farmdists.end() ); // Randomise
3269  // Now the vector is sorted/randomised we loop through and test probabilities
3270  for (int ch = 1; ch < 100000; ch++) // This loop just makes sure small chances don't mess up the run by tripping out early
3271  {
3272  int sz = int( farmdists.size() );
3273  for (int i = 0; i < sz; i++) {
3274  double chance = g_rand_uni();
3275  // Uses ch from the outer loop to scale probabilities - tripping out here will occur often for farms a long way from the area otherwise
3276  double calc = cfg_ClosestFarmProbParam2.value()* exp( (cfg_ClosestFarmProbParam1.value() / double( ch ))* farmdists[ i ].m_y );
3277  if (chance <= calc) {
3278  // We passed the first test now take a second test based on farm size
3279  chance = g_rand_uni();
3280  calc = pow( double( (*a_farmsizelist)[ farmdists[ i ].m_x ] / 4000.0 ), cfg_FarmSizeProbParam1.value() );
3281  if (chance>calc) return farmdists[ i ].m_x;
3282  }
3283  }
3284  }
3285  g_msg->Warn( "FarmManager::FindClosestFarmProb", "- No suitable farm found" );
3286  exit( 0 );
3287 }
3288 
3289 int FarmManager::FindClosestFarmOpennessProbNearRoostIsBest( HunterInfo a_hunterinfo, vector<int> * a_farmlist, int a_openness, vector<APoint>* a_roostlist ) {
3298  typedef APoint AFarmDist;
3300  vector <AFarmDist> farmdists;
3302  struct FarmDistSort {
3303  bool operator()( AFarmDist a, AFarmDist b ) {
3304  return a.m_y < b.m_y;
3305  }
3306  };
3307  for (unsigned i = 0; i < m_farms.size(); i++) {
3308  int fnum = m_farms[ i ]->GetFarmNumber();
3309  if (!InIllegalList( fnum, a_farmlist )) {
3310  if (m_farms[ i ]->GetMaxOpenness() > a_openness) {
3311  if (!IsDuplicateRef( fnum, &a_hunterinfo )) {
3312  // Is possible to use this farm, so test it.
3313  APoint FPt = m_farms[ i ]->GetCentroids();
3314  int dist = int(sqrt( (double( FPt.m_x - a_hunterinfo.homeX ) * double( FPt.m_x - a_hunterinfo.homeX ) + double( FPt.m_y - a_hunterinfo.homeY ) * double( FPt.m_y - a_hunterinfo.homeY )) ));
3315  if (dist>40000) dist = 40000;
3316  AFarmDist fd( unsigned( fnum ), dist );
3317  farmdists.push_back( fd );
3318  }
3319  }
3320  }
3321  }
3322  // By here we have a list of farms and their distances - now we have the option to sort it or randomise it - one or other line below should be commented out.
3323  // sort(farmdists.begin(), farmdists.end(), FarmDistSort()); // Sort
3324  random_shuffle( farmdists.begin(), farmdists.end() ); // Randomise
3325  // Now the vector is sorted/randomised we loop through and test probabilities
3326  for (int ch = 1; ch < 100000; ch++) // This loop just makes sure small chances don't mess up the run by tripping out early
3327  {
3328  int sz = int( farmdists.size() );
3329  for (int i = 0; i < sz; i++) {
3330  double chance = g_rand_uni();
3331  // Uses ch from the outer loop to scale probabilities - tripping out here will occur often for farms a long way from the area otherwise
3332  double calc = cfg_ClosestFarmProbParam2.value()* exp( (cfg_ClosestFarmProbParam1.value() / double( ch ))* farmdists[ i ].m_y );
3333  if (chance <= calc) {
3334  // We passed the first test now take a second test based on roost distance
3335  chance = g_rand_uni();
3336  // Loop through each roost and find the closest to the farm - then do probability based on that distance.
3337  double dist = 10000;
3338  for (int r = 0; r < int( a_roostlist->size() ); r++) {
3339  double fdistroostx = farmdists[ i ].m_x - (*a_roostlist)[ r ].m_x;
3340  double fdistroosty = farmdists[ i ].m_y - (*a_roostlist)[ r ].m_y;
3341  double distf = sqrt( fdistroostx * fdistroostx + fdistroosty * fdistroostx );
3342  if (distf < dist) dist = distf;
3343  }
3344  calc = -0.01 + pow( dist / 10000.0, cfg_RoostDistProbParam1.value() );
3345  if (chance>calc) return farmdists[ i ].m_x;
3346  }
3347  }
3348  }
3349  g_msg->Warn( "FarmManager::FindClosestFarmProbNearRoostBest", "- No suitable farm found" );
3350  exit( 0 );
3351 }
3352 
3353 int FarmManager::FindFarmWithRandom( vector<int> * a_farmlist )
3354 {
3355  int sz= (int)m_farms.size();
3356  int f = random(sz);
3357  while (InIllegalList(m_farms[f]->GetFarmNumber(), a_farmlist))
3358  {
3359  f = random(sz);
3360  if (a_farmlist->size() >= m_farms.size())
3361  {
3362  g_msg->Warn("FarmManager::FindFarmWithRandom"," - farm density rule means all hunters cannot be placed");
3363  exit(0);
3364  }
3365  }
3366  return m_farms[f]->GetFarmNumber();
3367 
3368 }
3369 
3370 int FarmManager::FindFarmWithOpenness(vector<int> * a_farmlist, int a_openness)
3371 {
3372  // Centroid calculation on farms must be called before calling this method for the first time
3373  int sz = (int)m_farms.size();
3374  int seed = random( sz );
3375  for (unsigned i = 0; i < m_farms.size(); i++) {
3376  int index = (i + seed) % sz;
3377  if (m_farms[ index ]->GetMaxOpenness() > a_openness)
3378  {
3379  if (!InIllegalList( m_farms[ index ]->GetFarmNumber(), a_farmlist )) return m_farms[ index ]->GetFarmNumber();
3380  }
3381  else AddToIllegalList(m_farms[ index ]->GetFarmNumber(), a_farmlist );
3382  }
3383  g_msg->Warn("FarmManager::FindFarmWithOpenness", "- No suitable farm found");
3384  exit(0);
3385 }
3386 
3388 {
3389  int sz = (int) m_farms.size();
3390  int seed = random(sz);
3391  for (unsigned i = 0; i < m_farms.size(); i++)
3392  {
3393  int index = (i + seed) % sz;
3394  if (m_farms[index]->GetMaxOpenness() > a_openness) return m_farms[index]->GetFarmNumber();
3395  }
3396  return -1; // Should never happen but if it does we need to handle the -1 error code.
3397 }
3398 
3399 bool FarmManager::CheckOpenness( int a_openness, int a_ref ) {
3400  if (m_farms[ a_ref ]->GetMaxOpenness() > a_openness) return true;
3401  return false;
3402 }
3403 
3405 
3406  //get farms areas and save them
3412  OptimisingFarm * opf;
3413  for(int j=0; j<(int)m_farms.size(); j++){
3414  if(m_farms[j]->GetType() == tof_OptimisingFarm){
3415  opf = dynamic_cast<OptimisingFarm*>(m_farms[j]);
3416  totalOptFarmsArea += opf->GetAreaDouble();
3417  if(opf->Get_farmType() == toof_Plant){
3419  }
3420  else if(opf->Get_farmType() == toof_Pig){
3422  }
3423  else if(opf->Get_farmType() == toof_Cattle){
3425  }
3426  else if(opf->Get_farmType() == toof_Other){
3428  }
3429  }
3430  }
3431 }
3432 
3434 
3435  for(int i=0; i<(int)m_farms.size(); i++){
3436  if(m_farms[i]->GetType() == tof_OptimisingFarm){ //take only optimising farms
3437  OptimisingFarm * opf;
3438  opf = dynamic_cast<OptimisingFarm*>(m_farms[i]);
3439  opf->ActualProfit();
3440  }
3441  }
3442 }
3443 
3445 
3446  for(int i=0; i<(int)m_farms.size(); i++){
3447  if(m_farms[i]->GetType() == tof_OptimisingFarm){ //take only optimising farms
3448  OptimisingFarm * opf;
3449  opf = dynamic_cast<OptimisingFarm*>(m_farms[i]);
3450  opf->ChooseDecisionMode();
3451 
3452  }
3453  }
3454 }
3455 
3457 
3458  for(int i=0; i<(int)m_farms.size(); i++){
3459  if(m_farms[i]->GetType() == tof_OptimisingFarm){ //take only optimising farms
3460  OptimisingFarm * opf;
3461  opf = dynamic_cast<OptimisingFarm*>(m_farms[i]);
3462  opf->Save_last_years_crops();
3463  }
3464  }
3465 }
3466 
3467 
3468 //void FarmManager::Switch_rotational_crops_for_farms(){
3469 //
3470 // for(int i=0; i<(int)m_farms.size(); i++){
3471 // if(m_farms[i]->GetType() == tof_OptimisingFarm){ //take only optimising farms
3472 // OptimisingFarm * opf;
3473 // opf = dynamic_cast<OptimisingFarm*>(m_farms[i]);
3474 // opf->Switch_rotational_crops();
3475 // }
3476 // }
3477 //}
3478 
3479 //--------------------------------------------------------------------------------------------
3480 //--------------------------------------------------------------------------------------------
3481 //--------------------------------------------------------------------------------------------
3482 
3483 
3485 
3486  int noFarms;
3487  int noParameters=6; //farm number, farm type, soil type, farm size, real ID, soil subtype
3488 
3489  //read the input file
3490  ifstream ifile("farms_data.txt", ios::in); //change it later - so that the nme can be set in the config file
3491 
3492  //check if there is an input file
3493  if ( !ifile.is_open() ) {
3494  cout << "Cannot open input file " << "farms_data.txt" << endl;
3495  char ch;
3496  cin >> ch; //so that it doesn't close immedietly
3497  exit(1);
3498  }
3499 
3500  //get the number of farms
3501  ifile>>noFarms;
3502  //get rid off the parameters' names
3503  string rubbish=""; //put here the names of the parameters;
3504  for(int i=0; i<noParameters; i++){
3505  ifile>>rubbish;
3506  }
3507  //read the data and assign values to the farm's variables
3508  for(int f=0; f<noFarms; f++){
3509  int almass_no, realID, soilSubType;
3510  string farm_type, soil_type, farm_size;
3511  ifile >> almass_no >> farm_type >> soil_type >> farm_size >> realID >> soilSubType;
3512  TTypesOfOptFarms farmType = TranslateFarmCodes (farm_type);
3513  TTypesOfSoils soilType = TranslateSoilCodes (soil_type);
3514  TTypesOfFarmSize farmSize = TranslateFarmSizeCodes (farm_size);
3515 
3518  pm_data->m_farm_data.push_back(fd);
3519  fd->md_almass_no=almass_no;
3520  fd->md_farmType=farmType;
3521  fd->md_soilType=soilType;
3522  fd->md_farmSize=farmSize;
3523  fd->md_farmRealID=realID;
3524  fd->md_soilSubType=soilSubType;
3525  }
3526 
3527  ifile.close();
3528 }
3529 
3531 
3532  int noFarms;
3533  //vector<TTypesOfAnimals>livestock_types; //vector of livestock types (enums)
3534 
3535  //read the input file
3536  ifstream ifile("livestock_numbers.txt", ios::in);
3537  //check if there is an input file
3538  if ( !ifile.is_open() ) {
3539  cout << "Cannot open input file " << "livestock_numbers.txt" << endl;
3540  char ch;
3541  cin >> ch; //so that it doesn't close immedietly
3542  exit(1);
3543  }
3544 
3545  //get the number of farms //and of types of livestock
3546  ifile>>noFarms; //>>noLivestockTypes;
3547 
3548  //put the names of the livestock types to the this vector;
3549  for(int l=0; l<toa_Foobar; l++){
3550  string type;
3551  ifile>>type;
3552  //livestock_types.push_back(TranslateAnimalsCodes(type));
3554  }
3555 
3556  //loop through the farms; create an instance of each livestock type
3557  for(int f=0; f<noFarms; f++){
3558  int almass_no; //in the first column of the input table
3559  ifile>>almass_no;
3560  pm_data->Set_livestockNumber(almass_no); //put it here so that you can search for the part of a vector - that contains numbers of a given farm
3561  for(int l=0; l<toa_Foobar; l++){
3562  int number;
3563  ifile >> number;
3564  pm_data->Set_livestockNumber(number);
3565  }
3566  }
3567  ifile.close();
3568 
3569 }
3570 
3572 
3573  int noFarms;
3574  //vector<TTypesOfCrops>crops_types; //vector of crops types (enums)
3575 
3576  //read the input file
3577  ifstream ifile("crop_areas.txt", ios::in);
3578  //check if there is an input file
3579  if ( !ifile.is_open() ) {
3580  cout << "Cannot open input file " << "crop_areas.txt" << endl;
3581  char ch;
3582  cin >> ch; //so that it doesn't close immedietly
3583  exit(1);
3584  }
3585 
3586  //get the number of farms /
3587  ifile>>noFarms;
3588 
3589  //put the names of the crop types to TWO vectors: one with strings, one with enums
3590  for(int c=0; c<toc_Foobar; c++){
3591  string type;
3592  ifile>>type;
3593  TTypesOfCrops type_enum = TranslateCropsCodes(type);
3594  pm_data->Set_cropTypes(type_enum);
3595  pm_data->Set_cropTypes_str(type);
3596  }
3597 
3598  //loop through the farms; create an instance of each crop type - also when the initial area is zero!
3599  for(int f=0; f<noFarms; f++){
3600  double almass_no; //in the first column of the input table
3601  ifile>>almass_no;
3602  pm_data->Set_cropArea(almass_no); //put it here so that you can search for the part of a vector - that contains numbers of a given farm
3603  for(int c=0; c<toc_Foobar; c++){
3604  double area;
3605  ifile >> area;
3606  pm_data->Set_cropArea(area);
3607  }
3608  }
3609  ifile.close();
3610 }
3611 
3613 
3614  int noFarms;
3615  int noCrops;
3616 
3617  //read the input file
3618  ifstream ifile("crop_areas.txt", ios::in);
3619  //check if there is an input file
3620  if ( !ifile.is_open() ) {
3621  cout << "Cannot open input file " << "crop_areas.txt" << endl;
3622  char ch;
3623  cin >> ch; //so that it doesn't close immedietly
3624  exit(1);
3625  }
3626 
3627  //get the number of crops
3628  ifile>>noCrops;
3629  //get the number of farms
3630  ifile>>noFarms;
3631  pm_data->Set_noCrops(noCrops);
3632 
3633  //put the names of the crop types to vector with enums and to the vector with strings - will be used for output
3634  for(int c=0; c<noCrops; c++){
3635  string type;
3636  ifile>>type;
3637  TTypesOfVegetation type_enum = TranslateCropCodes(type);
3638  pm_data->Set_cropTypes_almass(type_enum);
3640  }
3641 
3642  //loop through the farms; create an instance of each crop type - also when the initial area is zero!
3643  for(int f=0; f<noFarms; f++){
3644  double almass_no; //in the first column of the input table
3645  ifile>>almass_no;
3646  pm_data->Set_cropArea(almass_no); //put it here so that you can search for the part of a vector - that contains numbers of a given far
3647  for(int c=0; c<noCrops; c++){
3648  double area;
3649  ifile >> area;
3650  pm_data->Set_cropArea(area);
3651  }
3652  }
3653  ifile.close();
3654 }
3655 
3657 
3658  //read the input file
3659  ifstream ifile("crop_parameters.txt", ios::in);
3660  //check if there is an input file
3661  if ( !ifile.is_open() ) {
3662  cout << "Cannot open input file " << "crop_parameters.txt" << endl;
3663  char ch;
3664  cin >> ch; //so that it doesn't close immedietly
3665  exit(1);
3666  }
3667 
3668  //get rid of the parameters names
3669  for(int p=0; p<top_Foobar; p++){
3670  string type;
3671  ifile>>type;
3672  }
3673 
3674  //loop through the crops - save values of the parameters in a vector of the DataForOptimisation class
3675  for(int c=0; c<toc_Foobar; c++){
3676  string crop; //in the first column of the input table
3677  ifile>>crop; //do nothing with it
3678  for(int p=0; p<top_Foobar; p++){
3679  double par_value;
3680  ifile>>par_value;
3681  int index=top_Foobar*c + p;
3682  pm_data->Set_cropParameter (par_value, index );
3683  }
3684  }
3685  ifile.close();
3686 }
3687 
3689 
3690  //read the input file
3691  ifstream ifile("crop_parameters.txt", ios::in);
3692  //check if there is an input file
3693  if ( !ifile.is_open() ) {
3694  cout << "Cannot open input file " << "crop_parameters.txt" << endl;
3695  char ch;
3696  cin >> ch; //so that it doesn't close immedietly
3697  exit(1);
3698  }
3699 
3700  int noCrops=0;
3701  ifile>>noCrops;
3702 
3703  //get rid of the parameters names
3704  for(int p=0; p<top_Foobar; p++){
3705  string type;
3706  ifile>>type;
3707  }
3708 
3709  //loop through the crops - save values of the parameters in a vector of the DataForOptimisation class
3710  for(int c=0; c<noCrops; c++){
3711  string crop; //in the first column of the input table
3712  ifile>>crop; //do nothing with it
3713  for(int p=0; p<top_Foobar; p++){
3714  double par_value;
3715  ifile>>par_value;
3716  int index=top_Foobar*(pm_data->Get_cropTypes_almass(c)) + p; //Get_cropTypes_almass(c) - gives as a tov type crop at position c
3717  pm_data->Set_cropParameter (par_value, index );
3718  }
3719  }
3720  ifile.close();
3721 
3722 }
3723 
3725 
3726  //read the input files
3727  ifstream ifile1("alfa.txt", ios::in);
3728  ifstream ifile2("beta1.txt", ios::in);
3729  ifstream ifile3("beta2.txt", ios::in);
3730  ifstream ifile4("Nnorm.txt", ios::in);
3731  //check if there are all input files
3732  if ( !ifile1.is_open() ) {
3733  cout << "Cannot open input file " << "alfa.txt" << endl;
3734  char ch;
3735  cin >> ch; //so that it doesn't close immedietly
3736  exit(1);
3737  } else if(!ifile2.is_open() ){
3738  cout << "Cannot open input file " << "beta1.txt" << endl;
3739  char ch;
3740  cin >> ch; //so that it doesn't close immedietly
3741  exit(1);
3742  }
3743  else if(!ifile3.is_open() ){
3744  cout << "Cannot open input file " << "beta2.txt" << endl;
3745  char ch;
3746  cin >> ch; //so that it doesn't close immedietly
3747  exit(1);
3748  }
3749  else if(!ifile4.is_open() ){
3750  cout << "Cannot open input file " << "Nnorm.txt" << endl;
3751  char ch;
3752  cin >> ch; //so that it doesn't close immedietly
3753  exit(1);
3754  }
3755  //get rid off the crops names;
3756  for(int c=0; c<toc_Foobar; c++){
3757  string type;
3758  ifile1>>type;
3759  ifile2>>type;
3760  ifile3>>type;
3761  ifile4>>type;
3762  }
3763 
3764  //loop through the soil types!
3765  for(int s=0; s<tos_Foobar; s++){
3766  string soil;
3767  ifile1>>soil; //get rid off the soil type name
3768  ifile2>>soil;
3769  ifile3>>soil;
3770  ifile4>>soil;
3771  for(int c=0; c<toc_Foobar; c++){
3772  double par_value;
3773  ifile1>>par_value;
3774  pm_data->Set_alfa(par_value, toc_Foobar*s + c);
3775  ifile2>>par_value;
3776  pm_data->Set_beta1(par_value, toc_Foobar*s + c);
3777  ifile3>>par_value;
3778  pm_data->Set_beta2(par_value, toc_Foobar*s + c);
3779  ifile4>>par_value;
3780  pm_data->Set_Nnorm(par_value, toc_Foobar*s + c);
3781 
3782  }
3783  }
3784  ifile1.close();
3785  ifile2.close();
3786  ifile3.close();
3787  ifile4.close();
3788 }
3789 
3791 
3792  //read the input files
3793  ifstream ifile1("alfa.txt", ios::in);
3794  ifstream ifile2("beta1.txt", ios::in);
3795  ifstream ifile3("beta2.txt", ios::in);
3796  ifstream ifile4("Nnorm.txt", ios::in);
3797  ifstream ifile5("biomass_factor_almass.txt", ios::in);
3798 
3799  //check if there are all input files
3800  if ( !ifile1.is_open() ) {
3801  cout << "Cannot open input file " << "alfa.txt" << endl;
3802  char ch;
3803  cin >> ch; //so that it doesn't close immedietly
3804  exit(1);
3805  } else if(!ifile2.is_open() ){
3806  cout << "Cannot open input file " << "beta1.txt" << endl;
3807  char ch;
3808  cin >> ch; //so that it doesn't close immedietly
3809  exit(1);
3810  }
3811  else if(!ifile3.is_open() ){
3812  cout << "Cannot open input file " << "beta2.txt" << endl;
3813  char ch;
3814  cin >> ch; //so that it doesn't close immedietly
3815  exit(1);
3816  }
3817  else if(!ifile4.is_open() ){
3818  cout << "Cannot open input file " << "Nnorm.txt" << endl;
3819  char ch;
3820  cin >> ch; //so that it doesn't close immedietly
3821  exit(1);
3822  }
3823  if (!ifile5.is_open() ) {
3824  cout << "Cannot open input file " << "biomass_factor_almass.txt" << endl;
3825  char ch;
3826  cin >> ch; //so that it doesn't close immedietly
3827  exit(1);
3828  }
3829 
3830  int noCrops, noCrops1, noCrops2, noCrops3, noCrops4=0;
3831  ifile1>>noCrops;
3832  ifile2>>noCrops1;
3833  ifile3>>noCrops2;
3834  ifile4>>noCrops3;
3835  ifile5>>noCrops4; //should be always same number!
3836  if(noCrops!=noCrops1 || noCrops!=noCrops2 || noCrops!=noCrops3 || noCrops!=noCrops4){
3837  g_msg->Warn( WARN_FILE, "FarmManager::ReadCropsData_perSoilType_almass():"" Numbers of crops differ between input files! ", " " );
3838  exit( 1 );
3839  }
3840 
3841  //get rid off the crops names;
3842  for(int c=0; c<noCrops; c++){
3843  string type;
3844  ifile1>>type;
3845  ifile2>>type;
3846  ifile3>>type;
3847  ifile4>>type;
3848  ifile5>>type;
3849  }
3850 
3851  //loop through the soil types!
3852  for(int s=0; s<tos_Foobar; s++){
3853  string soil;
3854  ifile1>>soil; //get rid off the soil type name
3855  ifile2>>soil;
3856  ifile3>>soil;
3857  ifile4>>soil;
3858  ifile5>>soil;
3859  for(int c=0; c<noCrops; c++){
3860  double par_value;
3861  ifile1>>par_value;
3862  pm_data->Set_alfa(par_value, tov_Undefined*s + pm_data->Get_cropTypes_almass(c)); //Get_cropTypes_almass(c) - gives as a tov type crop at position c
3863  ifile2>>par_value;
3865  ifile3>>par_value;
3867  ifile4>>par_value;
3869  ifile5>>par_value;
3871 
3872  }
3873  }
3874  ifile1.close();
3875  ifile2.close();
3876  ifile3.close();
3877  ifile4.close();
3878  ifile5.close();
3879 }
3880 
3882 
3883  //read the input files
3884  ifstream ifile1("fixed.txt", ios::in);
3885  ifstream ifile2("fodder.txt", ios::in);
3886  ifstream ifile3("FUKey.txt", ios::in);
3887 
3888  //check if there are all input files
3889  if ( !ifile1.is_open() ) {
3890  cout << "Cannot open input file " << "fixed.txt" << endl;
3891  char ch;
3892  cin >> ch; //so that it doesn't close immedietly
3893  exit(1);
3894  } else if(!ifile2.is_open() ){
3895  cout << "Cannot open input file " << "fodder.txt" << endl;
3896  char ch;
3897  cin >> ch; //so that it doesn't close immedietly
3898  exit(1);
3899  }
3900  else if(!ifile3.is_open() ){
3901  cout << "Cannot open input file " << "FUKey.txt" << endl;
3902  char ch;
3903  cin >> ch; //so that it doesn't close immedietly
3904  exit(1);
3905  }
3906 
3907  //get rid off the crops names;
3908  for(int c=0; c<toc_Foobar; c++){
3909  string type;
3910  ifile1>>type;
3911  ifile2>>type;
3912  ifile3>>type;
3913  }
3914 
3915  //loop through the farm types!
3916  for(int f=0; f<toof_Foobar; f++){
3917  string farm_type;
3918  ifile1>>farm_type; //get rid off the farm type name
3919  ifile2>>farm_type;
3920  ifile3>>farm_type;
3921  for(int c=0; c<toc_Foobar; c++){
3922  string par;
3923  ifile1>>par;
3924  pm_data->Set_fixed(par, toc_Foobar*f + c);
3925  ifile2>>par;
3926  pm_data->Set_fodder(par, toc_Foobar*f + c);
3927  double par_value;
3928  ifile3>>par_value;
3929  pm_data->Set_FUKey(par_value, toc_Foobar*f + c);
3930  }
3931  }
3932  ifile1.close();
3933  ifile2.close();
3934  ifile3.close();
3935 }
3936 
3938 
3939  //read the input files
3940  ifstream ifile1("fixed.txt", ios::in);
3941  ifstream ifile2("fodder.txt", ios::in);
3942  ifstream ifile3("FUKey.txt", ios::in);
3943 
3944  //check if there are all input files
3945  if ( !ifile1.is_open() ) {
3946  cout << "Cannot open input file " << "fixed.txt" << endl;
3947  char ch;
3948  cin >> ch; //so that it doesn't close immedietly
3949  exit(1);
3950  } else if(!ifile2.is_open() ){
3951  cout << "Cannot open input file " << "fodder.txt" << endl;
3952  char ch;
3953  cin >> ch; //so that it doesn't close immedietly
3954  exit(1);
3955  }
3956  else if(!ifile3.is_open() ){
3957  cout << "Cannot open input file " << "FUKey.txt" << endl;
3958  char ch;
3959  cin >> ch; //so that it doesn't close immedietly
3960  exit(1);
3961  }
3962 
3963  int noCrops, noCrops1, noCrops2=0;
3964  ifile1>>noCrops;
3965  ifile2>>noCrops1;
3966  ifile3>>noCrops2; //should be always same number!
3967  if(noCrops!=noCrops1 || noCrops!=noCrops2){
3968  g_msg->Warn( WARN_FILE, "FarmManager::ReadCropsData_perSoilType_almass():"" Numbers of crops differ between input files! ", " " );
3969  exit( 1 );
3970  }
3971 
3972 
3973  //get rid off the crops names;
3974  for(int c=0; c<noCrops; c++){
3975  string type;
3976  ifile1>>type;
3977  ifile2>>type;
3978  ifile3>>type;
3979  }
3980 
3981  //loop through the farm types!
3982  for(int f=0; f<toof_Foobar; f++){
3983  string farm_type;
3984  ifile1>>farm_type; //get rid off the farm type name
3985  ifile2>>farm_type;
3986  ifile3>>farm_type;
3987  for(int c=0; c<noCrops; c++){
3988  string par;
3989  ifile1>>par;
3991  ifile2>>par;
3993  double par_value;
3994  ifile3>>par_value;
3996  }
3997  }
3998  ifile1.close();
3999  ifile2.close();
4000  ifile3.close();
4001 }
4002 
4004 
4005  //read the input files
4006  ifstream ifile1("sellingPrice.txt", ios::in);
4007 
4008  //check if there are all input files
4009  if ( !ifile1.is_open() ) {
4010  cout << "Cannot open input file " << "sellingPrice.txt" << endl;
4011  char ch;
4012  cin >> ch; //so that it doesn't close immedietly
4013  exit(1);
4014  }
4015 
4016  //get rid off the crops names;
4017  for(int c=0; c<toc_Foobar; c++){
4018  string type;
4019  ifile1>>type;
4020  }
4021 
4022  //loop through the farm and soil types!
4023  for(int f=0; f<(toof_Foobar * tos_Foobar); f++){
4024  string farm_type;
4025  string soil_type;
4026  ifile1>>farm_type>>soil_type; //get rid off the farm type and soil type names
4027  for(int c=0; c<toc_Foobar; c++){
4028  double par_value;
4029  ifile1>>par_value;
4030  pm_data->Set_sellingPrice(par_value, toc_Foobar*f + c);
4031  }
4032  }
4033  ifile1.close();
4034 }
4035 
4037 
4038  //read the input files
4039  ifstream ifile1("sellingPrice.txt", ios::in);
4040 
4041  //check if there are all input files
4042  if ( !ifile1.is_open() ) {
4043  cout << "Cannot open input file " << "sellingPrice.txt" << endl;
4044  char ch;
4045  cin >> ch; //so that it doesn't close immedietly
4046  exit(1);
4047  }
4048 
4049  int noCrops=0;
4050  ifile1>>noCrops;
4051 
4052  //get rid off the crops names;
4053  for(int c=0; c<noCrops; c++){
4054  string type;
4055  ifile1>>type;
4056  }
4057 
4058  //loop through the farm and soil types!
4059  for(int f=0; f<(toof_Foobar * tos_Foobar); f++){
4060  string farm_type;
4061  string soil_type;
4062  ifile1>>farm_type>>soil_type; //get rid off the farm type and soil type names
4063  for(int c=0; c<noCrops; c++){
4064  double par_value;
4065  ifile1>>par_value;
4067  }
4068  }
4069  ifile1.close();
4070 
4071 
4072  }
4073 
4075 
4076  //read the input files
4077  ifstream ifile1("rotationMax.txt", ios::in);
4078  ifstream ifile2("rotationMin.txt", ios::in);
4079 
4080  //check if there are all input files
4081  if ( !ifile1.is_open() ) {
4082  cout << "Cannot open input file " << "rotationMax.txt" << endl;
4083  char ch;
4084  cin >> ch; //so that it doesn't close immedietly
4085  exit(1);
4086  } else if(!ifile2.is_open() ){
4087  cout << "Cannot open input file " << "rotationMin.txt" << endl;
4088  char ch;
4089  cin >> ch; //so that it doesn't close immedietly
4090  exit(1);
4091  }
4092 
4093  //get rid off the crops names;
4094  for(int c=0; c<toc_Foobar; c++){
4095  string type;
4096  ifile1>>type;
4097  ifile2>>type;
4098  }
4099 
4100  //loop through the farm types, soil types and farm sizes!
4101  for(int f=0; f<(toof_Foobar *tos_Foobar * tofs_Foobar); f++){
4102  string farm_type, soil_type, farm_size;
4103  ifile1>>farm_type>>soil_type>>farm_size; //get rid off the farm type, soil type ad farm size names
4104  ifile2>>farm_type>>soil_type>>farm_size;
4105  for(int c=0; c<toc_Foobar; c++){
4106  double par_value;
4107  ifile1>>par_value;
4108  pm_data->Set_rotationMax(par_value, toc_Foobar*f + c);
4109  ifile2>>par_value;
4110  pm_data->Set_rotationMin(par_value, toc_Foobar*f + c);
4111  }
4112  }
4113  ifile1.close();
4114  ifile2.close();
4115 }
4116 
4118 
4119  //read the input files
4120 
4121  string rot_max;
4122  string rot_min;
4123 
4125  rot_max = "rotationMax_almass.txt";
4126  rot_min = "rotationMin_almass.txt";
4127  }
4128  else{ //rot max and min as specified in the Original Bedriftsmodel
4129  rot_max = "rotationMax.txt";
4130  rot_min = "rotationMin.txt";
4131  }
4132 
4133  ifstream ifile1(rot_max.c_str(), ios::in);
4134  ifstream ifile2(rot_min.c_str(), ios::in);
4135 
4136 
4137 
4138  //check if there are all input files
4139  if ( !ifile1.is_open() ) {
4140  cout << "Cannot open input file with rotation max" << endl;
4141  char ch;
4142  cin >> ch; //so that it doesn't close immedietly
4143  exit(1);
4144  } else if(!ifile2.is_open() ){
4145  cout << "Cannot open input file with rotation min" << endl;
4146  char ch;
4147  cin >> ch; //so that it doesn't close immedietly
4148  exit(1);
4149  }
4150 
4151  int noCrops, noCrops1=0;
4152  ifile1>>noCrops;
4153  ifile2>>noCrops1; //should be always same number!
4154  if(noCrops!=noCrops1){
4155  g_msg->Warn( WARN_FILE, "FarmManager::ReadCropsData_perSoilType_almass():"" Numbers of crops differ between input files! ", " " );
4156  exit( 1 );
4157  }
4158 
4159  //get rid off the crops names;
4160  for(int c=0; c<noCrops; c++){
4161  string type;
4162  ifile1>>type;
4163  ifile2>>type;
4164  }
4165 
4166  //loop through the farm types, soil types and farm sizes!
4167  for(int f=0; f<(toof_Foobar *tos_Foobar * tofs_Foobar); f++){
4168  string farm_type, soil_type, farm_size;
4169  ifile1>>farm_type>>soil_type>>farm_size; //get rid off the farm type, soil type ad farm size names
4170  ifile2>>farm_type>>soil_type>>farm_size;
4171  for(int c=0; c<noCrops; c++){
4172  double par_value;
4173  ifile1>>par_value;
4175  ifile2>>par_value;
4177  }
4178  }
4179  ifile1.close();
4180  ifile2.close();
4181 
4182 }
4183 
4185 
4186  //read the input files
4187  ifstream ifile1("winterMax.txt", ios::in);
4188 
4189  //check if there are all input files
4190  if ( !ifile1.is_open() ) {
4191  cout << "Cannot open input file " << "winterMax.txt" << endl;
4192  char ch;
4193  cin >> ch; //so that it doesn't close immedietly
4194  exit(1);
4195  }
4196 
4197  //get rid off the parameter name;
4198  string type;
4199  ifile1>>type;
4200 
4201  //loop through the farm types!
4202  for(int f=0; f<toof_Foobar; f++){
4203  string farm_type;
4204  ifile1>>farm_type; //get rid off the farm type name
4205  int par_value;
4206  ifile1>>par_value;
4207  pm_data->Set_winterMax(par_value, f);
4208  }
4209  ifile1.close();
4210 }
4211 
4213 
4214  //read the input file
4215  ifstream ifile("livestock_parameters.txt", ios::in);
4216  //check if there is an input file
4217  if ( !ifile.is_open() ) {
4218  cout << "Cannot open input file " << "livestock_parameters.txt" << endl;
4219  char ch;
4220  cin >> ch; //so that it doesn't close immedietly
4221  exit(1);
4222  }
4223 
4224  //get rid off the parameter names
4225  for(int p=0; p<tolp_Foobar; p++){
4226  string type;
4227  ifile>>type;
4228  }
4229 
4230  //loop through the livestock types - save values of the parameters in a vector of the DataForOptimisation class
4231  for(int l=0; l<toa_Foobar; l++){
4232  string livestock; //in the first column of the input table
4233  ifile>>livestock; //do nothing with it
4234  for(int p=0; p<tolp_Foobar; p++){
4235  double par_value;
4236  ifile>>par_value;
4237  pm_data->Set_livestockParameter(par_value, tolp_Foobar*l + p);
4238  }
4239  }
4240  ifile.close();
4241 }
4242 
4243 
4245 
4246 
4247  //read the input files
4248  ifstream ifile1(l_emaize_price_file.value(), ios::in);
4249 
4250  //check if there are all input files
4251  if ( !ifile1.is_open() ) {
4252  cout << "Cannot open input file " << l_emaize_price_file.value() << endl;
4253  char ch;
4254  cin >> ch; //so that it doesn't close immedietly
4255  exit(1);
4256  }
4257  //get th enumber of years he file has data for
4258  int no_years=0;
4259  ifile1>>no_years;
4260 
4261  //loop
4262  for(int i=0; i<no_years; i++){
4263  int year;
4264  ifile1>>year; //get rid off the year number
4265  double par_value;
4266  ifile1>>par_value;
4267  pm_data->Set_emaize_price(par_value);
4268  }
4269  ifile1.close();
4270 }
4271 
4272 
4274  // This simply checks through the list of legal farm types and returns
4275  // the correct farm type
4276  string str = astr;
4277  if ( str == "Other" ) return toof_Other;
4278  if ( str == "Cattle" ) return toof_Cattle;
4279  if ( str == "Plant" ) return toof_Plant;
4280  if ( str == "Pig" ) return toof_Pig;
4281  // No match so issue a warning and quit
4282  g_msg->Warn( WARN_FILE, "FarmManager::TranslateFarmCodes():"" Unknown Farm type Code ", str.c_str() );
4283  exit( 1 );
4284 }
4285 
4287  // This simply checks through the list of legal soil types and returns
4288  // the correct soil type
4289  string str = astr;
4290  if ( str == "Other" ) return tos_Other;
4291  if ( str == "Sand" ) return tos_Sand;
4292  if ( str == "Clay" ) return tos_Clay;
4293  // No match so issue a warning and quit
4294  g_msg->Warn( WARN_FILE, "FarmManager::TranslateSoilCodes():"" Unknown Soil type Code ", str.c_str() );
4295  exit( 1 );
4296 }
4297 
4299  // This simply checks through the list of legal farm sizes and returns
4300  // the correct farm size
4301  string str = astr;
4302  if ( str == "business" ) return tofs_Business;
4303  if ( str == "private" ) return tofs_Private;
4304  // No match so issue a warning and quit
4305  g_msg->Warn( WARN_FILE, "FarmManager::TranslateFarmSizeCodes():"" Unknown Farm Size Code ", str.c_str() );
4306  exit( 1 );
4307 }
4308 
4310  // This simply checks through the list of legal animal (livestock) types and returns
4311  // the correct animal type
4312  string str = astr;
4313  if ( str == "Horse") return toa_Horse;
4314  if ( str == "DCow") return toa_DCow;
4315  if ( str == "Suckler") return toa_Suckler;
4316  if ( str == "DCalf") return toa_DCalf;
4317  if ( str == "MCalf") return toa_MCalf;
4318  if ( str == "MCattle") return toa_MCattle;
4319  if ( str == "Sheep") return toa_Sheep;
4320  if ( str == "Goat") return toa_Goat;
4321  if ( str == "So") return toa_So;
4322  if ( str == "Finisher") return toa_Finisher;
4323  if ( str == "Piglet") return toa_Piglet;
4324  if ( str == "Deer") return toa_Deer;
4325  if ( str == "Mink") return toa_Mink;
4326  if ( str == "EHen") return toa_EHen;
4327  if ( str == "MHen") return toa_MHen;
4328  if ( str == "Turkey") return toa_Turkey;
4329  if ( str == "Goose") return toa_Goose;
4330  if ( str == "Duck") return toa_Duck;
4331  if ( str == "MDuck") return toa_MDuck;
4332  if ( str == "Ostrich") return toa_Ostrich;
4333  // No match so issue a warning and quit
4334  g_msg->Warn( WARN_FILE, "FarmManager::TranslateAnimalsCodes():"" Unknown Animal type Code ", str.c_str() );
4335  exit( 1 );
4336 }
4337 
4339 // This simply checks through the list of legal crops types and returns
4340 // the correct crop type
4341  string str = astr;
4342  if ( str == "SBarley") return toc_SBarley;
4343  if ( str == "Oats") return toc_Oats;
4344  if ( str == "OSCrops") return toc_OSCrops;
4345  if ( str == "WBarley") return toc_WBarley;
4346  if ( str == "WWheat") return toc_WWheat;
4347  if ( str == "WRye") return toc_WRye;
4348  if ( str == "Triticale") return toc_Triticale;
4349  if ( str == "SRape") return toc_SRape;
4350  if ( str == "WRape") return toc_WRape;
4351  if ( str == "OOilseed") return toc_OOilseed;
4352  if ( str == "Peas") return toc_Peas;
4353  if ( str == "OLSeed") return toc_OLSeed;
4354  if ( str == "GrassSeed") return toc_GrassSeed;
4355  if ( str == "Potato") return toc_Potato;
4356  if ( str == "PotatoFood") return toc_PotatoFood;
4357  if ( str == "SugarBeet") return toc_SugarBeet;
4358  if ( str == "GrassClover") return toc_GrassClover;
4359  if ( str == "OLSeedCut") return toc_OLSeedCut;
4360  if ( str == "SCerealSil") return toc_SCerealSil;
4361  if ( str == "PeasSil") return toc_PeasSil;
4362  if ( str == "MaizeSil") return toc_MaizeSil;
4363  if ( str == "WCerealSil") return toc_WCerealSil;
4364  if ( str == "SCerealG") return toc_SCerealG;
4365  if ( str == "PerGrassLow") return toc_PerGrassLow;
4366  if ( str == "PerGrassNorm") return toc_PerGrassNorm;
4367  if ( str == "GrassEnv1") return toc_GrassEnv1;
4368  if ( str == "GrassEnv2") return toc_GrassEnv2;
4369  if ( str == "GrassRot") return toc_GrassRot;
4370  if ( str == "Setaside") return toc_Setaside;
4371  if ( str == "Uncult") return toc_Uncult;
4372  if ( str == "OUncult") return toc_OUncult;
4373  if ( str == "OFodderBeet") return toc_OFodderBeet;
4374  if ( str == "CloverGrz") return toc_CloverGrz;
4375  if ( str == "Veg") return toc_Veg;
4376  if ( str == "Fruit") return toc_Fruit;
4377  if ( str == "FruitTree") return toc_FruitTree;
4378  if ( str == "OSpecCrops") return toc_OSpecCrops;
4379  if ( str == "ChrisTree") return toc_ChrisTree;
4380  if ( str == "EnergyFor") return toc_EnergyFor;
4381  if ( str == "Other") return toc_Other;
4382  // No match so issue a warning and quit
4383  g_msg->Warn( WARN_FILE, "FarmManager::TranslateCropCodes():"" Unknown Crop type Code ", str.c_str() );
4384  exit( 1 );
4385 }
4386 
4388  // This simply checks through the list of legal crop parameters (those not varying with farm type etc.)
4389  //and returns the correct enum
4390  string str = astr;
4391  if ( str == "Subsidy" ) return top_Subsidy;
4392  if ( str == "PriceLM" ) return top_PriceLM;
4393  if ( str == "PriceHerb" ) return top_PriceHerb;
4394  if ( str == "PriceFi" ) return top_PriceFi;
4395  if ( str == "PriceG" ) return top_PriceG;
4396  if ( str == "PriceH" ) return top_PriceH;
4397  if ( str == "PriceW" ) return top_PriceW;
4398  if ( str == "AlfaHerb" ) return top_AlfaHerb;
4399  if ( str == "BetaHerb" ) return top_BetaHerb;
4400  if ( str == "AlfaFi" ) return top_AlfaFi;
4401  if ( str == "BetaFi" ) return top_BetaFi;
4402  if ( str == "AlfaG" ) return top_AlfaG;
4403  if ( str == "BetaG" ) return top_BetaG;
4404  if ( str == "AlfaH" ) return top_AlfaH;
4405  if ( str == "BetaH" ) return top_BetaH;
4406  if ( str == "AlfaW" ) return top_AlfaW;
4407  if ( str == "BetaW" ) return top_BetaW;
4408 
4409  // No match so issue a warning and quit
4410  g_msg->Warn( WARN_FILE, "FarmManager::TranslateParametersCodes():"" Unknown Parameter Code ", str.c_str() );
4411  exit( 1 );
4412 }
4413 
4415  // This simply checks through the list of legal livestock parameters and returns the correct enum
4416  string str = astr;
4417  if ( str == "AUKey" ) return tolp_AUKey;
4418  if ( str == "Nusable" ) return tolp_Nusable;
4419  if ( str == "FUuKey" ) return tolp_FUuKey;
4420 
4421  // No match so issue a warning and quit
4422  g_msg->Warn( WARN_FILE, "FarmManager::TranslateLivestockParametersCodes():"" Unknown Livestock Parameter Code ", str.c_str() );
4423  exit( 1 );
4424 }
4425 
4427  // This simply checks through the list of legal crop variables and returns the correct enum
4428  string str = astr;
4429  if ( str == "m_areaPercent" ) return tocv_AreaPercent;
4430  if ( str == "m_area_ha" ) return tocv_AreaHa;
4431  if ( str == "m_n" ) return tocv_N;
4432  if ( str == "m_nt" ) return tocv_Nt;
4433  if ( str == "m_BIHerb" ) return tocv_BIHerb;
4434  if ( str == "m_BIFi" ) return tocv_BIFi;
4435  if ( str == "m_BI" ) return tocv_BI;
4436  if ( str == "m_grooming" ) return tocv_Grooming;
4437  if ( str == "m_hoeing" ) return tocv_Hoeing;
4438  if ( str == "m_weeding" ) return tocv_Weeding;
4439  if ( str == "m_totalLoss" ) return tocv_TotalLoss;
4440  if ( str == "m_resp" ) return tocv_Response;
4441  if ( str == "m_income" ) return tocv_Income;
4442  if ( str == "m_costs" ) return tocv_Costs;
4443  if ( str == "m_GM" ) return tocv_GM;
4444  if ( str == "m_savings" ) return tocv_Savings;
4445 
4446  // No match so issue a warning and quit
4447  g_msg->Warn( WARN_FILE, "FarmManager::TTypesOfCropVariables():"" Unknown crop variable Code ", str.c_str() );
4448  exit( 1 );
4449 }
4450 
4452 
4453 //1. crop variables
4454  PrintOutput(tocv_AreaPercent, "AreaPercent.txt");
4455  PrintOutput(tocv_AreaHa, "AreaHa.txt");
4456  PrintOutput(tocv_N, "N.txt");
4457  PrintOutput(tocv_Nt, "Nt.txt");
4458  PrintOutput(tocv_BIHerb, "BIHerb.txt");
4459  PrintOutput(tocv_BIFi, "BIFi.txt");
4460  PrintOutput(tocv_BI, "BI.txt");
4461  PrintOutput(tocv_Grooming, "Grooming.txt");
4462  PrintOutput(tocv_Hoeing, "Hoeing.txt");
4463  PrintOutput(tocv_Weeding, "Weeding.txt");
4464  PrintOutput(tocv_TotalLoss, "TotalLoss.txt");
4465  PrintOutput(tocv_Response, "Response.txt");
4466  PrintOutput(tocv_Income, "Income.txt");
4467  PrintOutput(tocv_Costs, "Costs.txt");
4468  PrintOutput(tocv_GM, "GM.txt");
4469  PrintOutput(tocv_Savings, "Savings.txt");
4470 
4471 //2. crop total areas in ha at the landscape level
4472 
4473  CropDistribution(); //now there are total area values for each crop in the m_cropTotals vector
4474  ofstream ofile("CropDistribution.txt", ios::out);
4475 
4477  //print crop names (using vector<string>m_cropTypes)
4478  for(int c=0; c<toc_Foobar; c++) ofile << pm_data->Get_cropTypes_str(c) << '\t';
4479  ofile << endl;
4480  //print the values (total areas in ha)
4481  for(int c=0; c<toc_Foobar; c++) ofile << m_cropTotals[c] << '\t';
4482  }
4483  else{
4484  //print 'year'
4485  ofile << "Year" << '\t';
4486  //print crop names
4487  for(int c=0; c<pm_data->Get_noCrops(); c++) ofile << pm_data->Get_cropTypes_almass_str(c) << '\t';
4488  ofile << endl;
4489  //it's the first optimisation, so say the year is zero
4490  ofile << "0" << '\t';
4491  //print the values (total areas in ha)
4492  for(int c=0; c<pm_data->Get_noCrops(); c++) ofile << m_cropTotals[c] << '\t';
4493  ofile << endl;
4494  }
4495 
4496  //restart the m_cropTotals:
4497  for(int i=0; i<(int)m_cropTotals.size(); i++){
4498  m_cropTotals[i]=0;
4499  }
4500 
4501  ofile.close();
4502 }
4503 
4504 void FarmManager::PrintOutput(TTypesOfCropVariables a_var, string a_fileName){
4505 
4506  ofstream ofile (a_fileName.c_str(), ios::out);
4507  ofile << "Farm no" << '\t';
4508  //print crop names (using vector<string>m_cropTypes)
4510  for(int c=0; c<toc_Foobar; c++) ofile << pm_data->Get_cropTypes_str(c) << '\t';
4511  }
4512  else{
4513  for(int c=0; c<pm_data->Get_noCrops(); c++) ofile << pm_data->Get_cropTypes_almass_str(c) << '\t';
4514  }
4515  ofile << endl;
4516 
4517  for (int i=0; i<(int)m_farms.size(); i++){
4518  if(m_farms[i]->GetType() == tof_OptimisingFarm){ //take only optimising farms
4519  OptimisingFarm * opf;
4520  opf = dynamic_cast<OptimisingFarm*>(m_farms[i]);
4521  int no = opf->Get_almass_no();
4522  ofile << no << '\t';
4523  int size = opf->Get_cropsSize();
4524  for(int j = 0; j < size; j++){
4525  double var_to_print = -1;
4526  CropOptimised* crop = opf->Get_crop(j);
4527  switch (a_var){
4528  case tocv_AreaPercent:
4529  var_to_print = crop ->m_areaPercent;
4530  break;
4531  case tocv_AreaHa:
4532  var_to_print = crop ->m_area_ha;
4533  break;
4534  case tocv_N:
4535  var_to_print = crop ->m_n;
4536  break;
4537  case tocv_Nt:
4538  var_to_print = crop ->m_nt;
4539  break;
4540  case tocv_BIHerb:
4541  var_to_print = crop ->m_BIHerb;
4542  break;
4543  case tocv_BIFi:
4544  var_to_print = crop ->m_BIFi;
4545  break;
4546  case tocv_BI:
4547  var_to_print = crop ->m_BI;
4548  break;
4549  case tocv_Grooming:
4550  var_to_print = crop ->m_grooming;
4551  break;
4552  case tocv_Hoeing:
4553  var_to_print = crop ->m_hoeing;
4554  break;
4555  case tocv_Weeding:
4556  var_to_print = crop ->m_weeding;
4557  break;
4558  case tocv_TotalLoss:
4559  var_to_print = crop ->m_totalLoss;
4560  break;
4561  case tocv_Response:
4562  var_to_print = crop ->m_resp;
4563  break;
4564  case tocv_Income:
4565  var_to_print = crop ->m_income_ha;
4566  break;
4567  case tocv_Costs:
4568  var_to_print = crop ->m_costs_ha;
4569  break;
4570  case tocv_GM:
4571  var_to_print = crop ->m_GM;
4572  break;
4573  case tocv_Savings:
4574  var_to_print = crop ->m_savings;
4575  break;
4576  default:
4577  g_msg->Warn( WARN_BUG, "FarmManager::PrintOutput(): ""Unknown crop variable type! ", "" );
4578  exit( 1 );
4579  }
4580  ofile << var_to_print << '\t';
4581  }
4582  ofile << endl;
4583  }
4584  }
4585  ofile.close();
4586 }
4587 
4589 
4590  int no_crops = (cfg_OptimiseBedriftsmodelCrops.value())? toc_Foobar : pm_data->Get_noCrops(); //bedriftsmodel crops/almass crops
4591  m_cropTotals.resize(no_crops); //no_crops is ok for both almass and bedriftsmodel crop mode; it is taken from the input file on initial crop areas
4592 
4593  for(int i=0; i<(int)m_farms.size(); i++){
4594 
4595  OptimisingFarm * opf;
4596  int size=0;
4597  if(m_farms[i]->GetType()==tof_OptimisingFarm) { //take only optimising farms
4598  opf = dynamic_cast<OptimisingFarm*>(m_farms[i]);
4599  size = opf->Get_cropsSize();
4600  for(int j=0; j<size; j++) {
4601  CropOptimised *crop = opf->Get_crop(j);
4602  double area = crop->m_area_ha;
4603  m_cropTotals[j] += area;
4604  }
4605  }
4606  }
4607 }
4608 
4610 
4611  pm_output_file = new ofstream ("FarmVariables.txt", ios::out);
4612 
4613  (*pm_output_file) << "Farm no \t";
4614 
4615  //print variables' names (18 variables, 09.05.12)
4616  (*pm_output_file) << "mainGoal \t" << "totalArea \t" << "totalIncome \t" << "totalCosts \t" << "totalProfit \t";
4617  (*pm_output_file) << "FodderDemand \t" << "FodderDemand_bef \t" << "FodderTrade \t" << "FodderGrown \t" ;
4618  (*pm_output_file) << "Nanim \t" << "totalNanim \t" << "totalNt \t" << "totalN \t" ;
4619  (*pm_output_file) << "totalBI \t" << "totalBIHerb \t" << "totalBIFi \t" ;
4620  (*pm_output_file) << "totalGrooming \t" << "totalHoeing \t" << "totalWeeding \t";
4621  (*pm_output_file) << endl;
4622 
4623 }
4624 
4626 
4627  //read the input file
4628  ifstream ifile("crops_lookup.txt", ios::in);
4629  //check if there is an input file
4630  if ( !ifile.is_open() ) {
4631  cout << "Cannot open input file " << "crops_lookup.txt" << endl;
4632  char ch;
4633  cin >> ch; //so that it doesn't close immedietly
4634  exit(1);
4635  }
4636 
4637  //get rid of the crop tov names - first line of the input file
4638  for(int p=0; p<tov_Undefined+1; p++){
4639  string tov_type;
4640  ifile>>tov_type;
4641  }
4642 
4643  //loop through the crops - save values (-1, 0 or 1) in the vector<int>m_crop_lookup_table;
4644  for(int r=0; r<tov_Undefined+1; r++){ //rows
4645  string tov_type; //in the first column of the input table
4646  ifile>>tov_type; //do nothing with it
4647  for(int c=0; c<tov_Undefined+1; c++){ //you are at row r, go through all the columns c
4648  int value;
4649  ifile >> value;
4650  m_crop_lookup_table.push_back(value);
4651  }
4652  }
4653  ifile.close();
4654 
4655 }
4656 
4658  //determine who is each farm's neighbour and save them in the farm's vector of its neighbours
4659  //and print the neighbours
4660 
4661  OptimisingFarm * opf_i;
4662  OptimisingFarm * opf_k;
4663 
4664  for(int i=0; i<(int)m_farms.size(); i++){
4665  if(m_farms[i]->GetType() == tof_OptimisingFarm){ //take only optimising farms
4666  opf_i = dynamic_cast<OptimisingFarm*>(m_farms[i]);
4667  opf_i->Centroids(); //finds each farm's centroid
4668  }
4669  }
4670 
4671  for(int i=0; i<(int)m_farms.size(); i++){
4672  if(m_farms[i]->GetType() == tof_OptimisingFarm){ //take only optimising farms
4673  opf_i = dynamic_cast<OptimisingFarm*>(m_farms[i]);
4674  int x = opf_i->GetFarmCentroidX();
4675  int y = opf_i->GetFarmCentroidY();
4676  int farm_no_i = opf_i->Get_almass_no();
4677 
4678  for(int k = 0; k<(int)m_farms.size(); k++) { //find neighbours of farm i
4679  if(m_farms[k]->GetType() == tof_OptimisingFarm){ //take only optimising farms
4680  opf_k = dynamic_cast<OptimisingFarm*>(m_farms[k]);
4681  int xb = opf_k->GetFarmCentroidX();
4682  int yb = opf_k->GetFarmCentroidY();
4683  double par = 1000 * cfg_Neighbor_dist.value(); //change km to m
4684  int farm_no_k = opf_k->Get_almass_no();
4685 
4686  if(abs(x - xb) <= par && abs(y - yb) <= par && farm_no_i!=farm_no_k){ //check neighbourship (make sure it is not the same farm)
4687  //this is a neighbour
4688  opf_i->Set_Neighbour(opf_k); //add farm k to the list of neighbours of farm i
4689  }
4690  }
4691  else break;
4692  }
4693  }
4694  else break; //break the for loop -there is no more optimising farms
4695  }
4696 
4697  PrintNeighbours();
4698 
4699 }
4700 
4702  //create a text file with the farms and their neighbours
4703  ofstream ofile ("Neighbours.txt", ios::out);
4704  ofile << "Farm no" << endl;
4705 
4706  //print each farms no and then the numbers of its neighbours
4707  for(int i=0; i<(int)m_farms.size(); i++){
4708  OptimisingFarm * opf_i;
4709  if(m_farms[i]->GetType() == tof_OptimisingFarm){ //take only optimising farms
4710  opf_i = dynamic_cast<OptimisingFarm*>(m_farms[i]);
4711  ofile << opf_i->Get_almass_no() << '\t';
4712  for(int j=0; j<opf_i->Get_NeighboursSize(); j++){
4713  ofile << opf_i->Get_Neighbour(j)->Get_almass_no() <<'\t'; //pointer to the current, i.e. 'i' farm, takes its neighbour (j) and retrieves his almass_no
4714  }
4715  ofile << endl;
4716  }
4717  }
4718 }
4719 
4721 
4722  //create a text file and make headers
4723  ofstream ofile ("Decision_modes_counts.txt", ios::out);
4724  ofile << "Farm_no\t" << "imitation\t" << "social comparison\t" << "repeat\t"<< "deliberation\t"<<endl;
4725 
4726  //print each farms no and then the content of the vector ...
4727  for(int i=0; i<(int)m_farms.size(); i++){
4728  OptimisingFarm * opf_i;
4729  if(m_farms[i]->GetType() == tof_OptimisingFarm){ //take only optimising farms
4730  opf_i = dynamic_cast<OptimisingFarm*>(m_farms[i]);
4731  ofile << opf_i->Get_almass_no() << '\t';
4732  for(int j=0; j<4; j++){
4733  ofile << opf_i->Get_decision_mode_counters(j) <<'\t';
4734  }
4735  ofile << endl;
4736  }
4737  }
4738 
4739 }
4740 
4742 
4744 
4745  int no_years = g_date->GetYearNumber() - 21; //exclude first 9 years + one - the last one, which has just started now - it's Jan 1st//exclude first 20 (0-19) years for the wildlife runs
4746  double BIherb_sum=0;
4747  double BIfi_sum=0;
4748  double BI_sum=0;
4749  double fertilizer_sum=0;
4750  double fertilizer_trade_sum=0;
4751 
4752  totalOptFarmsArea *= 0.0001;//change to ha
4753  totalOptFarmsArea_plant *= 0.0001;
4754  totalOptFarmsArea_pig *= 0.0001;
4755  totalOptFarmsArea_cattle *= 0.0001;
4756  totalOptFarmsArea_other *= 0.0001;
4757 
4758  ofstream ofile ("CropAreasTotal_and_Average.txt", ios::out);
4759  // "This file includes summed (over all optimising farms) areas of each crop during the whole simulation, the average areas " ;
4760  //"(equal to the sum divided by the number of years the simulation was run) and areas as percentage of total optimising farms area.\t" ;
4761  ofile << "CropName\t" << "Total\t" << "Average\t" << "Area_%\t"<< endl;
4762  for(int i=0; i<(int)m_cropTotals_sum.size(); i++){
4763  ofile << pm_data->Get_cropTypes_almass_str(i) << '\t';
4764  ofile << m_cropTotals_sum[i] << '\t';
4765  ofile << m_cropTotals_sum[i]/no_years << '\t';
4766  ofile << m_cropTotals_sum[i]/no_years/totalOptFarmsArea * 100 << '%';
4767  ofile << endl;
4768  }
4769  ofile.close();
4770 
4771  //printing separate files for specific farm types - just areas in %.
4772  ofstream ofile5 ("CropAreas_plant_farms.txt", ios::out);
4773  ofile5 << "CropName\t" << "Area_%\t" << endl; //<< "Total\t" << "Average\t" <<
4774  for(int i=0; i<(int)m_cropTotals_plant_sum.size(); i++){
4775  ofile5 << pm_data->Get_cropTypes_almass_str(i) << '\t';
4776  ofile5 << m_cropTotals_plant_sum[i]/no_years/totalOptFarmsArea_plant * 100 << '%';
4777  ofile5 << endl;
4778  }
4779  ofile5.close();
4780 
4781  ofstream ofile6 ("CropAreas_pig_farms.txt", ios::out);
4782  ofile6 << "CropName\t" << "Area_%\t" << endl; //<< "Total\t" << "Average\t" <<
4783  for(int i=0; i<(int)m_cropTotals_pig_sum.size(); i++){
4784  ofile6 << pm_data->Get_cropTypes_almass_str(i) << '\t';
4785  ofile6 << m_cropTotals_pig_sum[i]/no_years/totalOptFarmsArea_pig * 100 << '%';
4786  ofile6 << endl;
4787  }
4788  ofile6.close();
4789 
4790  ofstream ofile7 ("CropAreas_cattle_farms.txt", ios::out);
4791  ofile7 << "CropName\t" << "Area_%\t" << endl; //<< "Total\t" << "Average\t" <<
4792  for(int i=0; i<(int)m_cropTotals_cattle_sum.size(); i++){
4793  ofile7 << pm_data->Get_cropTypes_almass_str(i) << '\t';
4794  ofile7 << m_cropTotals_cattle_sum[i]/no_years/totalOptFarmsArea_cattle * 100 << '%';
4795  ofile7 << endl;
4796  }
4797  ofile7.close();
4798 
4799  ofstream ofile8 ("CropAreas_other_farms.txt", ios::out);
4800  ofile8 << "CropName\t" << "Area_%\t" << endl; //<< "Total\t" << "Average\t" <<
4801  for(int i=0; i<(int)m_cropTotals_other_sum.size(); i++){
4802  ofile8 << pm_data->Get_cropTypes_almass_str(i) << '\t';
4803  ofile8 << m_cropTotals_other_sum[i]/no_years/totalOptFarmsArea_other * 100 << '%';
4804  ofile8 << endl;
4805  }
4806  ofile8.close();
4807 
4808 
4809 
4810 
4811  ofstream ofile1 ("PesticideTotals.txt", ios::out);
4812  ofile1 << "CropName\t" << "BIherb\t" << "BIfi\t" << "BI\t" ; //total values within a simulation
4813  ofile1 << "BIherb_yr\t" << "BIfi_yr\t" << "BI_yr\t"; //average values per year (total/no_years)
4814  ofile1 << "BIherb_ha\t" << "BIfi_ha\t" << "BI_ha\t"; //average values per ha (total BI/total area)
4815  ofile1 << endl;
4816  for(int i=0; i<(int)m_crops_summary_BIs.size(); i++){
4817  //ofile1 << m_crops_summary_BIs[i].Tov << '\t';
4818  ofile1 << pm_data->Get_cropTypes_almass_str(i) << '\t';
4819 
4820  ofile1 << m_crops_summary_BIs[i].BIherb << '\t';
4821  BIherb_sum += m_crops_summary_BIs[i].BIherb;
4822 
4823  ofile1 << m_crops_summary_BIs[i].BIfi << '\t';
4824  BIfi_sum += m_crops_summary_BIs[i].BIfi;
4825 
4826  ofile1 << m_crops_summary_BIs[i].BI << '\t';
4827  BI_sum += m_crops_summary_BIs[i].BI;
4828 
4829  ofile1 << m_crops_summary_BIs[i].BIherb/no_years << '\t';
4830  ofile1 << m_crops_summary_BIs[i].BIfi/no_years << '\t';
4831  ofile1 << m_crops_summary_BIs[i].BI/no_years << '\t';
4832  if(!m_cropTotals_sum[i]==0){
4833  ofile1 << m_crops_summary_BIs[i].BIherb/m_cropTotals_sum[i] << '\t';
4834  ofile1 << m_crops_summary_BIs[i].BIfi/m_cropTotals_sum[i] << '\t';
4835  ofile1 << m_crops_summary_BIs[i].BI/m_cropTotals_sum[i] << '\t';
4836  }
4837  else{
4838  ofile1 <<"0\t" << "0\t" << "0\t" ;
4839  }
4840  ofile1 << endl;
4841  }
4842  ofile1.close();
4843 
4844  ofstream ofile2 ("FertilizerTotals.txt", ios::out);
4845  ofile2 << "CropName\t" << "Fertilizer\t" << "Fertilizer_yr\t" << "Fertilizer_ha\t" << endl;
4846  for(int i=0; i<(int)m_crops_summary_BIs.size(); i++){
4847  ofile2 << pm_data->Get_cropTypes_almass_str(i) << '\t';
4848  ofile2 << m_crops_fertilizer[i] << '\t'; //total - all farms, all years
4849  fertilizer_sum += m_crops_fertilizer[i];
4850  fertilizer_trade_sum += m_crops_fertilizer_trade[i];
4851  ofile2 << m_crops_fertilizer[i]/no_years << '\t'; // average per year
4852  if(m_cropTotals_sum[i]!=0){
4853  ofile2 << m_crops_fertilizer[i]/m_cropTotals_sum[i] << '\t'; //average per ha
4854  }
4855  else{
4856  ofile2 << "0\t";
4857  }
4858  ofile2 << endl;
4859  }
4860  ofile2.close();
4861 
4862  //READ the inputs on crop areas in diff model stages
4863  ifstream ifile("crop_results_stages.txt", ios::in);
4864  //check if there is an input file
4865  if ( !ifile.is_open() ) {
4866  cout << "Cannot open input file " << "crop_results_stages.txt" << endl;
4867  char ch;
4868  cin >> ch; //so that it doesn't close immedietly
4869  exit(1);
4870  }
4871  int no_crops = pm_data->Get_noCrops();
4872  //get rid of the crop names
4873  for(int c=0; c<no_crops; c++){
4874  string type;
4875  ifile>>type;
4876  }
4877  for(int stage=0; stage<2; stage++){ //get just the results of the baseline and of the original model
4878  //stage name
4879  string stage_name;
4880  ifile>>stage_name;
4881  //save crop areas
4882  for(int a=0; a<no_crops; a++){
4883  ifile>>m_crop_areas_stages[stage * no_crops + a];
4884  }
4885  }
4886 
4887  //determine the sums of squared differences in crop areas (araes as percentages)
4888  vector<double>sums;
4889  sums.resize(2);
4890  for(int s=0; s<2; s++){
4891  sums[s]=0;
4892  }
4893 
4894  for(int st=0; st<2; st++){
4895  for(int b=0; b<no_crops; b++){
4896  double sq_diff = pow(m_cropTotals_sum[b]/no_years/totalOptFarmsArea * 100 - m_crop_areas_stages[st * no_crops + b]*100, 2);
4897  sums[st] += sq_diff;
4898  }
4899  }
4900 
4901  ofstream ofile3 ("Result_summary.txt", ios::out);
4902  ofile3 << "BIherb\t" << "BIfi\t" << "BI\t" << "Fert\t" << "Fert_trade\t" ; // sum for all crops/no_years/total_opt_farms_area
4903  ofile3 << "Sum of sq. diff: Baseline\t" << "Sum of sq. diff: Original\t"; // << "Sum of sq. diff: New opt.\t" << "Sum of sq. diff: Almass_f.area\t" << "Sum of sq. diff: Crop_choice_ev_yr\t";
4904  //ofile3 << "Sum of sq. diff: Dec.modes\t" << "Sum of sq. diff: Farmer types\t" << "Sum of sq. diff: Types+modes\t" << endl;
4905  ofile3 << BIherb_sum/totalOptFarmsArea/no_years <<'\t';
4906  ofile3 << BIfi_sum/totalOptFarmsArea/no_years <<'\t';
4907  ofile3 << BI_sum/totalOptFarmsArea/no_years <<'\t';
4908  ofile3 << fertilizer_sum/totalOptFarmsArea/no_years <<'\t';
4909  ofile3 << fertilizer_trade_sum/totalOptFarmsArea/no_years <<'\t';
4910  for(int sta=0; sta<2; sta++){
4911  ofile3 << sums[sta] << '\t';
4912  }
4913  ofile3.close();
4914 
4915  //for calibration/sensitivty analysis: comparison to baseline
4916  ofstream ofile4 ("Output.txt", ios::out);
4917  //order: 1.BI 2.BI diff%; 3. BI_abs_diff; 4.fert; 5.fert diff%; 6.fert_abs_diff 7.sum of sq. diff. compared to baseline; 8. weigthed measure
4918  double BIdiff_percent = ((BI_sum/totalOptFarmsArea/no_years/2.2) - 1) *100;//BI in the baseline = 2.2 and is the country level score!
4919  double BIdiffabs = abs(BIdiff_percent);
4920  double fert_diff_percent = ((fertilizer_sum/totalOptFarmsArea/no_years/140.07)-1) * 100;
4921  double fertdiffabs = abs(fert_diff_percent);
4922  //ofile4 << endl;
4923  ofile4 << '\t' << BI_sum/totalOptFarmsArea/no_years <<'\t' << BIdiff_percent << '\t'<< BIdiffabs <<'\t';
4924  ofile4 << fertilizer_sum/totalOptFarmsArea/no_years << '\t' << fert_diff_percent << '\t' << fertdiffabs <<'\t'; //fert in baseline = 140.07 kg/ha
4925  ofile4 << sums[0] << '\t';
4926  ofile4 << 0.2 * abs(BIdiff_percent) + 0.2 * abs(fert_diff_percent) + 0.6 * sums[0] << endl;
4927  ofile4.close();
4928 
4929  //print also areas of all crops...
4930  ofstream ofile9 ("Output_crop_areas_percent.txt", ios::out);
4931  ofile9 << '\t';
4932  for(int i=0; i<(int)m_cropTotals_sum.size(); i++){
4933  ofile9 << m_cropTotals_sum[i]/no_years/totalOptFarmsArea * 100 << '\t'; //print just areas (no crop names!)
4934  }
4935  ofile9 << endl;
4936  ofile9.close();
4937 
4938 
4939 }
4940 
4941 
4943 
4944  //1. make a new rotation: include all rotational crops
4945  vector<TTypesOfVegetation> new_rotation;
4946  TTypesOfVegetation tov;
4947  for(int i=0; i<pm_data->Get_cropTypes_almass_size(); i++){
4948  tov = pm_data->Get_cropTypes_almass(i);
4951  new_rotation.push_back(tov);
4952  }
4953  }
4954 
4955  //2. assign it to each farm's m_rotation
4956  for(int i=0; i<(int)m_farms.size(); i++){
4957  OptimisingFarm * opf;
4958  if(m_farms[i]->GetType() == tof_OptimisingFarm){ //take only optimising farms
4959  opf = dynamic_cast<OptimisingFarm*>(m_farms[i]);
4960  opf->Assign_rotation(new_rotation);
4961  }
4962  }
4963 }
4964 
4966 
4967  //get the shares of certain types. Parameters in the config file.
4968  double profit_proportion = cfg_Profit_max_proportion.value();
4969  double yield_proportion = cfg_Yield_max_proportion.value();
4970  double env_proportion = cfg_Environmentalist_proportion.value();
4971 
4972  //get the number of optimising farms (count them) and make a list of opt farms and its copy
4973  int number_opt_farms=0;
4974  vector <OptimisingFarm*> opt_farms;
4975  vector <OptimisingFarm*> opt_farms_copy;
4976  for(int i=0; i<(int)m_farms.size(); i++){
4977  if(m_farms[i]->GetType()==tof_OptimisingFarm){
4978  number_opt_farms++;
4979  OptimisingFarm * opf = dynamic_cast<OptimisingFarm*>(m_farms[i]);
4980  opt_farms.push_back(opf);
4981  }
4982  }
4983  opt_farms_copy = opt_farms;
4984 
4985  //find the number of farms that should be of a certain type
4986  int number_profit = (int) (profit_proportion/100 * number_opt_farms); // + 0.5); round down - to avoid having a total number of diff types higher than the number of farms
4987  int number_yield = (int) (yield_proportion/100 * number_opt_farms + 0.5);
4988  int number_env = (int) (env_proportion/100 * number_opt_farms + 0.5);
4989 
4990  //see: http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution
4991  random_device rd;
4992  mt19937 gen(rd());
4993 
4994  int jj=0;
4995  int index_for_farm=0;
4996 
4997  //set farms with profit as a main goal
4998  for(int j=jj; j<number_profit; j++){
4999  distribution_type2 dis(0, number_opt_farms - j - 1); //each time we remove one farm, so '-j' and '-1' casue the last element in the list is =size-1.
5000  index_for_farm = dis(gen);
5001  opt_farms_copy[index_for_farm]->Set_main_goal(tofg_profit);
5002  opt_farms_copy.erase(opt_farms_copy.begin() + index_for_farm); //remove the farm from the list after assignign the goal
5003  jj = j;
5004  }
5005  jj++; //need to increase by one here!
5006 
5007  //set farms with yield as a main goal
5008  for(int j = jj; j<number_yield + number_profit; j++){ //start with the value of 'i' as it was after leaving the last for loop!
5009  distribution_type2 dis1(0, number_opt_farms - j - 1); //each time we remove one farm, so '-j'
5010  index_for_farm = dis1(gen);
5011  opt_farms_copy[index_for_farm]->Set_main_goal(tofg_yield);
5012  opt_farms_copy.erase(opt_farms_copy.begin() + index_for_farm); //remove the farm from the list after assignign the goal
5013  jj = j;
5014  }
5015  jj++;
5016 
5017  //set farms with environment as a main goal
5018  int loop_limit = (number_env + number_profit + number_yield > number_opt_farms)? number_opt_farms : number_env + number_profit + number_yield;
5019  for(int j=jj; j<loop_limit; j++){
5020  distribution_type2 dis2(0, number_opt_farms - j - 1); //each time we remove one farm, so '-j'
5021  index_for_farm = dis2(gen);
5022  opt_farms_copy[index_for_farm]->Set_main_goal(tofg_environment);
5023  opt_farms_copy.erase(opt_farms_copy.begin() + index_for_farm); //remove the farm from the list after assignign the goal
5024  }
5025 
5026  //check if there are any farms left without assigned goal
5027  if((int)opt_farms_copy.size()>0){ //it should be not more than 1-2
5028  for(int p=(int)opt_farms_copy.size(); p>0; p--){
5029  opt_farms_copy[p-1]->Set_main_goal(tofg_profit);
5030  }
5031  }
5032 
5033 }
5034 //--------------------------------------------------------------------------------------------
5035 //--------------------------OptimisingFarm----------------------------------------------------
5036 //--------------------------------------------------------------------------------------------
5037 
5038 
5039 void DataForOptimisation::InitializeVector(vector<double>&vector){
5040 
5041  for(int i=0; i<(int)vector.size(); i++){
5042  vector[i] = -1;
5043  }
5044 }
5045 
5051 
5052  int foobar = (cfg_OptimiseBedriftsmodelCrops.value())? (int)toc_Foobar : (int)tov_Undefined; //bedriftsmodel crops/almass crops
5053 
5054  m_cropParameters.resize(foobar*top_Foobar);
5055  m_alfa.resize(foobar*tos_Foobar);
5056  m_beta1.resize(foobar*tos_Foobar);
5057  m_beta2.resize(foobar*tos_Foobar);
5058  m_Nnorm.resize(foobar*tos_Foobar);
5059  m_biomass_factors.resize(foobar*tos_Foobar);
5060  m_fixed.resize(foobar*toof_Foobar);
5061  m_fodder.resize(foobar*toof_Foobar);
5062  m_FUKey.resize(foobar*toof_Foobar);
5063  m_sellingPrice.resize(foobar*toof_Foobar*tos_Foobar);
5067  m_winterMax.resize(toof_Foobar);
5069 
5071  //fill them with -1
5082  }
5083 }
5084 
5085 
5087  for(int i=0; i< (int) m_farm_data.size(); i++){
5088  if(m_farm_data[i]->md_almass_no == a_almass_no) return m_farm_data[i] -> md_farmType;
5089  }
5090  g_msg->Warn( WARN_BUG, "almass_no from farms_data doesn't match any of the numbers from farmrefs file", "" );
5091  exit(0);
5092 }
5093 
5094 Livestock::Livestock(TTypesOfAnimals a_animalType, int a_number){
5095  m_animalType=a_animalType;
5096  m_number=a_number;
5097  m_NanimUsable=0;
5098  m_FUdemand=0;
5099 
5100 }
5101 
5106 CropOptimised::CropOptimised(TTypesOfCrops a_cropType, double a_initialArea){
5107  m_cropType=a_cropType;
5108  m_cropType_almass = tov_Undefined; //just in case
5109  m_initialArea=a_initialArea;
5110 }
5111 
5112 CropOptimised::CropOptimised(TTypesOfVegetation a_cropType, double a_initialArea){
5113  m_cropType_almass = a_cropType;
5114  m_cropType = toc_Foobar; //just in case initialize it
5115  m_initialArea=a_initialArea;
5116 }
5117 
5119 
5120 }
5121 
5122 
5123 
5125 
5130  // First we need to assign the permanent crops if any.
5131  if (m_PermCrops.size()>0) {
5132  // We have something to do
5133  for (int i=0; i<(int)m_PermCrops.size(); i++) {
5135  }
5136 
5137  //check if in case there are no rotational crops - all fields have been assigned a perm crop
5138  if(m_area_rot ==0) { //so there's need to check
5139  for(int i=0; i<(int)m_fields.size(); i++){
5140  if(m_fields[i]->GetRotIndex() != -4){ //there is a field that is not assigned a perm crop!
5141  m_fields[i]->SetRotIndex(-4);
5142  TTypesOfVegetation tov = m_PermCrops[0].Tov; //just take the first perm crop?
5143  m_fields[i]->SetVegType(tov, tov_Undefined); //need a tov of one of the assigned perm crops
5144  }
5145  }
5146  }
5147 
5148  }
5149 
5151 }
5152 
5153 OptimisingFarm::OptimisingFarm(FarmManager* a_myfarmmanager, int a_No) : Farm(a_myfarmmanager)
5154 {
5155 
5156 
5157  m_farmtype = tof_OptimisingFarm; //this is almass farm type (and not the optimising farm type - see OptimisingFarm::Initialize)
5158  m_almass_no = a_No;
5159  force_deliberation = false;
5161 
5162  //assign goals - DEFAULT values. Later FarmManager assigns main goals again.
5164  //m_pest_goal = tofg_profit;
5165  //m_fert_goal = tofg_profit;
5166 
5167  //initialize the actual and expected values
5168  m_actual_profit=0;
5169  m_actual_income=0;
5170  m_actual_costs=0;
5172  m_exp_profit=0;
5173  m_exp_income=0;
5174  m_exp_costs=0;
5176 
5177  //initialize the dec. mode counters
5178  m_decision_mode_counters.resize(4);
5180 
5181  m_animals_numbers.resize(0);
5182  animals_no = 0;
5183 
5184 }
5185 
5186 
5188 
5189  //assign to each farm: farm type, farm size, real ID and soil type + soil subtype
5190  int size=(int)a_pfm->pm_data->m_farm_data.size();
5191  for(int i=0; i<size; i++){
5192  if(m_almass_no==a_pfm->pm_data->m_farm_data[i]->md_almass_no){
5193  m_farmType=a_pfm->pm_data->m_farm_data[i]->md_farmType;
5194  m_farmSize=a_pfm->pm_data->m_farm_data[i]->md_farmSize;
5195  m_farmRealID=a_pfm->pm_data->m_farm_data[i]->md_farmRealID;
5196  m_soilType=a_pfm->pm_data->m_farm_data[i]->md_soilType;
5197  m_soilSubType=a_pfm->pm_data->m_farm_data[i]->md_soilSubType;
5198  }
5199  }
5200 
5201  //create livestock
5202  for(int i=0; i<toa_Foobar; i++){
5203  int index=-1;
5204  int livestocknum=a_pfm->pm_data->Get_livestockNumbersSize();
5205  int j;
5206  for(j=0; j<livestocknum; j += (toa_Foobar+1)){
5207  if((a_pfm->pm_data->Get_livestockNumber(j))==m_almass_no){
5208  index=j;
5209  }
5210  }
5211  //test for index!!
5212  if(index==-1){
5213  g_msg->Warn( WARN_BUG, "Farm's almass_no doesn't match any of the numbers within the livestock numbers vector", "" );
5214  exit(0);
5215  }
5216  int index2 = index + 1 + i;
5217  int number = a_pfm->pm_data->Get_livestockNumber(index2);
5218  if (number!=0){
5219  Livestock * p_lvs;
5220  TTypesOfAnimals livestock_type = a_pfm->pm_data->Get_livestockTypes(i);
5221  p_lvs = new Livestock(livestock_type, number);
5222  Set_Livestock(p_lvs);
5223  }
5224  }
5225 
5226  //create crops
5227  int no_crops = (cfg_OptimiseBedriftsmodelCrops.value())? toc_Foobar : a_pfm->pm_data->Get_noCrops(); //bedriftsmodel crops/almass crops
5228 
5229  for(int i=0; i<no_crops; i++){ //crop areas vector contains only the crops that are used, not all tov types!
5230  int index=-1;
5231  int croparea=a_pfm->pm_data->Get_cropAreasSize();
5232  int j;
5233  for(j=0; j<croparea; j+=(no_crops+1)){ //+1 becuase in the vector we store also farm numbers
5234  if((a_pfm->pm_data->Get_cropArea(j))==m_almass_no){
5235  index=j;
5236  break;
5237  }
5238  }
5239  //test for index!!
5240  if(index==-1){
5241  g_msg->Warn( WARN_BUG, "Farm's almass_no doesn't match any of the numbers within the crop areas vector", "" );
5242  exit(0);
5243  }
5244  int index2= index + 1 + i;
5245  double area=a_pfm->pm_data->Get_cropArea(index2);
5246 
5247  int foobar = (cfg_OptimiseBedriftsmodelCrops.value())? (int)toc_Foobar : (int)tov_Undefined; //bedriftsmodel crops/almass crops
5248 
5249  CropOptimised *p_crop;
5250  int index3 = -1;
5252  TTypesOfCrops crop_type = a_pfm->pm_data->Get_cropTypes(i);
5253  p_crop = new CropOptimised(crop_type, area);
5254  index3 = foobar*tofs_Foobar*tos_Foobar*m_farmType + foobar*tofs_Foobar*m_soilType + foobar*m_farmSize + crop_type; //crop_type is TTypesOfCrops
5255  }
5256  else{
5257  TTypesOfVegetation crop_type = a_pfm->pm_data->Get_cropTypes_almass(i);
5258  p_crop = new CropOptimised(crop_type, area);
5259  index3 = foobar*tofs_Foobar*tos_Foobar*m_farmType + foobar*tofs_Foobar*m_soilType + foobar*m_farmSize + crop_type; //crop_type is TTypesOfVegetation
5260  }
5261  //added 01.05: save the rot max ad min
5262  p_crop->m_rotationMax = m_OurManager->pm_data->Get_rotationMax(index3);
5263  p_crop->m_rotationMin = m_OurManager->pm_data->Get_rotationMin(index3);
5264 
5265  //add crop to the list of crops
5266  Set_Crop(p_crop);
5267  }
5268 }
5269 
5270 AnimalFarm::AnimalFarm (FarmManager* a_fred, int a_No): OptimisingFarm(a_fred, a_No)
5271 {
5272  m_fakeCrop = new CropOptimised(); //("FakeCrop", 0)
5273  cash_crops_allowed = true;
5274 }
5275 
5276 NonAnimalFarm::NonAnimalFarm (FarmManager* a_myfarmmanager, int a_No): OptimisingFarm(a_myfarmmanager, a_No){
5277  ;
5278 }
5279 
5280 OptimisingPigFarm::OptimisingPigFarm(FarmManager* a_myfarmmanager, int a_No):AnimalFarm(a_myfarmmanager, a_No){
5281 
5282 }
5283 
5284 OptimisingCattleFarm::OptimisingCattleFarm(FarmManager* a_myfarmmanager, int a_No):AnimalFarm(a_myfarmmanager, a_No){
5285 }
5286 
5287 OptimisingPlantFarm::OptimisingPlantFarm(FarmManager* a_myfarmmanager, int a_No):NonAnimalFarm(a_myfarmmanager, a_No){
5288 
5289 }
5290 
5291 OptimisingOtherFarm::OptimisingOtherFarm(FarmManager* a_myfarmmanager, int a_No):NonAnimalFarm(a_myfarmmanager, a_No){
5292 }
5293 
5294 void OptimisingFarm::Init(ofstream * ap_output_file){
5295 
5296  int foobar = (cfg_OptimiseBedriftsmodelCrops.value())? (int)toc_Foobar : (int)tov_Undefined;
5297 
5298  FarmLevelCalculation(); //could stay in the constructor, but for clarity should be here
5299  createCropsLists(foobar);
5300  OptimiseFarm(foobar);
5301  Print_FarmVariables(ap_output_file);
5302 
5305  Make_rotations();
5306  }
5307  else{ //need to create almass crop vector and do all the things that are done otherwise in Make_rotations
5310  m_rotation.push_back(tov_SpringBarley); //put there one crop for the hidden year - m_rotation is used to initialize
5311 
5312  //deal with perm crops (copied from make rotations):
5313  int area_perm = 0; //sum of areas of permanent crops
5314  int no_perm=0;
5315  for(int i = 0; i < (int)m_crops_almass.size(); i++){
5316  TTypesOfVegetation tov = m_crops_almass[i].Tov;
5317 
5319  tov==tov_PermanentGrassLowYield || tov==tov_YoungForest || tov==tov_OrchardCrop) { //|| tov==tov_Orchard
5320  int pct = (int)(m_crops_almass[i].Number + 0.5); //round a double to int
5321  PermCropData pcd = {tov, pct};
5322  m_PermCrops.push_back(pcd);
5323  no_perm++;
5324  area_perm += pct;
5325  }
5326  }
5327  }
5329  Print_rotations(ap_output_file);
5330  }
5331 
5332 }
5333 
5337  int sum_centroidx = 0;
5338  int sum_centroidy = 0;
5339  int no_fields = (int)m_fields.size();
5340  for (int i=0; i<no_fields; i++){
5341  sum_centroidx += m_fields[i]->GetCentroidX();
5342  sum_centroidy += m_fields[i]->GetCentroidY();
5343  }
5344  m_farm_centroidx = sum_centroidx/no_fields;
5345  m_farm_centroidy = sum_centroidy/no_fields;
5346 }
5347 
5349 
5351  return true;
5352  }
5353  else{
5354  double BIherb = findCropByName_almass (a_tov_type)->m_BIHerb;
5355  if (BIherb > 0) return true;
5356  else return false;
5357  }
5358 }
5359 
5361 
5363  return true;
5364  }
5365  else{
5366  double BIfi = findCropByName_almass (a_tov_type)->m_BIFi;
5367  if (BIfi > 0) return true;
5368  else return false;
5369  }
5370 }
5371 
5373 
5374  if(m_main_goal==tofg_yield){ // || m_pest_goal == tofg_yield){ //in case we give farmers different goals - include also the pest_goal
5376  }
5377  else return 1; //for other farmer types
5378 }
5379 
5381 
5385  int no_farmers = (int)m_neighbours.size();
5386 
5387  if(no_farmers!=0){ //if the list is empty - no neighbours
5388  bool ok=false;
5389  vector<OptimisingFarm*>neighbours_copy = m_neighbours;
5390  for(int a=0; ok==false && neighbours_copy.size()>0; a++){
5391  srand ((unsigned)time(NULL)); //warning?
5392  int neighbour = rand() % (no_farmers-a); //returns a random int number from the range: <0, no_farmers-1-a> - need to subtract those remved from the list-there is 'a' removed neighbours
5393  m_previously_imitated_neighbour = neighbours_copy[neighbour];
5394  if(m_farmSize==tofs_Private){ //then look just at the soil type
5395  if(m_soilType!=tos_Clay){ //private with sand or other soil
5398  ok=true; //found somebody to imitate
5399  }
5400  else{
5401  neighbours_copy.erase(neighbours_copy.begin() + neighbour);
5402  }
5403  }
5404  else{ //private with clay
5407  ok=true; //found somebody to imitate
5408  }
5409  else{
5410  neighbours_copy.erase(neighbours_copy.begin() + neighbour);
5411  }
5412  }
5413  }
5414  else if(m_soilType!=tos_Clay){ //business farm with sand or other soil
5417  ok=true; //found somebody to imitate
5418  }
5419  else{
5420  neighbours_copy.erase(neighbours_copy.begin() + neighbour);
5421  }
5422  }
5423  else{ //business farm with clay soil
5426  ok=true; //found somebody to imitate
5427  }
5428  else{
5429  neighbours_copy.erase(neighbours_copy.begin() + neighbour);
5430  }
5431  }
5432 
5433  }
5434  if(ok==true){ //found a neighbouring farmer to imitate
5436  }
5437  else{ //try to find a neighbour with at least the same farm type
5438  neighbours_copy = m_neighbours; //first restart the neighbours copy!
5439  for(int a=0; ok==false && neighbours_copy.size()>0; a++){ //040713 - do not accept a farm with empty rot crops
5440  srand ((unsigned)time(NULL)); //warning?
5441  int neighbour = rand() % (no_farmers-a); //returns a random int number from the range: <0, no_farmers-1-a> - need to subtract those remved from the list-there is 'a' removed neighbours
5442  m_previously_imitated_neighbour = neighbours_copy[neighbour];
5444  ok=true;
5445  }
5446  else{
5447  neighbours_copy.erase(neighbours_copy.begin() + neighbour);
5448  }
5449  }
5450  if(ok==true){
5452  }
5453  else{
5454  m_previously_imitated_neighbour = this; //no neighbour that fits - copy yourself
5455  #ifdef _DEBUG
5456  char errornum[ 20 ];
5457  sprintf( errornum, "%d", m_almass_no );
5458  g_msg->Warn( WARN_BUG, "No farm with a matching farm type to imitate: ", errornum );
5459  #endif
5461  }
5462  }
5463  }
5464 
5465 
5466  else{ //no neighboring farmers //just set yourself
5469  }
5470 }
5471 
5473 
5475 
5476 }
5477 
5483  //pick a farmer to copy (imitation startegy)/ or compare with and possibly copy (social comparison strategy) if this is the first time this function is called: year 8
5484  if(g_date->GetYearNumber() == 8){
5486  }
5487 
5488  //1. get the values of parameters
5489  double min_certainty = cfg_Min_certainty.value();
5490  if(cfg_OnlyDeliberation.value()) min_certainty = 0;
5491 
5492  //2. determine the satisfaction level: already done in the ActualProfit()
5493 
5494  //3. determine the certainty level
5495  double sum_of_sat_levels=0;
5496  for(int i=0; i<5; i++){
5497  sum_of_sat_levels += m_previous_satisfaction_levels[i];
5498  }
5499  m_certainty_level = sum_of_sat_levels/5.0; // i.e. take 5 years into account
5500 
5501  //4. choose the decision mode
5502  //'if' for forcing deliberation:
5503  if(force_deliberation){ //do the same as when deliberation is chosen normally
5505  m_totalFUdemand=m_totalFUdemandBefore; //restart the fodder demand to the original value
5506  m_totalFUgrown = 0; //restart
5508  Make_almass_crops_vector(); //makes m_crops_almass
5509  Make_rotational_crops(); //makes new m_rotational_crops - based on m_crops_almass
5511  force_deliberation=false;
5512  }
5513  else{
5514  if(m_certainty_level < min_certainty){
5515  if(m_need_satisfaction_level == 1 ){ //IMITATION (high sat., low cert.)
5517  //now imitate:
5519  m_rotational_crops_copy = m_rotational_crops; //m_rotational_crops_copy is used for finding a crop for a given field - in Match_crop_to_field function.
5520  } //imitation over
5521 
5522  else{ //SOCIAL COMPARISON - similar to imitation, but includes comparison (low sat., low cert.)
5524  //compare yourself to the neighbour: this depends on your goal
5525  bool imitate=false;
5526  if(m_main_goal == tofg_profit){
5527  if(m_actual_profit < m_previously_imitated_neighbour->Get_actual_profit()){
5528  imitate=true;
5529  }
5530  }
5531  else if (m_main_goal == tofg_yield){
5532  if(m_actual_aggregated_yield < m_previously_imitated_neighbour->Get_actual_aggregated_yield()){
5533  imitate=true;
5534  }
5535  }
5536  else if (m_main_goal == tofg_environment) {
5537  if(m_actual_aggregated_yield < m_previously_imitated_neighbour->Get_actual_aggregated_yield() && m_actual_profit < m_previously_imitated_neighbour->Get_actual_profit()){//compare both
5538  imitate=true;
5539  }
5540  }
5541 
5542  if(imitate){
5544  }
5545  //else: just continue
5546  m_rotational_crops_copy = m_rotational_crops; //this happens for both cases - imitate or not
5547  } //social comparison over
5548  } //high uncertainty
5549 
5550  else{ //low uncertainty (= high certainty)
5551  int value_for_satisfaction = 1; //1 for a simulation with not only deliberation
5552  if(cfg_OnlyDeliberation.value()) value_for_satisfaction = 10; //10 - then everybody deliberates
5553  if(m_need_satisfaction_level == value_for_satisfaction){ //REPETITION (high sat., high cert.)
5555  //continue with the same set of crops - see line after else!
5556  }
5557  else{ //DELIBERATION - i.e. optimise to make a new m_rotational_crops (low sat., high cert.)
5559  m_totalFUdemand=m_totalFUdemandBefore; //restart the fodder demand to the original value
5560  m_totalFUgrown = 0; //restart
5562  Make_almass_crops_vector(); //makes m_crops_almass
5563  Make_rotational_crops(); //makes new m_rotational_crops - based on m_crops_almass
5564  }
5565  m_rotational_crops_copy = m_rotational_crops; //do this for both cases
5566  }
5567  }
5568 }
5569 
5571  createVariableCrops(a_foobar);
5572 }
5573 
5574 void AnimalFarm::createCropsLists(int a_foobar){
5576  createFodderCrops(a_foobar);
5577 }
5578 
5582  int n = (int)m_crops.size();
5583  for (int i=0; i < n; ++i) {
5584  int crop_type=(cfg_OptimiseBedriftsmodelCrops.value())? (int)m_crops[i]->m_cropType : (int)m_crops[i]->m_cropType_almass;
5585  int index=a_foobar*m_farmType + crop_type;
5586  if (m_OurManager->pm_data->Get_fixed(index)){ //if the crop is fixed, attach it to the list fixedCrops
5587  m_fixedCrops.push_back(m_crops[i]);
5588  }
5589  else{
5590  CropSort cs = {0., m_crops[i]}; //an object with a key and a pointer to crop
5591  m_variableCrops.push_back(cs);
5592  }
5593  }
5594 }
5595 
5599  int n = (int)m_crops.size();
5600  for (int i=0; i < n; ++i) {
5601  int crop_type=(cfg_OptimiseBedriftsmodelCrops.value())? (int)m_crops[i]->m_cropType : (int)m_crops[i]->m_cropType_almass;
5602  int index = a_foobar*m_farmType + crop_type;
5603  if(m_OurManager->pm_data->Get_fodder(index)){ //if the crop is a fodder crop...
5604  if(!(m_OurManager->pm_data->Get_fixed(index))){ //check if it is not fixed and attach it to the list
5605  CropSort cs={0., m_crops[i]};
5606  m_fodderCrops.push_back(cs);
5607  }
5608  }
5609  }
5610 }
5611 
5614 
5615  findTotalArea();
5616  findTotalNanim();
5617  findNanim();
5618  findFodderDemand(); //this function cannot be called in the constructor!
5620  preventCashCrops();
5621  }
5622 }
5623 
5629  m_totalArea=0.;
5630  for (int i=0; i< (int) m_crops.size(); i++) {
5631  m_totalArea+=m_crops[i]->m_initialArea;
5632  }
5634 
5635  if(!cfg_UseBedriftsmodelFarmAreas.value()){ //almass farm areas used: just sum the fields area
5636  double area_copy = m_totalArea; //ha
5637  m_totalArea = GetAreaDouble()/10000; //change from sq m to ha
5638  m_area_scaling_factor = m_totalArea/area_copy;
5639  }
5640  //otherwise do nothing: total area = sum of initial crop areas (see the for loop)
5641 }
5642 
5646  m_totalNanim = 0;
5647  for (int i=0; i< (int) m_livestock.size(); i++){
5648  string str_AUKey="AUKey";
5649  string str_Nusable="Nusable";
5650  TTypesOfAnimals index=m_livestock[i]->m_animalType;
5651  double AUKey = m_OurManager->pm_data->Get_livestockParameter(tolp_Foobar*index + m_OurManager->TranslateLivestockParametersCodes(str_AUKey)); //Number of animal units (AU, DE-dyreenheder) -> hkg N per year
5652  double Nusable = m_OurManager->pm_data->Get_livestockParameter(tolp_Foobar*index + m_OurManager->TranslateLivestockParametersCodes(str_Nusable)); // [%] Usable fertilizer from livestock
5653  double number = m_livestock[i]->m_number;
5654 
5655  if(!cfg_UseBedriftsmodelFarmAreas.value()){ //almass farm areas - need to scale the livestock numbers; we don't even have to take integer...
5656  number *= m_area_scaling_factor;
5657  }
5658 
5659  double NanimUsable = number*AUKey*Nusable*100; // [1*hkg/yr*1*100 = kg/yr] Usable fertilizer from livestock
5660  m_livestock[i]->m_NanimUsable = NanimUsable;
5661  m_totalNanim += NanimUsable;
5662  }
5663 }
5664 
5668  }
5669 
5673  m_totalFUdemand=0;
5674  for(int i=0; i< (int) m_livestock.size(); i++){
5675  string str_FUuKey="FUuKey";
5676  TTypesOfAnimals index=m_livestock[i]->m_animalType;
5677  double FUuKey=m_OurManager->pm_data->Get_livestockParameter(tolp_Foobar*index + m_OurManager->TranslateLivestockParametersCodes(str_FUuKey)); //number of fodder units needed per one animal per year
5678  double number = m_livestock[i]->m_number;
5679 
5680  if(!cfg_UseBedriftsmodelFarmAreas.value()){ //almass farm areas - need to scale the livestock numbers; we don't even have to take integer...
5681  number *= m_area_scaling_factor;
5682  }
5683 
5684  if(number>0){
5685  double FUdemand=FUuKey*number;
5686  m_livestock[i]->m_FUdemand = FUdemand;
5687  m_totalFUdemand+=FUdemand;
5688  }
5689  }
5690  m_totalFUdemandBefore=m_totalFUdemand; //just to know afterwards the total demand
5691 }
5692 
5694 
5700  m_totalFUdemand=0;
5701  m_totalFUgrown=0;
5702 }
5703 
5705 
5710  CropOptimised *ms = findCropByName_almass ("MaizeSilage");
5711  if(m_totalArea_original < 30){ //cattle farms with area < 30 ha do not have maize silage!
5712  ms->m_rotationMax = 0;
5713  }
5714 
5715  CropOptimised *wwheat = findCropByName_almass ("WinterWheat");
5716  CropOptimised *wrye = findCropByName_almass ("WinterRye");
5717  CropOptimised *srape = findCropByName_almass ("SpringRape");
5718  CropOptimised *wrape = findCropByName_almass ("WinterRape");
5719  CropOptimised *fpeas = findCropByName_almass ("FieldPeas");
5720  CropOptimised *potatoes = findCropByName_almass ("Potatoes");
5721  CropOptimised *potind = findCropByName_almass ("PotatoesIndustry");
5722  CropOptimised *seedg1 = findCropByName_almass ("SeedGrass1");
5723  CropOptimised *seedg2 = findCropByName_almass ("SeedGrass2");
5724 
5726 
5727  wwheat->m_rotationMax = 0;
5728  wrye->m_rotationMax = 0;
5729  srape->m_rotationMax = 0;
5730  wrape->m_rotationMax = 0;
5731  fpeas->m_rotationMax = 0;
5732  potatoes->m_rotationMax = 0;
5733  potind->m_rotationMax = 0;
5734  seedg1->m_rotationMax = 0;
5735  seedg2->m_rotationMax = 0;
5736 
5737  cash_crops_allowed=false;
5738  }
5739  else if(m_soilType==tos_Sand && m_totalArea_original >= 15 && m_soilSubType == 0){ //v. small prob. of having cash crops
5740 
5741  //see: http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution
5742  std::random_device rd;
5743  std::mt19937 gen(rd());
5744  distribution_type2 dis(0, 1);
5745  double random_no = dis(gen);
5746 
5747  if(random_no > 0.1){ //so in 90% of cases
5748  wwheat->m_rotationMax = 0;
5749  wrye->m_rotationMax = 0;
5750  srape->m_rotationMax = 0;
5751  wrape->m_rotationMax = 0;
5752  fpeas->m_rotationMax = 0;
5753  potatoes->m_rotationMax = 0;
5754  potind->m_rotationMax = 0;
5755  seedg1->m_rotationMax = 0;
5756  seedg2->m_rotationMax = 0;
5757 
5758  cash_crops_allowed=false;
5759  }
5760  }
5761  //else nothing - allow cash crops
5762 
5763 }
5764 
5765 void OptimisingFarm::OptimiseFarm(int a_foobar){
5766 
5767  optimizeCrops(a_foobar);
5768  sortCrops(m_variableCrops, "GM" );//ORDER OPTIMISED CROPS WRT HIGHEST GM
5769  randomizeCropList(m_variableCrops, "GM"); //shuffles elements of the list with equal GMs
5770  assignFixed();
5771  sumMinAreas();
5772  determineAreas(a_foobar);
5773 
5774  if(m_farmSize == tofs_Business){
5776  }
5777 
5779 
5781 
5783  m_totalNt=total(tocv_Nt); //total amount of Nt at a farm - summed for all crops
5793  else m_totalProfit = total(tocv_GM);
5794 }
5795 
5797 
5801  for (int i=0; i< (int) m_crops.size(); i++){
5802 
5803  //1. define the benefit; for non-fodder crops it is simply a selling price ;
5804  double benefit;
5805  int crop_type=(cfg_OptimiseBedriftsmodelCrops.value())? (int)m_crops[i]->m_cropType : (int)m_crops[i]->m_cropType_almass;
5806  int index = a_foobar*m_farmType + crop_type;
5807  bool fodder = m_OurManager->pm_data->Get_fodder(index);
5808  if(fodder){
5809  double FUKey = m_OurManager->pm_data->Get_FUKey(index);
5810  benefit = FUKey * cfg_Price_FU.value();
5811  }
5812  else {benefit = m_OurManager->pm_data->Get_sellingPrice(a_foobar*tos_Foobar*m_farmType + a_foobar*m_soilType + crop_type);}
5813 
5814  CropOptimised * crop = m_crops[i]; //define a pointer which is passed in the functions below
5815 
5816  crop->m_benefit = benefit; //added 090114
5817 
5818  //for SA: modify the prices of crops included in the analysis
5819  if(cfg_Sensitivity_analysis.value()){ //modify the prices only if this is a sensitivity analysis/calibration run
5821  if(crop_type==toc_Oats){
5822  if(m_farmType != toof_Pig && m_farmType != toof_Cattle){//don't modify for these farms - for them the price is zero for this crop - becasue it is a fodder crop!
5823  benefit = cfg_Price_Oats.value();
5824  }
5825  }
5826  else if(crop_type==toc_WWheat){ //not fodder
5827  benefit = cfg_Price_WWheat.value();
5828  }
5829  }
5830  else{//almass crop set
5831  if(crop_type==tov_SpringBarley){ //fodder for cattle and pig farms: price is zero if crop is a fodder crop. so changing price will affect only non-animal farms.
5832  if(m_farmType != toof_Pig && m_farmType != toof_Cattle){//don't modify for these farms - for them the price is zero for this crop - becasue it is a fodder crop!
5833  benefit = cfg_Price_SBarley.value();
5834  }
5835  }
5836  else if(crop_type==tov_Oats){ //f for c and p
5837  if(m_farmType != toof_Pig && m_farmType != toof_Cattle){//don't modify for these farms - for them the price is zero for this crop - becasue it is a fodder crop!
5838  benefit = cfg_Price_Oats.value();
5839  }
5840  }
5841  else if(crop_type==tov_WinterBarley){ //f for c and p
5842  if(m_farmType != toof_Pig && m_farmType != toof_Cattle){//don't modify for these farms - for them the price is zero for this crop - becasue it is a fodder crop!
5843  benefit = cfg_Price_WBarley.value();
5844  }
5845  }
5846  else if(crop_type==tov_WinterWheat){ //not fodder
5847  benefit = cfg_Price_WWheat.value();
5848  }
5849  else if(crop_type==tov_Triticale){
5850  if(m_farmType != toof_Cattle){//don't modify for these farms - for them the price is zero for this crop - becasue it is a fodder crop!
5851  benefit = cfg_Price_Triticale.value();
5852  }
5853  }
5854  else if(crop_type==tov_WinterRape){ //not fodder
5855  benefit = cfg_Price_WRape.value();
5856  }
5857  else if(crop_type==tov_SpringRape){ //not fodder
5858  benefit = cfg_Price_SRape.value();
5859  }
5860  }
5861  }
5862 
5863 
5864  //2. optimize the crop
5865  findFertilizer(crop, a_foobar, benefit);
5866  findResponse(crop, a_foobar);
5867  findBIs(crop, benefit);
5868  fixBI(); //added 22.03.13
5869  findMWeedControl(crop);
5870  findYieldLoss(crop);
5871  findGrossMargin(crop, a_foobar, benefit);
5872 
5873  }
5874 }
5875 
5876 
5878 
5879  CropOptimised *CGG1 = findCropByName_almass("CloverGrassGrazed1");
5880  CropOptimised *CGG2 = findCropByName_almass("CloverGrassGrazed2");
5881  CropOptimised *GS1 = findCropByName_almass("SeedGrass1");
5882  CropOptimised *GS2 = findCropByName_almass("SeedGrass2");
5883 
5884  double CGG1area = CGG1->m_areaPercent;
5885  double CGG2area = CGG2->m_areaPercent;
5886  double GS1area = GS1->m_areaPercent;
5887  double GS2area = GS2->m_areaPercent;
5888  if(CGG1area!= CGG2area){ //even if this is a cattle farm - where CGG are fodder - it won't have any effect here since the areas are zero or at min, so there won't be any change.
5889  double area_sum = CGG1area + CGG2area;
5890  double CGG1min = CGG1->m_rotationMin; double CGG2min = CGG2->m_rotationMin;
5891  CGG1->m_areaPercent = area_sum/2; CGG2->m_areaPercent = area_sum/2;
5892  CGG1->m_areaVariable = area_sum/2 - CGG1min; CGG2->m_areaVariable = area_sum/2 - CGG2min;
5893  }
5894  if(GS1area!=GS2area){
5895  double area_sum = GS1area + GS2area;
5896  double GS1min = GS1->m_rotationMin; double GS2min = GS2->m_rotationMin;
5897  GS1->m_areaPercent = area_sum/2; GS2->m_areaPercent = area_sum/2;
5898  GS1->m_areaVariable = area_sum/2 - GS1min; GS2->m_areaVariable = area_sum/2 - GS2min;
5899  }
5900 }
5901 
5902 //-------------------------------------------------------------------------------------
5903 //------------------OPTIMISATION - THE SIMPLIFIED METHOD-------------------------------
5904 //-------------------------------------------------------------------------------------
5905 
5906 void OptimisingFarm::findFertilizer(CropOptimised * a_crop, int a_foobar, double benefit){
5907 
5911  int index = (cfg_OptimiseBedriftsmodelCrops.value())? a_foobar * m_soilType + a_crop->m_cropType : a_foobar * m_soilType + a_crop->m_cropType_almass;
5912 
5913  double beta1=m_OurManager->pm_data->Get_beta1(index);
5914  double beta2=m_OurManager->pm_data->Get_beta2(index);
5915  double nNorm=m_OurManager->pm_data->Get_Nnorm(index);
5916  double priceNt=cfg_Price_Nt.value();
5917 
5918  if(!beta2==0){
5919  a_crop->m_optimalN = -(beta1/beta2)*0.5; //01.03.12 save the optimal free fertilizer
5920  }
5921  else{ //if beta2 is =0, beta1 is also =0 -> so optimum is at 0.
5922  a_crop->m_optimalN = 0;
5923  }
5924 
5925  if(m_main_goal == tofg_profit){
5926 
5927  if(!beta2==0){ //beta2 is not 0
5928  double n1=-(beta1/beta2)*0.5; //optimal fertilizer supposing it's for free
5929  if(m_Nanim >= n1){ //there is more than you need, so check the norm:
5930  if (n1<nNorm){
5931  a_crop->m_n = n1; //apply optimal amount
5932  }
5933  else {
5934  a_crop->m_n = nNorm; //apply max allowed amount
5935  }
5936  a_crop->m_nt = 0; //don't buy fertilizer
5937  }
5938  else { //the optimal amount is larger than Nanim
5939  double nt1= 0.5*(priceNt/(benefit*beta2) - beta1/beta2) - m_Nanim; //optimal fertilizer Nt
5940  if (nt1>0){
5941  double n2=nt1+m_Nanim; //optimal total N
5942  if (n2<nNorm){
5943  a_crop->m_nt = nt1;
5944  a_crop->m_n = n2;
5945  }
5946  else {
5947  double p=nNorm-m_Nanim;
5948  if(p>=0){a_crop->m_nt = p;} //buy the diff between what you have (Nanim) and what is the max allowed
5949  else{a_crop->m_nt = 0;}// your Nanim is higher than the norm!
5950  a_crop->m_n = nNorm; //total amount is the max allowed, Nanim+(nNorm-Nanim)=nNorm
5951  }
5952  }
5953  else { //it doesn't pay off to buy fertilizer, so just use Nanim
5954  if(m_Nanim<=nNorm){a_crop->m_n = m_Nanim;} //apply fertilizer
5955  else {a_crop->m_n = nNorm;}
5956  a_crop->m_nt = 0;
5957  }
5958  }
5959  }
5960  else{ //beta2=0, so don't apply fertilizer, but in this model - apply Nanim if there is any
5961  if(m_Nanim<=nNorm){a_crop->m_n = m_Nanim;} //apply fertilizer
5962  else {a_crop->m_n = nNorm;}
5963  a_crop->m_nt = 0;
5964  }
5965 
5966  }
5967 
5968  else if (m_main_goal == tofg_yield) { //modified profit optimization algorithm
5969  if(!beta2==0){ //beta2 is not 0
5970  double n1=-(beta1/beta2)*0.5; //optimal fertilizer supposing it's for free
5971  if(m_Nanim >= n1){ //there is more than you need, so check the norm:
5972  if (n1<nNorm){
5973  a_crop->m_n = n1; //apply optimal amount
5974  }
5975  else {
5976  a_crop->m_n = nNorm; //apply max allowed amount
5977  }
5978  a_crop->m_nt = 0; //don't buy fertilizer
5979  }
5980  else { //the optimal amount is larger than Nanim
5981  if(n1>=nNorm){
5982  if(m_Nanim > nNorm){a_crop->m_nt = 0;}
5983  else{a_crop->m_nt = nNorm - m_Nanim;}//buy the diff between what you have (Nanim) and what is the max allowed
5984  a_crop->m_n = nNorm; //total amount is the max allowed
5985  }
5986  else{
5987  a_crop->m_nt = n1 - m_Nanim;
5988  a_crop->m_n = n1;
5989  }
5990  }
5991  }
5992  else{ //beta2=0, so don't apply fertilizer, but in this model - apply Nanim if there is any
5993  if(m_Nanim<=nNorm){a_crop->m_n = m_Nanim;} //apply fertilizer
5994  else {a_crop->m_n = nNorm;}
5995  a_crop->m_nt = 0;
5996  }
5997 
5998  }
5999  else if (m_main_goal == tofg_environment) { //apply less than a norm: the code copied from yield max - the only change is in calculation of n1 - mulitplied by 0.8.
6000  if(!beta2==0){ //beta2 is not 0
6001  double n1=-(beta1/beta2)*0.5 * cfg_Env_fert_multiplier.value(); //optimal fertilizer supposing it's for free; multiplier - to make this type use less fertilizer
6002  if(m_Nanim >= n1){ //there is more than you need, so check the norm:
6003  if (n1<nNorm){
6004  a_crop->m_n = n1; //apply optimal amount
6005  }
6006  else {
6007  a_crop->m_n = nNorm; //apply max allowed amount
6008  }
6009  a_crop->m_nt = 0; //don't buy fertilizer
6010  }
6011  else { //the optimal amount is larger than Nanim
6012  if(n1>=nNorm){
6013  if(m_Nanim > nNorm){a_crop->m_nt = 0;}
6014  else{a_crop->m_nt = nNorm - m_Nanim;}//buy the diff between what you have (Nanim) and what is the max allowed
6015  a_crop->m_n = nNorm; //total amount is the max allowed
6016  }
6017  else{
6018  a_crop->m_nt = n1 - m_Nanim;
6019  a_crop->m_n = n1;
6020  }
6021  }
6022  }
6023  else{ //beta2=0, so don't apply fertilizer, but in this model - apply Nanim if there is any
6024  if(m_Nanim<=nNorm){a_crop->m_n = m_Nanim;} //apply fertilizer
6025  else {a_crop->m_n = nNorm;}
6026  a_crop->m_nt = 0;
6027  }
6028  }
6029 }
6030 
6031 void OptimisingFarm::findResponse (CropOptimised * a_crop, int a_foobar){
6032 
6036  int index = (cfg_OptimiseBedriftsmodelCrops.value())? a_foobar * m_soilType + a_crop->m_cropType : a_foobar * m_soilType + a_crop->m_cropType_almass;
6037 
6038  double beta1=m_OurManager->pm_data->Get_beta1(index);
6039  double beta2=m_OurManager->pm_data->Get_beta2(index);
6040  double alfa=m_OurManager->pm_data->Get_alfa(index);
6041 
6042  double ntotal=a_crop->m_n;
6043  double resp1=alfa + beta1*ntotal + beta2*pow(ntotal,2);
6044  a_crop->m_resp = resp1;
6045 }
6046 
6047 void OptimisingFarm::findBIs(CropOptimised * a_crop, double benefit){
6053  int index = (cfg_OptimiseBedriftsmodelCrops.value())? (int)a_crop->m_cropType : (int)a_crop->m_cropType_almass;
6054 
6055  double alfaFi = crop_parameter(index, "AlfaFi");
6056  double alfaHerb = crop_parameter(index, "AlfaHerb");
6057  double alfaG = crop_parameter(index, "AlfaG");
6058  double alfaH = crop_parameter(index, "AlfaH");
6059  double alfaW = crop_parameter(index, "AlfaW");
6060  double betaFi = crop_parameter(index, "BetaFi");
6061  double betaHerb = crop_parameter(index, "BetaHerb");
6062 
6063  double priceFi = crop_parameter(index, "PriceFi");
6064  double priceHerb = crop_parameter(index, "PriceHerb");
6065  double priceG = crop_parameter(index, "PriceG");
6066  double priceH = crop_parameter(index, "PriceH");
6067  double priceW = crop_parameter(index, "PriceW");
6068 
6069  double resp1=a_crop->m_resp;
6070 
6071  if(alfaHerb>0){//make sure it is not zero!it is for Fodder beet
6072  double BIHerbMax = betaHerb/alfaHerb;
6073  double gainHerb = 0;
6074  double BIHerb = 0;
6075 
6076  if(m_main_goal == tofg_profit){
6077  gainHerb = benefit*resp1*alfaHerb/100 + priceG*alfaG + priceH*alfaH + priceW*alfaW;
6078  BIHerb = (gainHerb>priceHerb)? BIHerbMax : 0;
6079  a_crop->m_BIHerb = BIHerb;
6080  }
6081  else if (m_main_goal == tofg_yield){
6082  a_crop->m_BIHerb = BIHerbMax; //12.12.12
6083  }
6084  else if (m_main_goal == tofg_environment){
6085  gainHerb = benefit*resp1*alfaHerb/100 + priceG*alfaG + priceH*alfaH + priceW*alfaW;
6086  BIHerb = (gainHerb> (priceHerb * cfg_Env_pest_multiplier.value()))? BIHerbMax : 0;
6087  a_crop->m_BIHerb = BIHerb;
6088  }
6089  }
6090  else a_crop->m_BIHerb = 0; //BI for fodder beet in the original model (Bedriftsmodel)
6091 
6092  if(alfaFi>0){
6093  double BIFiMax = betaFi/alfaFi;
6094  double gainFi = 0;
6095  double BIFi = 0;
6096  if(m_main_goal == tofg_profit){
6097  gainFi = benefit*resp1*alfaFi/100;
6098  BIFi = (gainFi > priceFi) ? BIFiMax : 0;
6099  a_crop->m_BIFi = BIFi;
6100  }
6101  else if (m_main_goal == tofg_yield){
6102  a_crop->m_BIFi = BIFiMax;
6103  }
6104  else if (m_main_goal == tofg_environment){
6105  gainFi = benefit*resp1*alfaFi/100;
6106  if (gainFi > (priceFi * cfg_Env_pest_multiplier.value())){
6107  BIFi = BIFiMax;
6108  }
6109  else{
6110  BIFi = 0;
6111  }
6112  a_crop->m_BIFi = BIFi;
6113  }
6114  }
6115  else a_crop->m_BIFi = 0;
6116 
6117  double BIFi = a_crop->m_BIFi;
6118  double BIHerb = a_crop->m_BIHerb;
6119  double BI = BIFi+BIHerb;
6120  a_crop->m_BI = BI;
6121 }
6122 
6124 
6125  if(cfg_OptimiseBedriftsmodelCrops.value()){ //b. crops
6126  CropOptimised *fodderBeet = findCropByName ("FodderBeet");
6127  CropOptimised *sugarBeet = findCropByName ("SugarBeet");
6128  CropOptimised *potato = findCropByName ("Potato");
6129  CropOptimised *potatoFood = findCropByName ("PotatoFood");
6130 
6131  fodderBeet->m_BIHerb = 2.28; //seems it's constant - in the results of Bedriftsmodel, but herbicide parameters are = zero!
6132  sugarBeet->m_BIHerb = 2.28;
6133  fodderBeet->m_BI = fodderBeet->m_BIFi + fodderBeet->m_BIHerb;
6134  sugarBeet->m_BI = sugarBeet->m_BIFi + sugarBeet->m_BIHerb;
6135 
6136  //potatoes - everything fixed
6137  potato->m_BIHerb = 1.41; potato->m_BIFi = 9.28; potato->m_BI = 10.69;
6138  potatoFood->m_BIHerb = 1.41; potatoFood->m_BIFi = 9.28; potatoFood->m_BI = 10.69;
6139  }
6140  else{ //almass crops
6141  CropOptimised *FodderBeet = findCropByName_almass ("FodderBeet");
6142  CropOptimised *PotatoesIndustry = findCropByName_almass ("PotatoesIndustry");
6143  CropOptimised *Potatoes = findCropByName_almass ("Potatoes");
6144 
6145  FodderBeet->m_BIHerb = 2.28; //the values have to be now like in the bedriftsmodel //modified probability
6146  FodderBeet->m_BI = FodderBeet->m_BIHerb + FodderBeet->m_BIFi;
6147  PotatoesIndustry->m_BIHerb = 1.41; PotatoesIndustry->m_BIFi = 9.28; PotatoesIndustry->m_BI = 10.69;
6148  Potatoes->m_BIHerb = 1.41; Potatoes->m_BIFi = 9.28; Potatoes->m_BI = 10.69;
6149  }
6150 
6151 }
6152 
6157  int index = (cfg_OptimiseBedriftsmodelCrops.value())? (int) a_crop->m_cropType : (int) a_crop->m_cropType_almass;
6158 
6159  double betaG = crop_parameter(index, "BetaG");
6160  double betaH = crop_parameter(index, "BetaH");
6161  double betaW = crop_parameter(index, "BetaW");
6162  double alfaG = crop_parameter(index, "AlfaG");
6163  double alfaH = crop_parameter(index, "AlfaH");
6164  double alfaW = crop_parameter(index, "AlfaW");
6165  double BIHerb = a_crop->m_BIHerb;
6166 
6167  double grooming, hoeing, weeding =0;
6168  double g = betaG - BIHerb*alfaG;
6169  double h = betaH - BIHerb*alfaH;
6170  double w = betaW - BIHerb*alfaW;
6171  double BIHerbCorr = BIHerb;
6172 
6173  if(g <= 0){
6174  grooming=0;
6175  if(alfaG!=0) BIHerbCorr=betaG/alfaG;
6176  }
6177  else{grooming=g;}
6178  if(h <= 0){
6179  hoeing=0;
6180  if(betaH/alfaH < BIHerbCorr) BIHerbCorr=betaH/alfaH;
6181  }
6182  else{hoeing=h;}
6183  if(w <= 0){
6184  weeding=0;
6185  if(betaW/alfaW < BIHerbCorr) BIHerbCorr = betaW/alfaW;
6186  }
6187  else{weeding=w;}
6188 
6189 
6190  a_crop->m_grooming = grooming;
6191  a_crop->m_hoeing = hoeing;
6192  a_crop->m_weeding = weeding;
6193  if(BIHerbCorr < BIHerb){
6194  a_crop->m_BIHerb = BIHerbCorr;
6195  a_crop->m_BI = a_crop->m_BIHerb + a_crop->m_BIFi;
6196  }
6197 
6198 }
6199 
6205  int index = (cfg_OptimiseBedriftsmodelCrops.value())? (int) a_crop->m_cropType : (int) a_crop->m_cropType_almass;
6206 
6207  double alfaFi = crop_parameter(index, "AlfaFi");
6208  double alfaHerb = crop_parameter(index, "AlfaHerb");
6209  double betaFi = crop_parameter(index, "BetaFi");
6210  double betaHerb = crop_parameter(index, "BetaHerb");
6211 
6212  double BIHerb=a_crop->m_BIHerb;
6213  double BIFi=a_crop->m_BIFi;
6214 
6215  double lossHerb = betaHerb - alfaHerb*BIHerb;
6216  a_crop->m_lossHerb = lossHerb;
6217 
6218  double lossFi = betaFi - alfaFi*BIFi;
6219  a_crop->m_lossFi = lossFi;
6220 
6221  double totalLoss = lossHerb + lossFi;// [%]
6222  a_crop->m_totalLoss = totalLoss;
6223 }
6224 
6225 void OptimisingFarm::findGrossMargin(CropOptimised * a_crop, int a_foobar, double benefit){
6229  int index = (cfg_OptimiseBedriftsmodelCrops.value())? (int) a_crop->m_cropType : (int) a_crop->m_cropType_almass;
6230 
6231  double priceFi = crop_parameter(index, "PriceFi");
6232  double priceHerb =crop_parameter(index, "PriceHerb");
6233  double priceG =crop_parameter(index, "PriceG");
6234  double priceH =crop_parameter(index, "PriceH");
6235  double priceW =crop_parameter(index, "PriceW");
6236  double priceLM =crop_parameter(index, "PriceLM");
6237  double subsidy =crop_parameter(index, "Subsidy");
6238 
6239  double resp = a_crop->m_resp;
6240  double BIHerb = a_crop->m_BIHerb;
6241  double BIFi = a_crop->m_BIFi;
6242  double grooming = a_crop->m_grooming;
6243  double hoeing = a_crop->m_hoeing;
6244  double weeding = a_crop->m_weeding;
6245  double totalLoss = a_crop->m_totalLoss;
6246  double nt = a_crop->m_nt;
6247  double priceNt = cfg_Price_Nt.value();
6248 
6249  double income_ha = benefit*resp*(1-totalLoss/100)+subsidy;
6250  double costs_ha = BIHerb*priceHerb + BIFi*priceFi + grooming*priceG + hoeing*priceH + weeding*priceW + nt*priceNt + priceLM;
6251  double profit = income_ha - costs_ha;
6252 
6253  a_crop->m_costs_ha = costs_ha;
6254  a_crop->m_GM_Savings = profit;
6255 
6256  //29.02.12
6257  int index1 = (cfg_OptimiseBedriftsmodelCrops.value())? a_foobar * m_farmType + a_crop->m_cropType : a_foobar * m_farmType + a_crop->m_cropType_almass;
6258  bool fodder = m_OurManager->pm_data->Get_fodder(index1);
6259  if (fodder){
6260  a_crop->m_income_ha = subsidy; //because fodder crops can't be sold
6261  a_crop->m_GM = subsidy-costs_ha; //because fodder crops can't be sold
6262  a_crop->m_savings = profit;
6263  }
6264  else{
6265  a_crop->m_income_ha = income_ha;
6266  a_crop->m_GM = profit;
6267  a_crop->m_savings = 0; //this is not a fodder crop!
6268  }
6269 }
6270 
6271 //------------------------------------------------------------------------------//
6272 //-----------------FUNCTIONS RELATED TO CROPS AREA------------------------------//
6273 //------------------------------------------------------------------------------//
6274 
6276 
6280  m_assigned = 0;
6281  for (int i=0; i<(int)m_fixedCrops.size(); i++){//take only crops that are fixed
6282  double area = m_fixedCrops[i]->m_initialArea;
6283 
6284  if(!cfg_UseBedriftsmodelFarmAreas.value()){ //almass farm areas are in use, so scale the fixed crop area
6285  area *= m_area_scaling_factor;
6286  }
6287 
6288  double areaPercent= area/m_totalArea*100;
6289  m_fixedCrops[i]->m_areaPercent = areaPercent; //assign initial area in % for fixed crops
6290  m_assigned += areaPercent;//add areaPercent of a fixed crop to assigned
6291  }//now assigned is a number <0, 100> - excluded from the optimisation
6292 }
6293 
6298  for(int i=0; i<(int)m_variableCrops.size(); i++){
6299  double rotationMin = m_variableCrops[i].crop->m_rotationMin;
6300  m_assigned+=rotationMin; //the min area added to the area already assigned
6301  }
6302 }
6303 
6313  m_grownVariableCrops.clear();
6314 
6315  for(int i=0; i<(int)m_variableCrops.size(); i++){
6316  double areaPercent=0;
6317  double minArea=m_variableCrops[i].crop->m_rotationMin;
6318 
6319  int index1 = (cfg_OptimiseBedriftsmodelCrops.value())? a_foobar*m_farmType + m_variableCrops[i].crop->m_cropType : a_foobar*m_farmType + m_variableCrops[i].crop->m_cropType_almass;
6320 
6321  //next two lines necessary for animal farms' function version
6322  bool fodder = m_OurManager->pm_data->Get_fodder(index1);
6323  if (!fodder){ //this should be checked for animal farms, for other and plant - will always be false
6324  if (m_assigned<100){ //check if there is any area left at a farm
6325  double rotationMax = m_variableCrops[i].crop->m_rotationMax; //same as in else
6326 
6327  if(cfg_Areas_Based_on_Distribution.value()){ //added 170713
6328 
6329  double GMsum = 0;
6330  for(int k=i; k<(int)m_variableCrops.size(); k++){ //do it for each crop (calculate prob) to avoid getting area without any crop. Start with the current crop (k=i), i.e. exclude the crops that are already assigned area.
6331  if(m_variableCrops[k].crop->m_GM > 0 && m_variableCrops[k].crop->m_rotationMax>0){ //make sure you dont include crops that have rot max set to zero! then the area won't sum up to 100%
6332  GMsum += pow (m_variableCrops[k].crop->m_GM, 1);
6333  }
6334  }
6335  double base_prob = 0;
6336  if(m_variableCrops[i].crop->m_GM > 0){
6337  base_prob = pow(m_variableCrops[i].crop->m_GM, 1)/GMsum;
6338  }
6339  else base_prob = 0;
6340 
6341  //draw a random number
6342  std::random_device rd;
6343  distribution_type3 dis(-1.0, 1.0);
6344  std::mt19937 engine(rd());
6345  double random_number = dis(engine);
6346  if(base_prob == 1) random_number = 0; // this is the last crop on the list - don't manipulate the area
6347  double area_1 = base_prob * (1 + 0.2 * random_number) * (100 - m_assigned); //take only a percent of the remaining area!
6348  areaPercent = ( area_1 <= rotationMax)? area_1 : rotationMax;
6349  if (areaPercent > 100 - m_assigned) areaPercent = 100 - m_assigned; //added 280813
6350 
6351  }
6352  else{ //standard area assignment
6353  areaPercent = (rotationMax-minArea <= 100-m_assigned)? rotationMax : (100 - m_assigned+minArea); //check if the remaining area (100-assigned) is enough to assign max allowed area for a crop (max-min, which was already assigned, if not - assign the remaining area+min area
6354  }
6355 
6356  m_assigned += areaPercent - minArea; //add the assigned area (final area percent minus minimum; minimum was assigned before) to the total assigned area
6357  if(areaPercent>minArea){m_grownVariableCrops.push_back(m_variableCrops[i].crop);} //this might not be used for other than animal farms...but maybe - it would be nice to have such a list anyway
6358 
6359  }//m_assigned < 100
6360 
6361  else {areaPercent = minArea;}
6362 
6363  m_variableCrops[i].crop->m_areaPercent = areaPercent;
6364  double areaVar=areaPercent-minArea;
6365  m_variableCrops[i].crop->m_areaVariable = areaVar; //save the value of the area that can be changed! For farms other than animal this maybe could be used just in restrictions functions...
6366  }
6367  else{ //it is a fodder crop, so just save its min area under areaPercent
6368  m_variableCrops[i].crop->m_areaPercent = minArea;
6369  }
6370  }
6371 }
6372 
6373 void AnimalFarm::determineAreas(int a_foobar){
6379 
6380 /*If after this loop area assigned is < 100%, this means that the sum of the maximum allowed areas of non-fodder crops doesn't reach 100%;
6381 in such case introduce a fake crop to fill up the space till 100% (temporarily - until the determineFodderAreas function is called).*/
6382 
6383  m_fakeCropTest=false;
6384  if(m_assigned<100){ //use virtual 'fake crop'
6385  m_fakeCropTest = true;
6386  m_grownVariableCrops.push_back(m_fakeCrop); //append at the end (it is - it must be - the least profitable crop); this list is used in the determineFodderAreas function
6387  double areaP = 100-m_assigned;
6388  m_fakeCrop->m_GM = -1000000;
6389  m_fakeCrop->m_rotationMax = 100;
6390  m_fakeCrop->m_rotationMin = 0;
6391  m_fakeCrop->m_areaPercent = areaP;
6392  m_fakeCrop->m_areaVariable = areaP;
6393  m_assigned += areaP;
6394  }
6395 
6396  sortCrops(m_fodderCrops, "Savings"); //order fodder crops from the highest to the lowest savings resulting from growing a fodder crop - in relation to purchased fodder
6397  randomizeCropList(m_fodderCrops, "Savings"); //shuffles elements of the list with equal Savings
6398 
6399  sortCrops(m_variableCrops, "GM_Savings"); //has to be done before restrictions, but only for animal farms.
6400  randomizeCropList(m_variableCrops, "GM_Savings"); //shuffles elements of the list with equal GM_Savings. Fodder crops have their savings saved under GM_Savings, non-fodder - GM.
6401 
6402  correctFodderDemand(a_foobar); //correct demand for min areas and fixed crops
6403  determineFodderAreas(a_foobar);
6404 }
6405 
6406 //------------------------------------------------------------------------------//
6407 //---------FUNCTIONS RELATED TO RESTRICTIONS ON RELATIVE CROP AREAS-------------//
6408 //------------------------------------------------------------------------------//
6409 
6429  //1st restriction: winter rotation
6430  if(!cfg_Areas_Based_on_Distribution.value()){ //if this is true, skip this restriction
6432  }
6433 
6434  //2nd restriction: max share of winter crops area
6435  checkWinterCrops();
6436 
6437  if (!cfg_OptimiseBedriftsmodelCrops.value()){ //just for almass crop mode: make sure cgg1 and cgg2, sgg1 and sgg2 - have equal areas. added 26.03.13 -function since 110613
6438  Check_SG_and_CGG();
6439  }
6440 }
6441 
6446 
6447  //3rd restriction: cattle crops
6450  }
6451  else{
6453  }
6454 
6455 }
6456 
6461 
6462  //restriction - grow winter barley if you have winter rape. Just in Almass crops mode when crops assignement is based on GM distribution:
6465  }
6466 
6467 }
6468 
6470 
6475  CropOptimised *wWheat;
6476  CropOptimised *wRape;
6477  CropOptimised *sRape;
6478  CropOptimised *oats;
6479  CropOptimised *peas;
6480 
6482  wWheat = findCropByName("WWheat");
6483  wRape = findCropByName("WRape");
6484  sRape = findCropByName("SRape");
6485  oats = findCropByName("Oats");
6486  peas = findCropByName("Peas"); //fixed
6487  }
6488  else{
6489  wWheat = findCropByName_almass("WinterWheat");
6490  wRape = findCropByName_almass("WinterRape");
6491  sRape = findCropByName_almass("SpringRape");
6492  oats = findCropByName_almass("Oats");
6493  peas = findCropByName_almass("FieldPeas"); //fixed
6494  }
6495 
6496  double areaWWheat = wWheat->m_areaPercent;
6497  double areaWRape = wRape->m_areaPercent;
6498  double areaSRape = sRape->m_areaPercent;
6499  double areaOats = oats->m_areaPercent;
6500  double areaPeas = peas->m_areaPercent;
6501 
6502  double diff = areaWWheat - (areaWRape + areaSRape + areaOats + areaPeas); //difference;
6503  if (diff > 0){ //restriction is not fulfilled
6504  CropSort cs1 = {0., wRape}; //an object with a key for sorting and a pointer to crop
6505  CropSort cs2 = {0., sRape};
6506  CropSort cs3 = {0., oats};
6507  m_rotationCrops.clear();
6508  m_rotationCrops.push_back(cs1);
6509  m_rotationCrops.push_back(cs2);
6510  m_rotationCrops.push_back(cs3);
6511 
6512  sortCrops(m_rotationCrops, "GM"); //sorting the rotation crops wrt GM
6513 
6514  m_variableCrops2 = m_variableCrops; //initialize the new list and remove all 'winter rotation' crops:
6515  for(int s =(int)m_variableCrops2.size()-1; s>=0; s--){
6516  if(m_variableCrops2[s].crop==wWheat || m_variableCrops2[s].crop==wRape || m_variableCrops2[s].crop==sRape || m_variableCrops2[s].crop==oats){
6517  m_variableCrops2.erase(m_variableCrops2.begin() + s);
6518  }
6519  }
6520 
6521  double GM_WWheat = wWheat->m_GM;
6522  double areaMin = wWheat->m_rotationMin;
6523 
6524  for(int i=0; i<(int)m_rotationCrops.size() && diff!=0; i++){
6525  double areaRC = m_rotationCrops[i].crop->m_areaPercent;
6526  double rotationMaxRC = m_rotationCrops[i].crop->m_rotationMax;
6527  if(areaRC < rotationMaxRC){
6528  double GM_RC = m_rotationCrops[i].crop->m_GM;
6529  bool stopInnerLoop = false;
6530 
6531  for(int j=0; j<(int)m_variableCrops2.size() && stopInnerLoop==false; j++){
6532 
6533  double GM_var = m_variableCrops2[j].crop->m_GM;
6534 
6535  if(GM_RC + GM_WWheat < 2*GM_var){
6536  //add the variable crop
6537  double areaVC = m_variableCrops2[j].crop->m_areaPercent;
6538  double rotationMaxVC = m_variableCrops2[j].crop->m_rotationMax;
6539  if(areaWWheat - areaMin >= diff){
6540  if(rotationMaxVC - areaVC >= diff){
6541  areaVC += diff;
6542  areaWWheat -= diff;
6543  diff = 0; //finito
6544  stopInnerLoop = true;
6545  }
6546  else{
6547  areaWWheat -= rotationMaxVC - areaVC;
6548  diff -= (rotationMaxVC - areaVC);
6549  areaVC = rotationMaxVC;
6550  }
6551  }
6552  else{
6553  if(rotationMaxVC - areaVC >= areaWWheat - areaMin){
6554  areaVC += areaWWheat - areaMin;
6555  diff -= (areaWWheat - areaMin);
6556  areaWWheat = areaMin; // now you can only add rot crops! so stop the inner loop
6557  stopInnerLoop = true;
6558  }
6559  else{
6560  areaWWheat -= rotationMaxVC - areaVC;
6561  diff -= (rotationMaxVC - areaVC);
6562  areaVC = rotationMaxVC;
6563  }
6564  }
6565  m_variableCrops2[j].crop->m_areaPercent = areaVC;
6566  }
6567 
6568  else{
6569  //add rotational crop
6570 
6571  if(areaWWheat - areaMin >= diff/2){
6572  if(rotationMaxRC - areaRC >= diff/2){
6573  areaRC += diff/2;
6574  areaWWheat -= diff/2;
6575  diff = 0; //finito
6576  stopInnerLoop = true;
6577  }
6578  else{
6579  areaWWheat -= rotationMaxRC - areaRC;
6580  diff -= 2 * (rotationMaxRC - areaRC);
6581  areaRC = rotationMaxRC;
6582  stopInnerLoop = true; //take next rotation crop
6583  }
6584  }
6585  else{
6586  if(rotationMaxRC - areaRC >= areaWWheat - areaMin){
6587  areaRC += areaWWheat - areaMin;
6588  diff -= 2 * (areaWWheat - areaMin);
6589  areaWWheat = areaMin; //now you can only add rot crops!//so stop the inner loop:
6590  stopInnerLoop = true;
6591  }
6592  else{
6593  areaWWheat -= rotationMaxRC - areaRC;
6594  diff -= 2 * (rotationMaxRC - areaRC);
6595  areaRC = rotationMaxRC;
6596  stopInnerLoop = true; //take the next rotation crop
6597  }
6598  }
6599  }
6600  }//inner for-loop
6601  m_rotationCrops[i].crop->m_areaPercent = areaRC;
6602  }//if rot crop<rotmax //else - take the next rot crop, i++
6603  }//outer for
6604 
6605  //now the diff can be positive in two cases:
6606 
6607  //1. wwheat area is at zero - need to increase rotation crops - if possible
6608  if(areaWWheat==areaMin && diff > 0){
6609  double diff1=diff;
6611  if(diff1==0) {decreaseCrops(m_variableCrops2, diff);} //do it only if we actually managed to add the diff (=diff1)
6612  //to the rotation crops,i.e. diff1=0; if it's >0, then we added smth, but not enough and restriction can't be fulfilled.Then:
6613  else{
6614  double toCut = diff - diff1;
6616  diff = diff1; //restriction will be broken by diff1
6617  ofstream ofile("Restrictions.txt",ios::app);
6618  ofile << m_almass_no << '\t' << "winter rotation1 restriction broken, WWheat area at 0. Diff is: " << diff << endl;
6619  ofile.close();
6620  }
6621  }
6622 
6623  //2. it was always more profitable to grow rotation crops, but they were not
6624  //enough (maybe at max from the beginning) - increase variable crops, cut wwheat
6625 
6626  if(diff > 0 && areaWWheat - areaMin >= diff){
6627  areaWWheat -= diff;
6629  }
6630 
6631  wWheat->m_areaPercent = areaWWheat;
6632 
6633  }//if
6634 }//end of the function
6635 
6637 
6642  CropOptimised *wWheat;
6643  CropOptimised *wRape;
6644  CropOptimised *sRape;
6645  CropOptimised *oats;
6646  CropOptimised *peas;
6647 
6649  wWheat = findCropByName("WWheat");
6650  wRape = findCropByName("WRape");
6651  sRape = findCropByName("SRape");
6652  oats = findCropByName("Oats");//fodder
6653  peas = findCropByName("Peas"); //fixed
6654  }
6655  else{
6656  wWheat = findCropByName_almass("WinterWheat");
6657  wRape = findCropByName_almass("WinterRape");
6658  sRape = findCropByName_almass("SpringRape");
6659  oats = findCropByName_almass("Oats");//fodder
6660  peas = findCropByName_almass("FieldPeas"); //fixed
6661  }
6662 
6663  double areaWWheat = wWheat->m_areaPercent;
6664  double areaWRape = wRape->m_areaPercent;
6665  double areaSRape = sRape->m_areaPercent;
6666  double areaOats = oats->m_areaPercent;
6667  double areaPeas = peas->m_areaPercent;
6668 
6669  double diff = areaWWheat - (areaWRape + areaSRape + areaOats + areaPeas); //difference;
6670  if (diff > 0){ //restriction is not fulfilled
6671  CropSort cs1 = {0., wRape}; //an object with a key for sorting and a pointer to crop
6672  CropSort cs2 = {0., sRape};
6673  CropSort cs3 = {0., oats};
6674  m_rotationCrops.clear();
6675  m_rotationCrops.push_back(cs1);
6676  m_rotationCrops.push_back(cs2);
6677  m_rotationCrops.push_back(cs3);
6678 
6679  sortCrops(m_rotationCrops, "GM_Savings"); //sorting the rotation crops wrt GM
6680 
6681 
6682  m_variableCrops2 = m_variableCrops; //initiate the new list and remove all 'winter rotation' crops:
6683  for(int s=(int)m_variableCrops2.size()-1; s>=0; s--){
6684  if(m_variableCrops2[s].crop==wWheat || m_variableCrops2[s].crop==wRape || m_variableCrops2[s].crop==sRape || m_variableCrops2[s].crop==oats){
6685  m_variableCrops2.erase(m_variableCrops2.begin() + s);
6686  }
6687  }
6688 
6689  double GM_WWheat = wWheat->m_GM;
6690  double areaMin = wWheat->m_rotationMin;
6691 
6692  for(int i=0; i<(int)m_rotationCrops.size() && diff!=0; i++){
6693  double areaRC = m_rotationCrops[i].crop->m_areaPercent;
6694  double rotationMaxRC = m_rotationCrops[i].crop->m_rotationMax;
6695  double areaBeforeRC = areaRC;
6696  if(areaRC < rotationMaxRC){
6697  double GM_RC = m_rotationCrops[i].crop->m_GM_Savings;
6698  bool stopInnerLoop = false;
6699 
6700  for(int j=0; j<(int)m_variableCrops2.size() && stopInnerLoop==false; j++){
6701 
6702  double GM_var = m_variableCrops2[j].crop->m_GM_Savings;
6703 
6704  if(GM_RC + GM_WWheat < 2 * GM_var){
6705  //add variable
6706  double areaVC = m_variableCrops2[j].crop->m_areaPercent;
6707  double rotationMaxVC = m_variableCrops2[j].crop->m_rotationMax;
6708  double areaBefore = areaVC;
6709  if(areaWWheat - areaMin >= diff){
6710  if(rotationMaxVC - areaVC >= diff){
6711  areaVC += diff;
6712  areaWWheat -= diff;
6713  diff = 0; //finished
6714  stopInnerLoop = true;
6715  }
6716  else{
6717  areaWWheat -= rotationMaxVC - areaVC;
6718  diff -= (rotationMaxVC - areaVC);
6719  areaVC = rotationMaxVC;
6720  }
6721  }
6722  else{
6723  if(rotationMaxVC - areaVC >= areaWWheat - areaMin){
6724  areaVC += (areaWWheat - areaMin);
6725  diff -= (areaWWheat - areaMin);
6726  areaWWheat = areaMin; //now you can only add rot crops! so stop the inner loop
6727  stopInnerLoop=true;
6728  }
6729  else{
6730  areaWWheat -= rotationMaxVC - areaVC;
6731  diff -= (rotationMaxVC - areaVC);
6732  areaVC = rotationMaxVC;
6733  }
6734  }
6735  m_variableCrops2[j].crop->m_areaPercent = areaVC;
6736  //this just in an animal version, add if - checking if area has changed
6737  if(areaVC > areaBefore){
6738  int index = (cfg_OptimiseBedriftsmodelCrops.value())? toc_Foobar*m_farmType + m_variableCrops2[j].crop->m_cropType : tov_Undefined*m_farmType + m_variableCrops2[j].crop->m_cropType_almass;
6739  bool fodder = m_OurManager->pm_data->Get_fodder(index);
6740  if(fodder){ //this is a fodder crop - so you need to buy less fodder - totalFUt
6741  double resp = m_variableCrops2[j].crop->m_resp;
6742  double loss = m_variableCrops2[j].crop->m_totalLoss;
6743  double FUKey = m_OurManager->pm_data->Get_FUKey(index);
6744  double FUha = resp * (1-loss/100) * FUKey; //[ha * hkg/ha * FU/hkg = FU]
6745  double changeFU = (areaVC - areaBefore) * m_totalArea/100 * FUha; //positive
6746  m_totalFUt -= changeFU;
6747  m_totalFUgrown+=changeFU;
6748  }
6749  }
6750  }
6751  else{
6752  //add rotational
6753 
6754  if(areaWWheat - areaMin >= diff/2){
6755  if(rotationMaxRC - areaRC >= diff/2){
6756  areaRC += diff/2;
6757  areaWWheat -= diff/2;
6758  diff = 0; //finito
6759  stopInnerLoop = true;
6760  }
6761  else{
6762  areaWWheat -= rotationMaxRC - areaRC;
6763  diff -= 2 * (rotationMaxRC - areaRC);
6764  areaRC = rotationMaxRC;
6765  stopInnerLoop = true; //take next rotation crop
6766  }
6767  }
6768  else{
6769  if(rotationMaxRC - areaRC >= areaWWheat - areaMin){
6770  areaRC += areaWWheat - areaMin;
6771  diff -= 2 * (areaWWheat - areaMin);
6772  areaWWheat = areaMin; //now you can only add rot crops! so stop the inner loop:
6773  stopInnerLoop = true;
6774  }
6775  else{
6776  areaWWheat -= rotationMaxRC - areaRC;
6777  diff -= 2 * (rotationMaxRC - areaRC);
6778  areaRC = rotationMaxRC;
6779  stopInnerLoop = true; //take the next rotation crop
6780  }
6781  }
6782  }
6783  }//inner for-loop
6784 
6785  m_rotationCrops[i].crop->m_areaPercent = areaRC;
6786  //this just in an animal version, add if - checking if area has changed
6787  if(areaRC>areaBeforeRC){
6788  int index = (cfg_OptimiseBedriftsmodelCrops.value())? toc_Foobar*m_farmType + m_rotationCrops[i].crop->m_cropType : tov_Undefined*m_farmType + m_rotationCrops[i].crop->m_cropType_almass;
6789  bool fodder = m_OurManager->pm_data->Get_fodder(index);
6790  if(fodder){ //this is a fodder crop - so you need to buy less fodder - totalFUt
6791  double resp = m_rotationCrops[i].crop->m_resp;
6792  double loss = m_rotationCrops[i].crop->m_totalLoss;
6793  double FUKey = m_OurManager->pm_data->Get_FUKey(index);
6794  double FUha = resp * (1-loss/100) * FUKey; //[ha * hkg/ha * FU/hkg = FU]
6795  double changeFU = (areaRC - areaBeforeRC) * m_totalArea/100 * FUha; //positive
6796  m_totalFUt -= changeFU;
6797  m_totalFUgrown += changeFU;
6798  }
6799  }
6800  }//if rot crop<rotmax//else - take the next rot crop, i++
6801  }//outer for
6802 
6803  //now the diff can be positive in two cases:
6804 
6805  //1. wwheat area is at zero - need to increase rotation crops - if possible
6806  if(areaWWheat==areaMin && diff>0){
6807  double diff1 = diff;
6809  if(diff1==0) {decreaseCrops(m_variableCrops2, diff);} //do it only if we actually
6810  //managed to diff (=diff1) to the rotation crops,so diff1=0; if it's (0, diff)-then
6811  //we added smth, but not enough and restriction can't be fulfilled...- then...
6812  else{
6813  double toCut = diff-diff1;
6815  diff = diff1; //restriction will be broken by diff1
6816  ofstream ofile("Restrictions.txt",ios::app);
6817  ofile << m_almass_no << '\t' << "winter rotation1 restriction broken. Animal farm. WWheat area at 0. Diff is: " << diff << endl;
6818  ofile.close();
6819  }
6820  }
6821 
6822  //2. it was always more profitable to grow rotation crops, but they were not
6823  //enough (maybe at max from the beginning) - increase variable crops, cut wwheat
6824 
6825  if(diff>0 && areaWWheat-areaMin >= diff){
6826  areaWWheat -= diff;
6828  }
6829 
6830  wWheat->m_areaPercent = areaWWheat;
6831 
6832  }//if
6833 
6834 }//end of the function
6835 
6837 
6843  CropOptimised *wBarley;
6844  CropOptimised *wWheat;
6845  CropOptimised *wRye;
6846  CropOptimised *wRape;
6847  CropOptimised *wCerealSil = NULL; // Prevents warning
6848 
6850  wBarley = findCropByName("WBarley");
6851  wWheat = findCropByName("WWheat");
6852  wRye = findCropByName("WRye");
6853  wRape = findCropByName("WRape"); //should not be decreased - might cause violation of winterRotation restriction
6854  wCerealSil = findCropByName("WCerealSil");
6855  }
6856  else{
6857  wBarley = findCropByName_almass("WinterBarley");
6858  wWheat = findCropByName_almass("WinterWheat");
6859  wRye = findCropByName_almass("WinterRye");
6860  wRape = findCropByName_almass("WinterRape"); //should not be decreased - might cause violation of winterRotation restriction
6861  }
6862 
6863 
6864  double areaWBarley = wBarley->m_areaPercent;
6865  double areaWWheat = wWheat->m_areaPercent;
6866  double areaWRye = wRye->m_areaPercent;
6867  double areaWRape = wRape->m_areaPercent;
6868  double areaWCerealSil = 0;
6869 
6871  areaWCerealSil = wCerealSil->m_areaPercent; //it is used here only if it was initilized - in the bedriftsmodel crop mode
6872  }
6873 
6874  double sum = areaWBarley + areaWWheat + areaWRye + areaWRape + areaWCerealSil;
6875 
6876  int winterMax = m_OurManager->pm_data->Get_winterMax(m_farmType);
6877  if(sum > winterMax){
6878 
6879  m_variableCrops2 = m_variableCrops; //initiate the new list and remove all winter crops:
6880 
6882  for(int s=(int)m_variableCrops2.size()-1; s>=0; s--){
6883  if(m_variableCrops2[s].crop==wBarley || m_variableCrops2[s].crop==wWheat || m_variableCrops2[s].crop==wRye || m_variableCrops2[s].crop==wRape || m_variableCrops2[s].crop==wCerealSil){
6884  m_variableCrops2.erase(m_variableCrops2.begin() + s);
6885  }
6886  }
6887  }
6888  else{
6889  for(int s=(int)m_variableCrops2.size()-1; s>=0; s--){
6890  if(m_variableCrops2[s].crop==wBarley || m_variableCrops2[s].crop==wWheat || m_variableCrops2[s].crop==wRye || m_variableCrops2[s].crop==wRape){
6891  m_variableCrops2.erase(m_variableCrops2.begin() + s);
6892  }
6893  }
6894  }
6895 
6896  double diff = sum - winterMax;
6897  double diffBefore = diff;
6898 
6899  CropSort cs1 = {0., wBarley}; //an object with a key for sorting and a pointer to crop
6900  CropSort cs2 = {0., wWheat};
6901  CropSort cs3 = {0., wRye}; //CropSort cs4 = {0., wRape};
6902  m_winterCrops.clear();
6903  m_winterCrops.push_back(cs1);
6904  m_winterCrops.push_back(cs2);
6905  m_winterCrops.push_back(cs3);
6906 
6908  CropSort cs5 = {0., wCerealSil};
6909  m_winterCrops.push_back(cs5);
6910  }
6911 
6912  sortCrops(m_winterCrops, "GM");
6913 
6914  //decrease area of one or more winter crops by diff
6916 
6917  if(diff > 0){ //loop in decreaseCrops was stopped by the other condition: impossible to cut more
6918  //violation of the restriction; do not exit, print warning
6919  ofstream ofile("Restrictions.txt",ios::app);
6920  ofile << m_almass_no << '\t' << "winter crops restriction broken, non-animal farm. Diff is: " << diff << endl;
6921  ofile.close();
6922  }
6923 
6924  //assign area cut from winter crops to one or more variable crops (that haven't reached the max yet)
6925  double toIncrease = diffBefore - diff;
6926  increaseCrops(m_variableCrops2, toIncrease);
6927 
6928  }//else nothing!:) it's ok
6929 
6930 }//end of checkWinterCrops
6931 
6933 
6939  CropOptimised *wBarley;
6940  CropOptimised *wWheat;
6941  CropOptimised *wRye;
6942  CropOptimised *wRape;
6943  CropOptimised *wCerealSil = NULL; // To prevent the annoying warning
6944 
6946  wBarley = findCropByName("WBarley");
6947  wWheat = findCropByName("WWheat");
6948  wRye = findCropByName("WRye");
6949  wRape = findCropByName("WRape"); //should not be decreased - might cause violation of winterRotation restriction
6950  wCerealSil = findCropByName("WCerealSil");
6951  }
6952  else{
6953  wBarley = findCropByName_almass("WinterBarley");
6954  wWheat = findCropByName_almass("WinterWheat");
6955  wRye = findCropByName_almass("WinterRye");
6956  wRape = findCropByName_almass("WinterRape"); //should not be decreased - might cause violation of winterRotation restriction
6957  }
6958 
6959  double areaWBarley = wBarley->m_areaPercent;
6960  double areaWWheat = wWheat->m_areaPercent;
6961  double areaWRye = wRye->m_areaPercent;
6962  double areaWRape = wRape->m_areaPercent;
6963  double areaWCerealSil = 0;
6964 
6966  areaWCerealSil = wCerealSil->m_areaPercent;
6967  }
6968 
6969  double sum = areaWBarley + areaWWheat + areaWRye + areaWRape + areaWCerealSil;
6970 
6971  int winterMax = m_OurManager->pm_data->Get_winterMax(m_farmType);
6972  if(sum > winterMax){
6973  double diff = sum - winterMax;
6974  double diffBefore = diff;
6975 
6976  m_variableCrops2 = m_variableCrops; //initiate the new list and remove all winter crops:
6978  for(int s=(int)m_variableCrops2.size()-1; s>=0; s--){
6979  if(m_variableCrops2[s].crop==wBarley || m_variableCrops2[s].crop==wWheat || m_variableCrops2[s].crop==wRye || m_variableCrops2[s].crop==wRape || m_variableCrops2[s].crop==wCerealSil){
6980  m_variableCrops2.erase(m_variableCrops2.begin() + s);
6981  }
6982  }
6983  }
6984  else{
6985  for(int s=(int)m_variableCrops2.size()-1; s>=0; s--){
6986  if(m_variableCrops2[s].crop==wBarley || m_variableCrops2[s].crop==wWheat || m_variableCrops2[s].crop==wRye || m_variableCrops2[s].crop==wRape){
6987  m_variableCrops2.erase(m_variableCrops2.begin() + s);
6988  }
6989  }
6990  }
6991 
6992  //assign keys for sorting - for fodder crops these will be Savings!
6993  CropSort cs1 = {0., wBarley}; //an object with a key for sorting and a pointer to crop
6994  CropSort cs2 = {0., wWheat};
6995  CropSort cs3 = {0., wRye};//CropSort cs4 = {wRape->pullVariable<double>("GM"), wRape};
6996 
6997  m_winterCrops.clear();
6998  m_winterCrops.push_back(cs1);
6999  m_winterCrops.push_back(cs2);
7000  m_winterCrops.push_back(cs3);
7001 
7003  CropSort cs5 = {0., wCerealSil};
7004  m_winterCrops.push_back(cs5);
7005  }
7006 
7007  sortCrops(m_winterCrops, "GM_Savings");
7008 
7009  //decrease area of one or more winter crops by diff
7011 
7012  if(diff>0){ //loop stopped by the other condition: impossible to cut more
7013  //violation of the restriction; do not exit, just print a warning
7014  ofstream ofile("Restrictions.txt",ios::app);
7015  ofile << m_almass_no << '\t' << "winter crops restriction broken, Animal farm. Diff is: " << diff << endl;
7016  ofile.close();
7017  }
7018 
7019  //assign the area cut from winter crops to one or more variable crops (that haven't reached the max yet)
7020  double toIncrease = diffBefore - diff;
7021  increaseCrops(m_variableCrops2, toIncrease);
7022 
7023  }//else nothing!:) it's ok
7024 
7025 }//end of checkWinterCropsAnimal
7026 
7030  for(int i=0; i<(int)m_cattleCrops.size(); i++){ //just go through all 2 of them:)
7031  double area = m_cattleCrops[i].crop->m_areaPercent;
7032  double areaBefore = area;
7033  double rotationMin = m_cattleCrops[i].crop->m_rotationMin;
7034  area = rotationMin; //set all at min
7035  m_cattleCrops[i].crop->m_areaPercent = area;
7036 
7037  if(areaBefore > area){
7038  int index = (cfg_OptimiseBedriftsmodelCrops.value())? toc_Foobar*m_farmType + m_cattleCrops[i].crop->m_cropType : tov_Undefined*m_farmType + m_cattleCrops[i].crop->m_cropType_almass;
7039  bool fodder = m_OurManager->pm_data->Get_fodder(index);
7040  if(fodder){
7041  double resp = m_cattleCrops[i].crop->m_resp;
7042  double loss = m_cattleCrops[i].crop->m_totalLoss;
7043  double FUKey = m_OurManager->pm_data->Get_FUKey(index);
7044  double FUha = resp * (1-loss/100) * FUKey; //[ha * hkg/ha * FU/hkg = FU]
7045  double changeFU = (areaBefore - area) * m_totalArea/100 * FUha; //positive number
7046  m_totalFUt += changeFU; //so you buy more
7047  m_totalFUgrown -= changeFU; //and grow less:)
7048  }
7049  }
7050  }
7051 }
7052 
7061 //This function can be called only after fodder crops were assigned areas because two of them are fodder crops! So before assiging the fodder crops, their areas will be zero!
7062 
7063 
7064  CropOptimised *sBarley = findCropByName("SBarley"); //fodder
7065  CropOptimised *gClover = findCropByName("GrassClover"); //fodder
7066  CropOptimised *gSeed = findCropByName("GrassSeed");
7067 
7068  CropOptimised *wWheat = findCropByName("WWheat");
7069 
7070  double areaSBarley = sBarley->m_areaPercent;
7071  double areaGClover = gClover->m_areaPercent;
7072  double areaGSeed = gSeed->m_areaPercent;
7073 
7074  double diff = areaGClover + areaGSeed - areaSBarley;
7075 
7076  if(diff > 0){ //restriction is not fulfilled
7077 
7078  //1. Make a vector of (two) cattle crops and sort them from highest to lowest GM/Savings
7079  CropSort cs1 = {0., gClover}; //an object with a key for sorting and a pointer to crop
7080  CropSort cs2 = {0., gSeed};
7081  m_cattleCrops.push_back(cs1);
7082  m_cattleCrops.push_back(cs2);
7083 
7084  sortCrops(m_cattleCrops, "GM_Savings"); //sorting the two crops
7085 
7086  //2. Make a new list of variable crops - excluding all crops forming the condition
7087  m_variableCrops2 = m_variableCrops; //initiate the new list and remove all three crops:
7088  for(int s=(int)m_variableCrops2.size()-1; s>=0; s--){
7089  if(m_variableCrops2[s].crop==sBarley || m_variableCrops2[s].crop==gClover || m_variableCrops2[s].crop==gSeed || m_variableCrops2[s].crop==wWheat){ //14.02 - added winter wheat - do not increase it!maybe i should even add here all winter crops...
7090  m_variableCrops2.erase(m_variableCrops2.begin() + s);
7091  }
7092  }
7093 
7094  //3. check if it pays off to substitute one of the two cattle crops with variable crops other than SBarley; if so - change the areas
7095  for(int i=(int)m_cattleCrops.size()-1; i>=0 && diff>0; i--){ //start with the worse one
7096  double areaCC = m_cattleCrops[i].crop->m_areaPercent; //don't know which of the two it is, so have to get the values this way
7097  double areaMinCC = m_cattleCrops[i].crop->m_rotationMin;
7098  double areaCCBefore = areaCC;
7099  if(areaCC > areaMinCC){
7100  bool cCropAtMin = false;
7101  for(int j=0; j<(int)m_variableCrops2.size() && cCropAtMin==false; j++){ //start with the best variable crop
7102  double GM_SBarley = sBarley->m_GM_Savings;
7103  double GM_CC = m_cattleCrops[i].crop->m_GM_Savings; //in case it is a fodder crop - then it takes savings, as now, after findFodderCropSavings() - savings are saved under GM_Savings for fodder crops
7104  double GM_var = m_variableCrops2[j].crop->m_GM_Savings;
7105  if(GM_SBarley + GM_CC > 2*GM_var){
7106  //yes: it doesn't pay off to remove this cattle crop; go to the next part of the cattle rot. function: increase SBarley, cut one of the cattle crops
7107  }
7108  else{
7109  double areaVar = m_variableCrops2[j].crop->m_areaPercent;
7110  double areaMaxVar = m_variableCrops2[j].crop->m_rotationMax;
7111  double areaVarBefore = areaVar;
7112 
7113  if(areaCC - areaMinCC >= diff){
7114  if(areaMaxVar - areaVar >= diff){
7115  areaCC -= diff;
7116  areaVar += diff;
7117  diff = 0; //finished -> cattle rotation fulfilled
7118  cCropAtMin = true; //stop the inner loop!!!
7119  }
7120  else{
7121  diff -= (areaMaxVar - areaVar);
7122  areaCC -= (areaMaxVar - areaVar);
7123  areaVar = areaMaxVar; //go to the next var. crop (j++)
7124  }
7125  }
7126  else{
7127  if(areaMaxVar - areaVar >= areaCC - areaMinCC){
7128  diff -= areaCC - areaMinCC;
7129  areaVar += areaCC - areaMinCC;
7130  areaCC = areaMinCC;
7131  cCropAtMin = true; //stop the inner loop - take the next cattle crop(i--)
7132  }
7133  else{
7134  diff -= areaMaxVar - areaVar;
7135  areaCC -= areaMaxVar - areaVar;
7136  areaVar = areaMaxVar; //go to the next var crop (j++)
7137  }
7138  }
7139 
7140  //save the areas
7141  m_variableCrops2[j].crop->m_areaPercent = areaVar;
7142  m_cattleCrops[i].crop->m_areaPercent = areaCC;
7143 
7144  //correct fodder variables for the changes - both for cattle and var crop
7145 
7146  if(areaVar > areaVarBefore){
7147  int index = toc_Foobar*m_farmType + m_variableCrops[j].crop->m_cropType;
7148  bool fodder = m_OurManager->pm_data->Get_fodder(index);
7149  if(fodder){ //this is a fodder crop - so you need to buy less fodder - totalFUt
7150  double resp = m_variableCrops[j].crop->m_resp;
7151  double loss = m_variableCrops[j].crop->m_totalLoss;
7152  double FUKey = m_OurManager->pm_data->Get_FUKey(index);
7153  double FUha = resp * (1-loss/100) * FUKey; //[ha * hkg/ha * FU/hkg = FU]
7154  double changeFU = (areaVar - areaVarBefore) * m_totalArea/100 * FUha; //positive
7155  m_totalFUt -= changeFU;
7156  m_totalFUgrown += changeFU;
7157  }
7158  }
7159 
7160  if(areaCC < areaCCBefore){
7161  int index = toc_Foobar*m_farmType + m_cattleCrops[i].crop->m_cropType;
7162  bool fodder = m_OurManager->pm_data->Get_fodder(index);
7163  if(fodder){ //this is a fodder crop - so you need to buy less fodder - totalFUt
7164  double resp = m_cattleCrops[i].crop->m_resp;
7165  double loss = m_cattleCrops[i].crop->m_totalLoss;
7166  double FUKey = m_OurManager->pm_data->Get_FUKey(index);
7167  double FUha = resp * (1-loss/100) * FUKey; //[ha * hkg/ha * FU/hkg = FU]
7168  double changeFU = (areaCCBefore - areaCC) * m_totalArea/100 * FUha; //positive
7169  m_totalFUt += changeFU;
7170  m_totalFUgrown -= changeFU;
7171  }
7172  }
7173  }
7174 
7175  }//inner for
7176  }
7177  else{
7178  //nothing - go to the next cattle crop; if there's no more - then the diff must be zero - so the loop will stop
7179  }
7180 
7181  }//outer for
7182 
7183  //4. Check if diff is still > 0 (after point 3.), if so - substitute some area of one of the cattle crops with SBarley
7184 
7185  if(diff>0){
7186 
7187  double areaSBarleyMax = sBarley->m_rotationMax;
7188  double SBarleyAvailableArea = areaSBarleyMax-areaSBarley;
7189  double areaSBarleyBefore = areaSBarley;
7190 
7191  double available = 0; //available to cut from GClover and GSeed
7192  for(int i=0; i<(int)m_cattleCrops.size(); i++){ //or simply: i<2
7193  double areaMin = m_cattleCrops[i].crop->m_rotationMin;
7194  double area = m_cattleCrops[i].crop->m_areaPercent;
7195  available += (area - areaMin);
7196  }
7197 
7198  if(areaSBarley < areaSBarleyMax){ //Y1
7199  if(SBarleyAvailableArea >= diff/2){ //Y2
7200  if(available >= diff/2){ //Y 3.2
7201  areaSBarley += diff/2; //increase Sbarley by diff/2
7202  diff /= 2; //updating diff
7203  decreaseCrops(m_cattleCrops, diff);//decrease the two crops by diff/2 (now=to diff)
7204  }
7205 
7206  else{ //N 3.2
7207  areaSBarley += available;
7208  diff -= 2 * available;//update diff
7209  setCattleCropsAtMin(); //decrease the two crops to min each (by available<diff/2),
7210 
7211  if(SBarleyAvailableArea >= diff){//if possible:
7212  areaSBarley += diff;//increase Sbarley by diff
7213  decreaseCrops(m_variableCrops2, diff);//& decrease the worst (available) normal crop by diff
7214  }
7215  else{
7216  //do as much as possible
7217  double toDecrease = areaSBarleyMax - areaSBarley; //neccesary -area has changed
7218  areaSBarley = areaSBarleyMax; //increase Sbarley to max
7219  diff-=toDecrease; //update diff
7220  decreaseCrops(m_variableCrops2, toDecrease);//decrease normal crops
7221  //and throw an exception! restriction must be violated
7222  ofstream ofile("Restrictions.txt",ios::app); //changed 06.06 out to app
7223  ofile << m_almass_no << '\t' << "cattle restriction: broken after N 3.2" << endl;
7224  ofile.close();
7225  }
7226  }
7227  }
7228  else{ //N2
7229  //increase SBarley to max in both cases
7230  if(available >= SBarleyAvailableArea){ //Y 3.1
7231  areaSBarley = areaSBarleyMax; //increase Sbarley to max
7232  diff -= 2 * SBarleyAvailableArea; //update diff
7233  available -= SBarleyAvailableArea; //decrease by what you add in the next line
7234  decreaseCrops(m_cattleCrops, SBarleyAvailableArea);//increase needed by
7235 
7236  double diffBefore = diff;
7237  if(available >= diff){
7238  decreaseCrops(m_cattleCrops, diff);//decrease the two crops by diff
7239  increaseCrops(m_variableCrops2, diffBefore);//increase normal crops by diff
7240  }
7241  else{
7242  //do as much as possible
7244  diff -= available; //update diff
7245  double toDecrease = available;
7246  increaseCrops(m_variableCrops2, toDecrease); //add some normal crops!
7247  //and throw exception - restriction must be violated!
7248  ofstream ofile("Restrictions.txt",ios::out);
7249  ofile << m_almass_no << '\t' << "cattle restriction: broken after Y 3.1" << endl;
7250  ofile.close();
7251  }
7252  }
7253  else{ //N 3.1 - restriction violated, but try to do as much as possible
7254  areaSBarley += available;
7256  diff -= 2 * available; //update diff
7257  double toDecrease = areaSBarleyMax - areaSBarley; //here it is necessary! because the area has changed
7258  areaSBarley = areaSBarleyMax;//
7259  diff -= toDecrease; //update diff
7260  decreaseCrops(m_variableCrops2, toDecrease);//add normal crops-but still-violation!
7261  //AND !!! throw an exception - violation
7262  ofstream ofile("Restrictions.txt",ios::out);
7263  ofile << m_almass_no << '\t' << "cattle restriction: broken after N 3.1" << endl;
7264  ofile.close();
7265  }
7266  }
7267 
7268  sBarley->m_areaPercent = areaSBarley;
7269 
7270  //this is a fodder crop - so you need to buy less fodder - totalFUt
7271  double resp = sBarley->m_resp;
7272  double loss = sBarley->m_totalLoss;
7273  double FUKey = m_OurManager->pm_data->Get_FUKey (toc_SBarley);
7274  double FUha = resp * (1-loss/100) * FUKey; //[ha * hkg/ha * FU/hkg = FU]
7275  double changeFU = (areaSBarley - areaSBarleyBefore) * m_totalArea/100 * FUha; //positive
7276  m_totalFUt -= changeFU;
7277  m_totalFUgrown += changeFU;
7278  }
7279 
7280  else{ // N 1
7281  if(available >= diff){
7282  double diffBefore = diff;
7283  decreaseCrops(m_cattleCrops, diff); //cover the diff
7284  increaseCrops(m_variableCrops2, diffBefore); //increase some normal crops
7285  }
7286  else{//restr must be violated
7287  setCattleCropsAtMin(); //set the two crops at min
7288  diff -= available;
7289  double toIncrease = available;
7290  increaseCrops(m_variableCrops2, toIncrease);
7291  //throw an exception - restriction must be violated!
7292  ofstream ofile("Restrictions.txt",ios::out);
7293  ofile << m_almass_no << '\t' << "cattle restriction: broken after N 1" << endl;
7294  ofile.close();
7295  }
7296  }
7297 
7298  }//end of the second if(diff>0)
7299 
7300  }//end of the if(diff>0)?
7301 
7302 }//end of check CattleRotation
7303 
7308  CropOptimised *sBarley = findCropByName_almass("SpringBarley"); //fodder
7309  CropOptimised *CGG1 = findCropByName_almass("CloverGrassGrazed1"); //fodder
7310  CropOptimised *CGG2 = findCropByName_almass("CloverGrassGrazed2"); //fodder
7311 
7312  double areaSBarley = sBarley->m_areaPercent;
7313  double areaCGG = 2*(CGG1->m_areaPercent); //cgg1 and 2 have equal areas - it waa checked in Check_sg_and_cgg (called in check restrictions)
7314 
7315  double diff = areaCGG/2 - areaSBarley; //SpringBarley has to have an area at least as big as CGG1 = CGG2 = areaCGG/2.
7316 
7317  if(diff > 0){ //restriction is not fulfilled
7318 
7319  //need to make new variableCrops2 - without the grasses and sbarley!
7320  m_variableCrops2 = m_variableCrops; //initiate the new list and remove crops:
7321  for(int s=(int)m_variableCrops2.size()-1; s>=0; s--){
7322  if(m_variableCrops2[s].crop==sBarley || m_variableCrops2[s].crop==CGG1 || m_variableCrops2[s].crop==CGG2){
7323  m_variableCrops2.erase(m_variableCrops2.begin() + s);
7324  }
7325  }
7326 
7327  double new_area_sbarley = areaSBarley;
7328  double new_area_cgg = areaCGG;
7329 
7330  double available=0; //all area except for fixed crops and min. areas of variable crops
7331  for(int i=0; i<(int)m_variableCrops.size(); i++){ //can't use m_grownVariableCrops - it doesn't include fodder crops!
7332  double areaVariableCrop = m_variableCrops[i].crop->m_areaPercent - m_variableCrops[i].crop->m_rotationMin;
7333  available += areaVariableCrop;
7334  }
7335 
7336  if(areaCGG/2 *3 <= available){ //then Sbarley can get as much as each CGG1; cgg area doesn't change
7337  new_area_sbarley = areaCGG/2;
7338  double area_to_decrease = new_area_sbarley - areaSBarley; // must be > 0 if this code is executed
7339  decreaseCrops(m_variableCrops2, area_to_decrease);
7340  }
7341  else{ //need to also cut grass, not just increase sbarley
7342  new_area_cgg = available/3 * 2; // = new area for sbarley = cgg1 = cgg2 (these 3 crops take all available area)
7343  new_area_sbarley = available/3;
7344  double current_sbarley_and_grasses = areaSBarley + areaCGG; // so other crops area (variable area) = 100 - current_sbarley_and_grasses
7345  double other_crops_area = available - current_sbarley_and_grasses;
7346  if(current_sbarley_and_grasses < available){ //there are other crops - and we're now substituting them with sbarley
7347  decreaseCrops(m_variableCrops2, other_crops_area);
7348  }
7349  //else - just these 3 crops - do nothing - grass is already cut :), sbarley area is increased
7350  }
7351 
7352  //correct fodder....
7353  double resp = sBarley->m_resp;
7354  double loss = sBarley->m_totalLoss;
7356  double FUKey = m_OurManager->pm_data->Get_FUKey(index);
7357  double FUha = resp * (1-loss/100) * FUKey; //[ha * hkg/ha * FU/hkg = FU]
7358  double changeFU = (new_area_sbarley - areaSBarley) * m_totalArea/100 * FUha; //positive
7359  m_totalFUt -= changeFU;
7360  m_totalFUgrown += changeFU;
7361 
7362  resp = CGG1->m_resp;
7363  loss = CGG1->m_totalLoss;
7365  FUKey = m_OurManager->pm_data->Get_FUKey(index);
7366  FUha = resp * (1-loss/100) * FUKey; //[ha * hkg/ha * FU/hkg = FU]
7367  changeFU = (areaCGG - new_area_cgg) * m_totalArea/100 * FUha; //positive
7368  m_totalFUt += changeFU;
7369  m_totalFUgrown -= changeFU;
7370 
7371  //and change the areas
7372  CGG1->m_areaPercent = new_area_cgg/2; //areaCGG is a summary area for both CGG
7373  CGG2->m_areaPercent = new_area_cgg/2;
7374  sBarley->m_areaPercent = new_area_sbarley;
7375 
7376  }
7377 
7378 }//end of check CattleRotation for almass crops
7379 
7387  CropOptimised *wBarley;
7388  CropOptimised *wRape;
7389  wBarley = findCropByName_almass("WinterBarley");
7390  wRape = findCropByName_almass("WinterRape");
7391  double area_WB = wBarley->m_areaPercent;
7392  double area_WR = wRape->m_areaPercent;
7393 
7394  if(area_WB < area_WR){ //then need to make changes!
7395 
7396  //1. need to make new variableCrops2 - without wrape and wbarley
7397  m_variableCrops2 = m_variableCrops; //initiate the new list and remove crops:
7398  for(int s=(int)m_variableCrops2.size()-1; s>=0; s--){
7399  if(m_variableCrops2[s].crop==wBarley || m_variableCrops2[s].crop==wRape){
7400  m_variableCrops2.erase(m_variableCrops2.begin() + s);
7401  }
7402  }
7403 
7404  //check how much area available is there:
7405  double available=0;
7406  for(int i=0; i<(int)m_variableCrops2.size(); i++){ //can't use m_grownVariableCrops - it doesn't include fodder crops!
7407  double areaVariableCrop = m_variableCrops2[i].crop->m_areaPercent - m_variableCrops2[i].crop->m_rotationMin;
7408  available += areaVariableCrop;
7409  }
7410 
7411  double new_area_wbarley = area_WB;
7412  double new_area_wrape = area_WR;
7413 
7414  if(2 * area_WR <= available){ //then WBarley can get area equal to the current WRape's area; WRape's area doesn't change
7415  new_area_wbarley = area_WR;
7416  double area_to_decrease = new_area_wbarley - area_WB; // must be > 0 if this code is executed
7417  decreaseCrops(m_variableCrops2, area_to_decrease); //increased the WBarley's area, so need to cut the same amount in other crops
7418  }
7419  else{ //need to cut wrape, not just increase wbarley
7420  new_area_wrape = available/2; // these 2 crops take the whole available area
7421  new_area_wbarley = available/2;
7422  double current_wbarley_and_wrape = area_WB + area_WR; // so other crops area (variable area) = 100 - current_wbarley_and_wrape
7423  double other_crops_area = available - current_wbarley_and_wrape;
7424  if(current_wbarley_and_wrape < available){ //there are other crops - and we're now substituting them with wbarley
7425  decreaseCrops(m_variableCrops2, other_crops_area);
7426  }
7427  //else nothing
7428  }
7429 
7430  //check how much winter crops is there now - before changes:
7431  double winter_crops=0;
7432  for(unsigned j=0; j<m_crops.size(); j++){
7433  if(m_crops[j]->m_cropType_almass == tov_WinterRape || m_crops[j]->m_cropType_almass == tov_WinterBarley ||
7434  m_crops[j]->m_cropType_almass == tov_WinterWheat || m_crops[j]->m_cropType_almass == tov_WinterRye){
7435  winter_crops += m_crops[j]->m_areaPercent;
7436  }
7437  }
7438  int winterMax = m_OurManager->pm_data->Get_winterMax(m_farmType);
7439 
7440  //now save the changes in the areas
7441  wRape->m_areaPercent = new_area_wrape;
7442  wBarley->m_areaPercent = new_area_wbarley;
7443 
7444  //check how much winter crops there is now:
7445  winter_crops=0;
7446  for(unsigned j=0; j<m_crops.size(); j++){
7447  if(m_crops[j]->m_cropType_almass == tov_WinterRape || m_crops[j]->m_cropType_almass == tov_WinterBarley ||
7448  m_crops[j]->m_cropType_almass == tov_WinterWheat || m_crops[j]->m_cropType_almass == tov_WinterRye){
7449  winter_crops += m_crops[j]->m_areaPercent;
7450  }
7451  }
7452 
7453  //need to check if the winter crops restriction is still fine:
7454  if(winter_crops > winterMax){ //problem
7455  double diff = winter_crops - winterMax;
7456  //need to make new variableCrops2 - without all winter crops!
7457  m_variableCrops2 = m_variableCrops; //initiate the new list and remove crops:
7458  for(int s=(int)m_variableCrops2.size()-1; s>=0; s--){
7459  if(m_variableCrops2[s].crop==wBarley || m_variableCrops2[s].crop==wRape || m_variableCrops2[s].crop->m_cropType_almass==tov_WinterWheat || m_variableCrops2[s].crop->m_cropType_almass == tov_WinterRye){
7460  m_variableCrops2.erase(m_variableCrops2.begin() + s);
7461  }
7462  }
7463  new_area_wrape -= diff/2;
7464  new_area_wbarley -= diff/2;
7466 
7467  //and change the areas again
7468  wRape->m_areaPercent = new_area_wrape;
7469  wBarley->m_areaPercent = new_area_wbarley;
7470  }
7471 
7472  //correct fodder. only winter barley is a fodder crop for pig farms
7473  double resp = wBarley->m_resp;
7474  double loss = wBarley->m_totalLoss;
7476  double FUKey = m_OurManager->pm_data->Get_FUKey(index);
7477  double FUha = resp * (1-loss/100) * FUKey; //[ha * hkg/ha * FU/hkg = FU]
7478  double changeFU = (new_area_wbarley - area_WB) * m_totalArea/100 * FUha; //positive
7479  m_totalFUt -= changeFU;
7480  m_totalFUgrown += changeFU;
7481  }
7482 }
7483 
7484 //------------------------------------------------------------------------------//
7485 //------------------------FUNCTIONS RELATED TO FODDER---------------------------//
7486 //------------------------------------------------------------------------------//
7487 
7493  m_totalFUgrown=0; //initialize
7494 
7495  double min_fodder = (m_farmType == toof_Pig) ? cfg_Min_fodder_prod_pig.value() : cfg_Min_fodder_prod_cattle.value(); //there are only two types of animal farms
7496  m_totalFodderToProduce = (min_fodder/100)*m_totalFUdemand; //[FU]
7497 
7498  double fodderFromFixed=0;
7499  for (int i=0; i<(int)m_fixedCrops.size(); i++){
7500  double area_percent = m_fixedCrops[i]->m_areaPercent;
7501  if(area_percent!=0){
7502  double area = area_percent/100* m_totalArea;
7503  double resp = m_fixedCrops[i]->m_resp;
7504  double loss = m_fixedCrops[i]->m_totalLoss;
7505 
7506  int index = (cfg_OptimiseBedriftsmodelCrops.value())? a_foobar*m_farmType + m_fixedCrops[i]->m_cropType : a_foobar*m_farmType + m_fixedCrops[i]->m_cropType_almass;
7507  double FUKey = m_OurManager->pm_data->Get_FUKey(index);//if it is not a fodder crop, key=0
7508  double FU = area*resp*(1-loss/100)*FUKey; //[ha * hkg/ha * FU/hkg = FU]
7509  fodderFromFixed += FU;//0 will be added in case of non-fodder crops
7510  m_totalFUgrown += FU;
7511  }
7512  }
7513  double fodderFromMinAreas=0;
7514  for (int i=0; i<(int)m_variableCrops.size(); i++){
7515  double areaMinPercent = m_variableCrops[i].crop->m_rotationMin;
7516  if(areaMinPercent!=0){ //150713
7517  double area = areaMinPercent/100*m_totalArea; //min area in ha
7518  double resp = m_variableCrops[i].crop->m_resp;
7519  double loss = m_variableCrops[i].crop->m_totalLoss;
7520 
7521  int index = (cfg_OptimiseBedriftsmodelCrops.value())? a_foobar*m_farmType + m_variableCrops[i].crop->m_cropType : a_foobar*m_farmType + m_variableCrops[i].crop->m_cropType_almass;
7522  double FUKey = m_OurManager->pm_data->Get_FUKey(index);//if it is not a fodder crop, key=0
7523  double FU = area*resp*(1-loss/100)*FUKey; //[ha * hkg/ha * FU/hkg = FU]
7524  fodderFromMinAreas += FU;
7525  m_totalFUgrown += FU;
7526  }
7527  }
7528  //this much fodder HAS to be obtained from self-production IF the requirment
7529  //on min fodder production holds; might be negative!
7530 
7531  m_fodderToProduce = m_totalFodderToProduce - (fodderFromFixed + fodderFromMinAreas);
7533 
7534  //decrease the fodder demand by the amount obtained from growing fixed crops and from
7535  //min areas of variable crops; could be also negative now;
7536  m_totalFUdemand -= (fodderFromFixed + fodderFromMinAreas);
7537 
7538 }
7539 
7540 
7544  double areaAssignedToFodder=0; //holds the value of area that has to be grown to cover the min fodder production requirement
7545  if(m_fodderToProduce > 0){
7546  double available=0; //area of normal (non-fodder) crops available to substitute with fodder crops
7547  for(int i=0; i<(int)m_grownVariableCrops.size(); i++){
7548  double areaVariableCrop = m_grownVariableCrops[i]->m_areaVariable;
7549  available += areaVariableCrop;
7550  }
7551 
7552  for(int i=0; available>0 && i<(int)m_fodderCrops.size() && m_fodderToProduce > 0 ; i++){// if so, more has to be produced (than it is already-from min areas and fixed crops)
7553  int index = (cfg_OptimiseBedriftsmodelCrops.value())? a_foobar*m_farmType + + m_fodderCrops[i].crop->m_cropType : a_foobar*m_farmType + + m_fodderCrops[i].crop->m_cropType_almass;
7554  double rotationMax = m_fodderCrops[i].crop->m_rotationMax;
7555  double area = m_fodderCrops[i].crop->m_areaPercent; //fodder crop's area
7556  double areaBefore = area; //this is positive if areaMin>0, so save it
7557  double FUKey = m_OurManager->pm_data->Get_FUKey(index); //if it is not a fodder crop, key=0; number of FU per hkg of a crop
7558  double resp = m_fodderCrops[i].crop->m_resp;
7559  double loss = m_fodderCrops[i].crop->m_totalLoss;
7560  double FUha = resp * (1-loss/100) * FUKey;
7561  double haNeeded = m_fodderToProduce/FUha;
7562  double percNeeded = haNeeded*100/m_totalArea;
7563  if(percNeeded <= rotationMax - area){ //area might be positive! (min area)
7564  if(percNeeded <= available){
7565  area += percNeeded; //the end, fodderToProduce will be 0.
7566  available -= percNeeded;
7567  }
7568  else{
7569  area+=available; //so we can't grow any more fodder - no space left!
7570  available=0;
7571  }
7572  }
7573  else{
7574  if(rotationMax-area >= available){
7575  area += available;
7576  available=0; //no space left
7577  }
7578  else{
7579  available -= rotationMax-area;
7580  area = rotationMax;
7581  }
7582  }
7583  m_fodderCrops[i].crop->m_areaPercent = area;
7584  double Funits = FUha * (area-areaBefore) * m_totalArea/100;
7585  m_fodderToProduce -= Funits; //update fodderToProduce; in 1st case - it's now = 0.
7586  m_totalFUdemand -= Funits; //update the total demand as well!
7587  m_totalFUgrown += Funits; //update the amount of grown fodder units
7588  areaAssignedToFodder += (area-areaBefore);
7589 
7590  }
7591  if(m_fodderToProduce>0.1){
7592  //restriction broken! impossible to produce the min amount of fodder - send a message, but don't stop.
7593  char index[ 20 ];
7594  sprintf( index, "%d", m_almass_no);
7595  g_msg->Warn( WARN_BUG, "AnimalFarm::determineMinFodder(): impossible to cover the min. fodder prod., farm no: ", index );
7596  //exit( 1 );
7597  }
7598  //decreasing area of variable crops that has just been assigned to fodder crops
7599  //need to create a vector of type CropSort
7600  vector<CropSort>grownVarCrops_key;
7601  for(int g=0; g < (int)m_grownVariableCrops.size(); g++){
7602  CropSort gc = {0., m_grownVariableCrops[g]};
7603  grownVarCrops_key.push_back(gc);
7604  }
7605 
7606  OptimisingFarm::decreaseCrops(grownVarCrops_key, areaAssignedToFodder); //m_grownVariableCrops does not contain fodder crops-call optimising farms version. there might be here a fake crop; here use grownVarCrops_key - need CropSort type vector to use decreaseCrops;
7607  if(areaAssignedToFodder>0){
7608  //there is not enough space to grow fodder to cover the min required.
7609  char index[ 20 ];
7610  sprintf( index, "%d", m_almass_no);
7611  g_msg->Warn( WARN_BUG, "AnimalFarm::determineMinFodder(): not enough space to grow the min. fodder, farm no.: ", index );
7612  //exit( 1 );
7613 
7614  }
7615  }
7616 } //determineMinFodder
7617 
7618 
7620 
7642 //1. assigning area to fodder crops in order to cover the min fodder production
7643  if(!cash_crops_allowed) determineMinFodder(a_foobar);
7644 
7645 //2. now the choice - produce or purchase fodder
7646 
7647  m_totalFUt=0;
7648 
7649 
7650  //go through fodder crops - start with the one with max savings. Check if it reached its max area (could have happened in the previous step)
7651 
7652 for(int p=0; m_totalFUdemand>0 && p<(int)m_fodderCrops.size(); p++){ //outer for loop - fodder crops;
7653 
7654  double rotationMax = m_fodderCrops[p].crop->m_rotationMax;
7655  double areaFodder = m_fodderCrops[p].crop->m_areaPercent;
7656  if(areaFodder < rotationMax){ //if not -> go to the next fodder crop
7657  double savings = m_fodderCrops[p].crop->m_savings;
7658  bool assigningFinished = false; //changed to true when a fodder crop reaches rotationMax
7659 
7660  int v = (int)m_grownVariableCrops.size()-1;
7661  double minGM = 1000000; //set it high so that if there are no grown var crops - we go directly to the fodder trade code (as savings are not > minGM)
7662  do{ //inner loop; normal crops; starts with the crop with the lowest GM;
7663  if(v>=0){
7664  minGM = m_grownVariableCrops[v]->m_GM;
7665  }
7666  if(savings > minGM){ //compare savings to GM of the worst 'available' normal crop - which is currently planted and have areaVariable>0
7667  double areaVariable = m_grownVariableCrops[v]->m_areaVariable;
7668  int index = (cfg_OptimiseBedriftsmodelCrops.value())? a_foobar*m_farmType + m_fodderCrops[p].crop->m_cropType : a_foobar*m_farmType + m_fodderCrops[p].crop->m_cropType_almass;
7669  double FUKey = m_OurManager->pm_data->Get_FUKey(index);//if it is not a fodder crop, key=0
7670  double resp = m_fodderCrops[p].crop->m_resp;
7671  double loss = m_fodderCrops[p].crop->m_totalLoss;
7672  double FUha = resp*(1-loss/100)*FUKey;
7673  double haNeeded = m_totalFUdemand/FUha;
7674  double percNeeded = haNeeded*100/m_totalArea;
7675 
7676  if(percNeeded <= rotationMax - areaFodder){//you can plant as much as need of fodder crop, but check if there is enough space in the normal crop
7677  if(percNeeded <= areaVariable){//if so, just plant as much as you need of this one fodder crop and cut the normal crop by percNeeded
7678  areaFodder += percNeeded; //increase the area (not just assign!)
7679  m_totalFUdemand = 0; //finish outer loop
7680  m_totalFUgrown += percNeeded*FUha*m_totalArea/100;
7681  areaVariable -= percNeeded;
7682  assigningFinished = true; //finish inner loop
7683  }
7684  else{//you can plant fodder crop on an area of a normal crop and then check with the next normal crop
7685  areaFodder += areaVariable; //increase by the whole 'available' area of a normal crop
7686  m_totalFUdemand -= FUha*areaVariable*m_totalArea/100; //update fodder demand
7687  m_totalFUgrown += areaVariable*FUha*m_totalArea/100;
7688  areaVariable = 0;
7689  }
7690  }
7691  else{//this fodder crop will not cover all the needs; will have to check the next one
7692  if(rotationMax - areaFodder <= areaVariable){//if so, just plant as much as you need of this one fodder crop and cut the normal crop by...
7693  areaVariable -= rotationMax-areaFodder;
7694  m_totalFUgrown += (rotationMax-areaFodder)*FUha*m_totalArea/100;
7695  m_totalFUdemand -= FUha*(rotationMax-areaFodder)*m_totalArea/100;
7696  areaFodder = rotationMax; //max
7697  assigningFinished = true;
7698  //finish inner loop-you have to take the next fodder crop
7699  }
7700  else{//you can plant fodder crop on an area of a normal crop and then check with the next normal crop
7701  areaFodder += areaVariable; //increase by the whole 'available' area of a normal crop
7702  m_totalFUdemand -= FUha*areaVariable*m_totalArea/100;
7703  m_totalFUgrown += areaVariable*FUha*m_totalArea/100;
7704  areaVariable = 0;
7705  //whole replaced by a fodder crop
7706  }
7707  }
7708  double areaMin = m_grownVariableCrops[v]->m_rotationMin;
7709  double areaPer = areaMin + areaVariable;
7710  m_grownVariableCrops[v]->m_areaPercent = areaPer;
7711  m_grownVariableCrops[v]->m_areaVariable = areaVariable;
7712 
7713  }
7714  else{//buy all the remaining fodder demand
7715  m_totalFUt = m_totalFUdemand; //demand is already updated for fodder from fixed crops and min areas
7716  m_totalFUdemand = 0; //finish outer loop
7717  assigningFinished = true; //finish inner loop
7718  }
7719  v--;
7720  }while (assigningFinished==false && v>=0);//inner loop (normal crops)
7721 
7722  m_fodderCrops[p].crop->m_areaPercent = areaFodder;//update fodder crop - after the inner loop
7723 
7724  if(assigningFinished==false){ //loop was stopped by the condition->no more space on normal crops available
7725  //there's no more space on normal crops-have to buy the remaining totalFUdemand
7727  }
7728  }
7729 }//outer for-loop (fodder crops)
7730 
7731 
7732 if(m_totalFUdemand > 0){ //added 30.01 - for some farms the condition 'if(areaFodder<rotationMax)' is never fulfilled, so the inner loop will never run
7734  m_totalFUdemand = 0;
7735 }
7736 
7737 if(m_fakeCropTest==true){ //only if it was used in determineAreas - check if it is >0
7738  //check if the fake crop is still there - if so, substitute it with fodder crops
7739  int s = (int)m_grownVariableCrops.size()-1;
7740  double areaFakeCrop = m_grownVariableCrops[s]->m_areaPercent;
7741  if(areaFakeCrop > 0){
7742  increaseCrops(m_fodderCrops, areaFakeCrop);
7743  m_grownVariableCrops[s]->m_areaPercent = areaFakeCrop; //sets fake crop's area at 0.
7744  }
7745  //remove the fake crop from the grownVariable crops vector
7746  m_grownVariableCrops.erase(m_grownVariableCrops.begin() + s);
7747 }
7748 
7749 }// end of determineFodderAreas
7750 
7751 
7752 //------------------------------------------------------------------------------//
7753 //-----------------------OTHER FUNCTIONS----------------------------------------//
7754 //------------------------------------------------------------------------------//
7755 
7756 double OptimisingFarm::crop_parameter(int index, string par_name){
7757  double par_value;
7759  return par_value;
7760 }
7761 
7763  for(int c=0; c< (int)m_crops.size(); c++){
7764  if(m_crops[c]->m_cropType==m_OurManager->TranslateCropsCodes(crop_name)) return m_crops[c];
7765  }
7766  g_msg->Warn( WARN_FILE, "OptimisingFarm::findCropByName():" "Unknown Code Identificator", crop_name.c_str() );
7767  exit(0);
7768 }
7769 
7771  for(int c=0; c< (int)m_crops.size(); c++){
7772  if(m_crops[c]->m_cropType_almass == m_OurManager->TranslateCropCodes(crop_name)) return m_crops[c];
7773  }
7774  g_msg->Warn( WARN_FILE, "OptimisingFarm::findCropByName_almass():" "Unknown Code Identificator", crop_name.c_str() );
7775  exit(0);
7776 }
7777 
7779  for(int c=0; c< (int)m_crops.size(); c++){
7780  if(m_crops[c]->m_cropType_almass == a_tov_type) return m_crops[c];
7781  }
7782  char error_num[ 20 ];
7783  sprintf( error_num, "%d", a_tov_type);
7784  g_msg->Warn( WARN_BUG, "OptimisingFarm::findCropByName_almass():" "Unknown Code Identificator", error_num );
7785  exit(0);
7786 }
7787 
7788 void OptimisingFarm::sortCrops(vector<CropSort> &cropsToSort, string sortKey){
7792  if(sortKey=="GM"){
7793  for (int i=0; i<(int)cropsToSort.size(); i++){//define the key to sorting
7794  cropsToSort[i].key = cropsToSort[i].crop->m_GM;
7795  }
7796  }
7797  else if (sortKey=="Savings"){
7798  for (int i=0; i<(int)cropsToSort.size(); i++){//define the key to sorting
7799  cropsToSort[i].key = cropsToSort[i].crop->m_savings;
7800  }
7801  }
7802  else {
7803  for (int i=0; i<(int)cropsToSort.size(); i++){//define the key to sorting
7804  cropsToSort[i].key = cropsToSort[i].crop->m_GM_Savings;
7805  }
7806  }
7807 
7808  sort(cropsToSort.begin(), cropsToSort.end(), reverseSort());
7809 }
7810 
7811 void OptimisingFarm::randomizeCropList(vector<CropSort> &listToRandomize, string key){
7814  std::vector<CropSort>helper; //to store and shuffle elements with an equal value of a key
7815  helper.push_back(listToRandomize[0]); //save the first element of the list in the helper list
7816 
7817  for(int i=1; i<(int)listToRandomize.size(); i++){
7818  double key_current, key_previous;
7819  if(key=="GM"){
7820  key_current=listToRandomize[i].crop->m_GM;
7821  key_previous=listToRandomize[i-1].crop->m_GM;
7822  }
7823  else if (key=="Savings"){
7824  key_current=listToRandomize[i].crop->m_savings;
7825  key_previous=listToRandomize[i-1].crop->m_savings;
7826  }
7827  else if(key=="GM_Savings"){
7828  key_current=listToRandomize[i].crop->m_GM_Savings;
7829  key_previous=listToRandomize[i-1].crop->m_GM_Savings;
7830  }
7831  else{
7832  key_current=key_previous=0;
7833  g_msg->Warn( WARN_FILE, "OptimisingFarm::randomizeCropList():" "Unknown sorting key identificator", key.c_str() );
7834  exit(0);
7835  }
7836 
7837  if(key_current==key_previous){
7838  helper.push_back(listToRandomize[i]);
7839  }
7840  else{
7841  std::random_shuffle(helper.begin(), helper.end());
7842  //insert the elements of the vector - back to the original list
7843  //assign the elements of the vector in the reverse order (that's easier then the
7844  //normal order). The last element of the list has index = i-1.
7845  for(int j=(int)helper.size()-1; j>=0; j--){
7846  listToRandomize[i-1-j]=helper[j];
7847  }
7848  helper.clear(); //remove the elements...
7849  helper.push_back(listToRandomize[i]); //and 'start' a new vector with the current element
7850  }
7851  }
7852 }
7853 
7854 void OptimisingFarm::increaseCrops(vector<CropSort>cropsToIncrease, double &howMuchToIncrease){
7857  for(int i=0; howMuchToIncrease>0 && i<(int)cropsToIncrease.size(); i++){
7858  double area = cropsToIncrease[i].crop->m_areaPercent;
7859  double rotationMax = cropsToIncrease[i].crop->m_rotationMax;
7860  double rotMinCrop = cropsToIncrease[i].crop->m_rotationMin;
7861  if(area + howMuchToIncrease <= rotationMax){
7862  area += howMuchToIncrease; //finito
7863  howMuchToIncrease = 0;
7864  }
7865  else{
7866  howMuchToIncrease -= rotationMax-area;
7867  area = rotationMax;
7868  }
7869  cropsToIncrease[i].crop->m_areaPercent = area;
7870  cropsToIncrease[i].crop->m_areaVariable = area - rotMinCrop;
7871  }
7872 }
7873 
7874 void AnimalFarm::increaseCrops(vector<CropSort>cropsToIncrease, double &howMuchToIncrease){
7879  for(int i=0; howMuchToIncrease>0 && i<(int)cropsToIncrease.size(); i++){
7880  double area = cropsToIncrease[i].crop->m_areaPercent;
7881  double areaBefore = area;
7882  double rotationMax = cropsToIncrease[i].crop->m_rotationMax;
7883  double rotMinCrop = cropsToIncrease[i].crop->m_rotationMin;
7884  if(area + howMuchToIncrease <= rotationMax){
7885  area += howMuchToIncrease; //finito
7886  howMuchToIncrease = 0;
7887  }
7888  else{
7889  howMuchToIncrease -= rotationMax-area;
7890  area = rotationMax;
7891  }
7892  cropsToIncrease[i].crop->m_areaPercent = area;
7893  cropsToIncrease[i].crop->m_areaVariable = area - rotMinCrop;
7894 
7895  //checking if area has changed
7896  if(area > areaBefore){
7897  int index = (cfg_OptimiseBedriftsmodelCrops.value())? toc_Foobar*m_farmType + cropsToIncrease[i].crop->m_cropType : tov_Undefined*m_farmType + cropsToIncrease[i].crop->m_cropType_almass;
7898  bool fodder = m_OurManager->pm_data->Get_fodder(index);
7899  if(fodder){ //this is a fodder crop - so you need to buy less fodder (totalFUt)
7900  double resp = cropsToIncrease[i].crop->m_resp;
7901  double loss = cropsToIncrease[i].crop->m_totalLoss;
7902  double FUKey = m_OurManager->pm_data->Get_FUKey(index);
7903  double FUha = resp * (1-loss/100) * FUKey; //[ha * hkg/ha * FU/hkg = FU]
7904  double changeFU = (area-areaBefore) * m_totalArea/100 * FUha; //positive
7905  m_totalFUt -= changeFU;
7906  m_totalFUgrown += changeFU;
7907  }
7908  }
7909  }
7910 }
7911 
7912 void OptimisingFarm::decreaseCrops(vector<CropSort>cropsToDecrease, double &howMuchToDecrease){
7915  for(int j=(int)cropsToDecrease.size()-1; howMuchToDecrease>0 && j>=0; j--){ //start with the worst
7916  double areaCrop = cropsToDecrease[j].crop->m_areaPercent;
7917  double rotMinCrop = cropsToDecrease[j].crop->m_rotationMin;
7918  if(areaCrop - howMuchToDecrease >= rotMinCrop){
7919  areaCrop -= howMuchToDecrease;
7920  howMuchToDecrease = 0; //finito
7921  }
7922  else{
7923  howMuchToDecrease -= areaCrop - rotMinCrop;
7924  areaCrop = rotMinCrop;
7925  }
7926  cropsToDecrease[j].crop->m_areaPercent = areaCrop;
7927  cropsToDecrease[j].crop->m_areaVariable = areaCrop - rotMinCrop;
7928  }
7929 }
7930 
7931 void AnimalFarm::decreaseCrops(vector<CropSort>cropsToDecrease, double &howMuchToDecrease){
7936  for(int j=(int)cropsToDecrease.size()-1; howMuchToDecrease>0 && j>=0; j--){ //start with the worst
7937  double areaCrop = cropsToDecrease[j].crop->m_areaPercent;
7938  double areaBefore = areaCrop;
7939  double rotMinCrop = cropsToDecrease[j].crop->m_rotationMin;
7940  if(areaCrop - howMuchToDecrease >= rotMinCrop){
7941  areaCrop -= howMuchToDecrease;
7942  howMuchToDecrease = 0; //finito
7943  }
7944  else{
7945  howMuchToDecrease -= areaCrop - rotMinCrop;
7946  areaCrop = rotMinCrop;
7947  }
7948  cropsToDecrease[j].crop->m_areaPercent = areaCrop;
7949  cropsToDecrease[j].crop->m_areaVariable = areaCrop - rotMinCrop;
7950 
7951  if(areaCrop < areaBefore){
7952  int index = (cfg_OptimiseBedriftsmodelCrops.value())? toc_Foobar*m_farmType + cropsToDecrease[j].crop->m_cropType : tov_Undefined*m_farmType + cropsToDecrease[j].crop->m_cropType_almass;
7953  bool fodder = m_OurManager->pm_data->Get_fodder(index);
7954  if(fodder){ //this is a fodder crop - so you need to buy more fodder (totalFUt)
7955  double resp = cropsToDecrease[j].crop->m_resp;
7956  double loss = cropsToDecrease[j].crop->m_totalLoss;
7957  double FUKey = m_OurManager->pm_data->Get_FUKey(index);
7958  double FUha = resp * (1-loss/100) * FUKey; //[ha * hkg/ha * FU/hkg = FU]
7959  double changeFU = (areaBefore - areaCrop) * m_totalArea/100 * FUha; //positive number
7960  m_totalFUt += changeFU;
7961  m_totalFUgrown -= changeFU;
7962  }
7963  }
7964  }
7965 }
7966 
7967 void OptimisingFarm::determineAreas_ha(vector<CropOptimised*>allCrops){ //area in ha
7970  for(int i=0; i<(int)allCrops.size(); i++){
7971  double areaPercent = allCrops[i]->m_areaPercent;
7972  double area_ha = (areaPercent==0) ? 0 : (areaPercent/100 * m_totalArea);
7973  allCrops[i]->m_area_ha = area_ha;
7974  }
7975 }
7976 
7981  double totalAmount = 0;
7982  for (int i=0; i<(int)m_crops.size(); i++){
7983  double area_ha = m_crops[i]->m_area_ha;
7984  if(!area_ha==0){ //otherwise don't change totalAmount
7985  double value_per_ha;
7986  switch (a_var){
7987  case tocv_AreaPercent:
7988  value_per_ha = m_crops[i] ->m_areaPercent;
7989  break;
7990  case tocv_AreaHa:
7991  value_per_ha = m_crops[i] ->m_area_ha;
7992  break;
7993  case tocv_N:
7994  value_per_ha = m_crops[i] ->m_n;
7995  break;
7996  case tocv_Nt:
7997  value_per_ha = m_crops[i] ->m_nt;
7998  break;
7999  case tocv_BIHerb:
8000  value_per_ha = m_crops[i] ->m_BIHerb;
8001  break;
8002  case tocv_BIFi:
8003  value_per_ha = m_crops[i] ->m_BIFi;
8004  break;
8005  case tocv_BI:
8006  value_per_ha = m_crops[i] ->m_BI;
8007  break;
8008  case tocv_Grooming:
8009  value_per_ha = m_crops[i] ->m_grooming;
8010  break;
8011  case tocv_Hoeing:
8012  value_per_ha = m_crops[i] ->m_hoeing;
8013  break;
8014  case tocv_Weeding:
8015  value_per_ha = m_crops[i] ->m_weeding;
8016  break;
8017  case tocv_TotalLoss:
8018  value_per_ha = m_crops[i] ->m_totalLoss;
8019  break;
8020  case tocv_Response:
8021  value_per_ha = m_crops[i] ->m_resp;
8022  break;
8023  case tocv_Income:
8024  value_per_ha = m_crops[i] ->m_income_ha;
8025  break;
8026  case tocv_Costs:
8027  value_per_ha = m_crops[i] ->m_costs_ha;
8028  break;
8029  case tocv_GM:
8030  value_per_ha = m_crops[i] ->m_GM;
8031  break;
8032  case tocv_Savings:
8033  value_per_ha = m_crops[i] ->m_savings;
8034  break;
8035  default:
8036  g_msg->Warn( WARN_BUG, "OptimisingFarm::total(): ""Unknown crop variable type! ", "" );
8037  exit( 1 );
8038  }
8039  totalAmount += value_per_ha * area_ha; //each crop's/(field's) optimal values per ha multiplied by acreage of a crop
8040  }
8041  }
8042  return totalAmount;
8043  }
8044 
8045 void OptimisingFarm::Print_FarmVariables(ofstream * ap_output_file){
8048  //print the almass farm number
8049  (*ap_output_file) << m_almass_no << '\t';
8050 
8051  //print the values
8052  (*ap_output_file) << m_main_goal << '\t' << m_totalArea << '\t' << m_totalIncome<<'\t'<< m_totalCosts <<'\t'<< m_totalProfit <<'\t';
8053  (*ap_output_file) << m_totalFUdemand <<'\t' << m_totalFUdemandBefore << '\t' << m_totalFUt <<'\t'<< m_totalFUgrown << '\t';
8054  (*ap_output_file) << m_Nanim <<'\t'<< m_totalNanim <<'\t'<< m_totalNt <<'\t'<< m_totalN <<'\t';
8055  (*ap_output_file) << m_totalBI <<'\t'<< m_totalBIHerb <<'\t'<< m_totalBIFi <<'\t';
8056  (*ap_output_file) << m_totalGrooming <<'\t'<< m_totalHoeing <<'\t'<< m_totalWeeding <<'\t';
8057  (*ap_output_file) << endl;
8058 }
8059 
8063  double area_to_check = 0.0;
8064  for(int i=0; i<(int)m_crops.size(); i++) {
8065  area_to_check += m_crops[i]->m_areaPercent;
8066  }
8067 
8068  if(area_to_check > 100.0001 || area_to_check < 99.999){ //issue a warning
8069  ofstream ofile("Check_if_area_is_100%.txt",ios::app);
8070  ofile << m_almass_no << '\t' << "Farms area is not equal to 100%. The sum of crops areaPercent is: " << area_to_check << endl;
8071  ofile.close();
8072  }
8073 }
8074 
8080  for(int i = 0; i < (int)m_crops.size(); i++){
8081  if(m_crops[i]->m_areaPercent > 0){
8082  TTypesOfCrops toc = m_crops[i]->m_cropType; //Bedriftsmodel crop type
8083  TTypesOfVegetation tov;
8084 
8085  switch (toc) {
8086  case 0: //toc_SBarley
8087  tov = tov_SpringBarley;
8088  break;
8089  case 1: //toc_Oats
8090  tov = tov_Oats;
8091  break;
8092  case 2: //toc_OSCrops
8093  tov = tov_SpringBarley; //spring wheat - no code for this crop
8094  break;
8095  case 3: //toc_WBarley
8096  tov = tov_WinterBarley;
8097  break;
8098  case 4: //toc_WWheat
8099  tov = tov_WinterWheat;
8100  break;
8101  case 5: //toc_WRye
8102  tov = tov_WinterRye;
8103  break;
8104  case 6: //toc_Triticale
8105  tov = tov_Triticale;
8106  break;
8107  case 7: //toc_SRape
8108  tov = tov_SpringRape;
8109  break;
8110  case 8: //toc_WRape
8111  tov = tov_WinterRape;
8112  break;
8113  case 9: //toc_OOilseed
8114  tov = tov_WinterRape;
8115  break;
8116  case 10: //toc_Peas
8117  tov = tov_FieldPeas;
8118  break;
8119  case 11: //toc_OLSeed
8120  tov = tov_FieldPeas;
8121  break;
8122  case 12: //toc_GrassSeed //TRANSLATES TO TWO ALMASS CROPS
8123  tov = tov_SeedGrass1; //this translates to both tov_SeedGrass1 and tov_SeedGrass2; thus sg2 has to be considered in the rotation vector after the sg1; both get area percent = half of the original crop area percent
8124  break;
8125  case 13: //toc_Potato
8126  tov = tov_PotatoesIndustry;
8127  break;
8128  case 14: //toc_PotatoFood
8129  tov = tov_Potatoes;
8130  break;
8131  case 15: //toc_SugarBeet
8132  tov = tov_FodderBeet;
8133  break;
8134  case 16: //toc_GrassClover //TRANSLATES TO TWO ALMASS CROPS
8135  tov = tov_CloverGrassGrazed1; // also tov_CloverGrassGrazed2; need to first aggregate with CloverGrz and then divide the sum by two!
8136  break;
8137  case 17: //toc_OLSeedCut
8138  tov = tov_FieldPeasSilage;
8139  break;
8140  case 18: //toc_SCerealSil
8141  tov = tov_SpringBarleySilage; //undersown
8142  break;
8143  case 19: //toc_PeasSil
8144  tov = tov_FieldPeasSilage;
8145  break;
8146  case 20: //toc_MaizeSil
8147  tov = tov_MaizeSilage; //
8148  break;
8149  case 21: //toc_WCerealSil
8150  tov = tov_SpringBarleySilage;
8151  break;
8152  case 22: //toc_SCerealG
8153  tov = tov_SpringBarleySilage;
8154  break;
8155  case 23: //toc_PerGrassLow
8157  break;
8158  case 24: //toc_PerGrassNorm
8160  break;
8161  case 25: //toc_GrassEnv1
8162  tov = tov_PermanentGrassTussocky; // is aggregated with GrassEnv2
8163  break;
8164  case 26: //toc_GrassEnv2
8165  tov = tov_PermanentGrassTussocky; // is aggregated with GrassEnv1
8166  break;
8167  case 27: //toc_GrassRot
8168  tov = tov_FodderGrass;
8169  break;
8170  case 28: //toc_Setaside
8171  tov = tov_Setaside;
8172  break;
8173  case 29: //toc_Uncult
8174  tov = tov_PermanentSetaside;
8175  break;
8176  case 30: //toc_OUncult
8177  tov = tov_PermanentSetaside;
8178  break;
8179  case 31: //toc_FodderBeet
8180  tov = tov_FodderBeet;
8181  break;
8182  case 32: //toc_CloverGrz //TRANSLATES TO TWO ALMASS CROPS
8183  tov = tov_CloverGrassGrazed1; // also tov_CloverGrassGrazed2; need to first aggregate with GrassClover and then divide the sum by two!
8184  break;
8185  case 33: //toc_Veg
8186  tov = tov_Carrots;
8187  break;
8188  case 34: //toc_Fruit
8189  tov = tov_OrchardCrop;
8190  break;
8191  case 35: //toc_FruitTree
8192  tov = tov_OrchardCrop;
8193  break;
8194  case 36: //toc_OSpecCrops
8195  tov = tov_Carrots; // could be also smth else
8196  break;
8197  case 37: //toc_ChrisTree
8198  tov = tov_YoungForest;
8199  break;
8200  case 38: //toc_EnergyFor
8201  tov = tov_YoungForest; // ideally should be willow
8202  break;
8203  case 39: //toc_Other
8204  tov = tov_Carrots; // this also could be smth else
8205  break;
8206  default:
8207  g_msg->Warn( WARN_BUG, "OptimisingFarm::Translate_crops_to_almass(): ""Unknown crop type! ", "" );
8208  exit( 1 );
8209  }
8210 
8211  //try not separating fixed from variables crops
8212  AlmassCrop crop = { m_crops[i]->m_areaPercent, tov};
8213  m_crops_almass.push_back(crop);
8214 
8215  } //if
8216  }//for
8217 
8218  //aggregate the almass crops that are in >1 position in the m_crops vector - so that they are listed only once
8219 
8220  vector<AlmassCrop>crops_almass_aggregated;
8221  int size = (int)m_crops_almass.size();
8222 
8223  for(int i = 0; i < size; i++){
8224  TTypesOfVegetation tov1 = m_crops_almass[i].Tov;
8225  double summaryArea = m_crops_almass[i].Number; //initialize
8226  bool skip = false;
8227 
8228  for(int p = 0; p < i; p++){ //check if this tov was already aggregated (so check elements of the vector before this one)
8229  if(m_crops_almass[p].Tov == tov1){ //this tov is already aggregated, so skip i element
8230  skip = true;
8231  }
8232  }
8233  if (!skip){
8234  for(int j = i+1; j < size; j++){ // start comparing with the crop following the one at position i
8235  if(m_crops_almass[j].Tov == tov1){
8236  summaryArea += m_crops_almass[j].Number; //add area to the summary area
8237  }
8238  }
8239  AlmassCrop crop = {summaryArea, m_crops_almass[i].Tov, };
8240  crops_almass_aggregated.push_back(crop);
8241  }
8242  }
8243  m_crops_almass = crops_almass_aggregated; //save the aggregated crops in m_crops_almass vector
8244 
8245 
8246  //now deal with the crops that translate to more than one almass crop, i.e.:
8247  //1) GrassClover + CloverGrz = CGG1 + CGG2
8248  //2) GrassSeed = SG1 + SG2
8249 
8250 
8251  for(int i = 0; i < (int)m_crops_almass.size(); i++){
8252  if(m_crops_almass[i].Tov == tov_CloverGrassGrazed1){
8253  double pct = (m_crops_almass[i].Number)/2; //have to divide the area between CGG1 and CGG2
8254  m_crops_almass[i].Number = pct;
8255  AlmassCrop cgg2 = {pct, tov_CloverGrassGrazed2};
8256  m_crops_almass.push_back(cgg2);
8257  }
8258  if(m_crops_almass[i].Tov == tov_SeedGrass1){
8259  double pct = (m_crops_almass[i].Number)/2; //have to divide the area between SG1 and SG2
8260  m_crops_almass[i].Number = pct;
8261  AlmassCrop sg2 = {pct, tov_SeedGrass2};
8262  m_crops_almass.push_back(sg2);
8263  }
8264  }
8265 
8266 }
8267 
8268 
8273  m_crops_almass.clear();
8274 
8275  for(int i = 0; i < (int)m_crops.size(); i++){
8276  if(m_crops[i]->m_areaPercent > 0){
8277  TTypesOfVegetation tov = m_crops[i]->m_cropType_almass;
8278  AlmassCrop crop = { m_crops[i]->m_areaPercent, tov};
8279  m_crops_almass.push_back(crop);
8280  }
8281  }
8282 
8283 }
8284 
8286 
8287  //first deal with the probelmatic crops:CGG1 + CGG2 and SB, and SG1 + SG2
8288  double area_cgg=0;
8289  for(int i = 0; i < (int)m_crops_almass.size(); i++){
8290  if(m_crops_almass[i].Tov == tov_CloverGrassGrazed1){
8291  bool cg2=false;
8292  for(int j = 0; j < (int)m_crops_almass.size(); j++){
8293  if(m_crops_almass[j].Tov == tov_CloverGrassGrazed2){
8294  double pct = (m_crops_almass[i].Number + m_crops_almass[j].Number)/2; //take average
8295  m_crops_almass[i].Number = pct;
8296  m_crops_almass[j].Number = pct;
8297  area_cgg = pct;
8298  cg2=true;
8299  }
8300  }
8301  if(!cg2){ //there is cgg1 but not cgg2
8302  double pct = (m_crops_almass[i].Number)/2; //divide cgg1 area by two and save it in cgg1 and create cgg2
8303  m_crops_almass[i].Number = pct;
8304  area_cgg = pct;
8305  AlmassCrop cgg2 = {pct, tov_CloverGrassGrazed2};
8306  m_crops_almass.push_back(cgg2);
8307  }
8308  break;
8309  }
8310  }
8311 
8312  //cgg and sb
8313  bool sb=false;
8314  double new_area = area_cgg; //initialize with the current area of cgg - maybe it won't change
8315  for(int i = 0; i < (int)m_crops_almass.size(); i++){
8316  if(m_crops_almass[i].Tov == tov_SpringBarley){
8317  sb=true;
8318  double area_sb = m_crops_almass[i].Number;
8319  if(area_sb < area_cgg){ //problem
8320  new_area = (area_sb + 2*area_cgg)/3;
8321  m_crops_almass[i].Number = new_area;
8322  }
8323  break;
8324  }
8325  }
8326  if(!sb){ //there wasn't spring barley - need to add
8327  new_area = area_cgg*2/3;
8328  if(new_area >0){ //otherwise do not add sbarley
8329  AlmassCrop sbarley = {new_area, tov_SpringBarley};
8330  m_crops_almass.push_back(sbarley);
8331  }
8332  }
8333  //now find both cgg and change their areas
8334  for(int j = 0; j < (int)m_crops_almass.size(); j++){
8335  if(m_crops_almass[j].Tov == tov_CloverGrassGrazed1){
8336  m_crops_almass[j].Number = new_area;
8337  }
8338  if(m_crops_almass[j].Tov == tov_CloverGrassGrazed2){
8339  m_crops_almass[j].Number = new_area;
8340  }
8341  }
8342 
8343 
8344 
8345  //sg1 and sg2
8346  for(int i = 0; i < (int)m_crops_almass.size(); i++){
8347  if(m_crops_almass[i].Tov == tov_SeedGrass1){
8348  bool sg2=false;
8349  for(int j = 0; j < (int)m_crops_almass.size(); j++){
8350  if(m_crops_almass[j].Tov == tov_SeedGrass2){
8351  double pct = (m_crops_almass[i].Number + m_crops_almass[j].Number)/2; //take average
8352  m_crops_almass[i].Number = pct;
8353  m_crops_almass[j].Number = pct;
8354  sg2=true;
8355  }
8356  }
8357  if(!sg2){ //there is cgg1 but not cgg2
8358  double pct = (m_crops_almass[i].Number)/2; //divide cgg1 area by two and save it in cgg1 and create cgg2
8359  m_crops_almass[i].Number = pct;
8360  AlmassCrop sgrass2 = {pct, tov_SeedGrass2};
8361  m_crops_almass.push_back(sgrass2);
8362  }
8363  break;
8364  }
8365  }
8366 
8367  //first clear the current m_rotational_crops
8368  m_rotational_crops.clear();
8369 
8370  //then add rotational crops from the list of all crops - both rotational and permanent
8371  m_area_rot = 0;//sum of areas of rotational crops - need it for checking if there is any field without perm crops in case there are no rot. crops
8372  for(int i = 0; i < (int)m_crops_almass.size(); i++){
8373  TTypesOfVegetation tov = m_crops_almass[i].Tov;
8374 
8377  //do nothing - just need rotational crops
8378  }
8379  else {
8380  double pct = m_crops_almass[i].Number;
8381  if(pct<0.5) pct+=0.5; //thanks to that such crop won't disappear! (won't have area=0 after rounding)
8382  AlmassCrop pcd = {pct, tov};
8383  m_rotational_crops.push_back(pcd);
8384  m_area_rot += pct;
8385  }
8386  }
8387 }
8388 
8389 void OptimisingFarm::Print_rotations(ofstream * ap_output_file){
8392  //print the almass farm number
8393  //(*ap_output_file) << m_almass_no << '\t';
8394 
8395  //print the content of the m_rotation vector
8396  for(int i=0; i<(int)m_rotation.size(); i++){
8397  TTypesOfVegetation crop = m_rotation[i];
8398  (*ap_output_file) << i << '\t' << crop << endl;
8399  }
8400  (*ap_output_file) << endl;
8401 }
8402 
8411  //1. STOCK FARM
8413  else m_stockfarmer = false;
8414 
8415  //2. INTENSITY - skip
8416 
8417  //3. PERMANENT vs ROTATIONAL CROPS
8418  //sort them and put into two vectors: m_PermCrops (member of Farm class, type: struct PermCropData) + local vector rotational_crops (type: struct AlmassCrop)
8419 
8420  int no_perm = 0;
8421  int no_rotational = 0;
8422  int area_perm = 0; //sum of areas of permanent crops
8423  m_area_rot = 0; //sum of areas of rotational crops
8424 
8425  for(int i = 0; i < (int)m_crops_almass.size(); i++){
8426  TTypesOfVegetation tov = m_crops_almass[i].Tov;
8427 
8430  int pct = (int)(m_crops_almass[i].Number + 0.5); //round a double to int
8431  PermCropData pcd = {tov, pct};
8432  m_PermCrops.push_back(pcd);
8433  no_perm++;
8434  area_perm += pct;
8435  }
8436  else {
8437  double pct = m_crops_almass[i].Number;
8438  if(pct<0.5) pct+=0.5; //thanks to that such crop won't disappear! (won't have area=0 after rounding)
8439  AlmassCrop pcd = {pct, tov};
8440  m_rotational_crops.push_back(pcd);
8441  no_rotational++;
8442  m_area_rot += pct;
8443  }
8444  }
8445 
8446  //4. ROTATIONAL CROPS
8447 
8448  //first check if there are any rotational crops!
8449  if(m_rotational_crops.size()!=0){
8450 
8451  m_rotation.resize(100);
8452  vector<TTypesOfVegetation>all_crops; //vector the has a right proportion of each crop tov type
8453  vector<MakeRotation>rotation;
8454  rotation.resize(100);
8455 
8456  //scale the rotational crop areas to account for the area that is reserved for permanent crops
8457  //and
8458  //save scaled areas of SBarley and CGG1 to make a check in the next step
8459  int area_rot_int = (int)(m_area_rot + 0.5); //area in percent of rot crops - as an integer
8460  int SBarley_area=0;
8461  int CGG1_area=0;
8462 
8463  for(int i=0; i<(int)m_rotational_crops.size(); i++){
8464  double area = m_rotational_crops[i].Number;
8465  int area_scaled = (int)(100 * area / area_rot_int + 0.5);
8466  m_rotational_crops[i].Number = area_scaled;
8467  if(m_rotational_crops[i].Tov == tov_CloverGrassGrazed1) CGG1_area = (int) m_rotational_crops[i].Number; //scaled area
8468  if(m_rotational_crops[i].Tov == tov_SpringBarley) SBarley_area = (int) m_rotational_crops[i].Number; //(this is scaled area)
8469  }
8470 
8471  //check if we have enough spring barley for CGG1 and CGG2 (area CGG1 = area CGG2); if not - change the areas so that
8472  //SBarley = CGG1 = CGG2 area.
8473  if(SBarley_area < CGG1_area){ //problem
8474  if(SBarley_area == 0){ //there's no sbarley! - need to create
8475  AlmassCrop sbarley = {0, tov_SpringBarley};
8476  m_rotational_crops.push_back(sbarley); //add sbarley
8477  }
8478  int new_area = (int)((CGG1_area * 2 + SBarley_area)/3 + 0.5); //= (CGG1 + CGG2 + SBarley)/3 ->and take integer
8479  for(int i=0; i<(int)m_rotational_crops.size(); i++){
8482  m_rotational_crops[i].Number = new_area;
8483  }
8484  }
8485  }
8486 
8487 
8488  //fill the all_crops vector with tov types -> in the right proportions
8489  for(int i = 0; i<(int)m_rotational_crops.size(); i++){
8490  int area = (int) m_rotational_crops[i].Number; //conversion to int - OK! - this is already int after the previous for loop
8491  for(int j = 0; j<area; j++){
8492  all_crops.push_back(m_rotational_crops[i].Tov);
8493  }
8494  }//now the size of all_crops might NOT be 100! - so check and make it to be 100?
8495 
8496  //sort the all_crops vector and rearrange it so that the probability of two crops that cannot follow each other is minimised
8497  //so - the order of the for loops below matter!!!
8498  vector<TTypesOfVegetation>all_crops_helper; //vector helper
8499 
8500  for(int i = (int)all_crops.size()-1; i>=0; i--){
8501  if(all_crops[i] == tov_SpringBarley) {
8502  all_crops_helper.push_back(all_crops[i]);
8503  all_crops.erase(all_crops.begin() + i);
8504  }
8505  }
8506 
8507  for(int i = (int)all_crops.size()-1; i>=0; i--){
8508  if(all_crops[i] == tov_CloverGrassGrazed1) {
8509  all_crops_helper.push_back(all_crops[i]);
8510  all_crops.erase(all_crops.begin() + i);
8511  }
8512  }
8513  for(int i = (int)all_crops.size()-1; i>=0; i--){
8514  if(all_crops[i] == tov_CloverGrassGrazed2) {
8515  all_crops_helper.push_back(all_crops[i]);
8516  all_crops.erase(all_crops.begin() + i);
8517  }
8518  }
8519  for(int i = (int)all_crops.size()-1; i>=0; i--){
8520  if(all_crops[i] == tov_FodderBeet) {
8521  all_crops_helper.push_back(all_crops[i]);
8522  all_crops.erase(all_crops.begin() + i);
8523  }
8524  }
8525  for(int i = (int)all_crops.size()-1; i>=0; i--){
8526  if(all_crops[i] == tov_WinterRape) {
8527  all_crops_helper.push_back(all_crops[i]);
8528  all_crops.erase(all_crops.begin() + i);
8529  }
8530  }
8531  for(int i = (int)all_crops.size()-1; i>=0; i--){
8532  if(all_crops[i] == tov_SpringRape) {
8533  all_crops_helper.push_back(all_crops[i]);
8534  all_crops.erase(all_crops.begin() + i);
8535  }
8536  }
8537  for(int i = (int)all_crops.size()-1; i>=0; i--){
8538  if(all_crops[i] == tov_Potatoes) {
8539  all_crops_helper.push_back(all_crops[i]);
8540  all_crops.erase(all_crops.begin() + i);
8541  }
8542  }
8543  for(int i = (int)all_crops.size()-1; i>=0; i--){
8544  if(all_crops[i] == tov_SeedGrass1) {
8545  all_crops_helper.push_back(all_crops[i]);
8546  all_crops.erase(all_crops.begin() + i);
8547  }
8548  }
8549  for(int i = 0; i<(int)all_crops.size(); i++){
8550  if(all_crops[i] == tov_SeedGrass2) {
8551  all_crops_helper.push_back(all_crops[i]);
8552  all_crops.erase(all_crops.begin() + i);
8553  }
8554  }
8555  for(int i = (int)all_crops.size()-1; i>=0; i--){
8556  if(all_crops[i] == tov_FieldPeas) {
8557  all_crops_helper.push_back(all_crops[i]);
8558  all_crops.erase(all_crops.begin() + i);
8559  }
8560  }
8561  for(int i = (int)all_crops.size()-1; i>=0; i--){
8562  if(all_crops[i] == tov_FieldPeasSilage) {
8563  all_crops_helper.push_back(all_crops[i]);
8564  all_crops.erase(all_crops.begin() + i);
8565  }
8566  }
8567  for(int i = (int)all_crops.size()-1; i>=0; i--){
8568  if(all_crops[i] == tov_WinterBarley) {
8569  all_crops_helper.push_back(all_crops[i]);
8570  all_crops.erase(all_crops.begin() + i);
8571  }
8572  }
8573  for(int i = (int)all_crops.size()-1; i>=0; i--){
8574  if(all_crops[i] == tov_WinterWheat) {
8575  all_crops_helper.push_back(all_crops[i]);
8576  all_crops.erase(all_crops.begin() + i);
8577  }
8578  }
8579  for(int i = (int)all_crops.size()-1; i>=0; i--){
8580  if(all_crops[i] == tov_Setaside) {
8581  all_crops_helper.push_back(all_crops[i]);
8582  all_crops.erase(all_crops.begin() + i);
8583  }
8584  }
8585 
8586  for(int i = (int)all_crops.size()-1; i>=0; i--){
8587  if(all_crops[i] == tov_MaizeSilage) {
8588  all_crops_helper.push_back(all_crops[i]);
8589  all_crops.erase(all_crops.begin() + i);
8590  }
8591  }
8592 
8593  //now place the other - remaining crops (in the all_crops vector) in further positions of the helper vector
8594  for(int i = 0; i<(int)all_crops.size(); i++){
8595  all_crops_helper.push_back(all_crops[i]);
8596  }
8597 
8598  //check if the size is 100 - correct if not
8599  if(all_crops_helper.size()!=100){
8600  if(all_crops_helper.size()>100){
8601  for(int i = (int)all_crops_helper.size(); i>100; i--){
8602  all_crops_helper.erase(all_crops_helper.end()-1); //just remove the last element
8603  }
8604  }
8605  else{ //<100
8606  for(int i = (int)all_crops_helper.size(); i<100; i++){
8607  if(all_crops_helper[i-2] != tov_CloverGrassGrazed2) all_crops_helper.push_back(all_crops_helper[i-2]); //this way I duplicate the ending (max 2/4 last elements)
8608  else all_crops_helper.push_back(tov_SpringBarley); //add spring barley
8609  }
8610  }
8611  }
8612 
8613  //copy the helper to all_crops
8614  all_crops = all_crops_helper;
8615 
8616 
8617  //fill the rotation vector with tov_Undefined
8618  for(int i = 0; i<(int)rotation.size(); i++){
8619  rotation[i].Tov = tov_Undefined;
8620  }
8621 
8622 
8623  // go through all_crops - should be 100...
8624 
8625  for(int i = 0; i < (int)all_crops.size(); i++){
8626 
8627  //find a place for the tov in the rotation vector:
8628  bool test=false;
8629  int count=0;
8630  TTypesOfVegetation crop_index = all_crops[i]; //current crop (tov) you want to place in a vector
8631 
8632  int step=no_rotational;
8633  int pp=0;
8634 
8635  for(int j = pp; count<101 && test==false; j=j+step){
8636  double sb_area = (cfg_OptimiseBedriftsmodelCrops.value())? findCropByName ("SBarley")->m_areaPercent : findCropByName_almass ("SpringBarley")->m_areaPercent;
8637  if (crop_index == tov_SpringBarley && sb_area > (100/step)) step = (int)(100/sb_area + 0.5);
8638  if(j>=100) {//without this we would always start out in the same position
8639  if (crop_index == tov_SpringBarley) {pp+=3; j=pp;} //special case - sbarley, cgg1 and cgg2; has to be 3 - doesn't work with 4
8640  else j=++pp;
8641  }
8642 
8643  if(!(rotation[j].taken)){ //not taken - so check if it is allowed here - lookup
8644 
8645  TTypesOfVegetation crop_before, crop_after;
8646 
8647  crop_before = (j==0) ? rotation[99].Tov : rotation[j-1].Tov;
8648  crop_after = (j==99) ? rotation[0].Tov : rotation[j+1].Tov;
8649 
8650  int lookup_before = m_OurManager->Get_lookup_table(crop_before * (tov_Undefined+1) + crop_index); //check with a preceeding crop; tov_undef+1 - because this tov_undef is included in the lookup table
8651  int lookup_after = m_OurManager->Get_lookup_table(crop_index * (tov_Undefined+1) + crop_after); //check with a following crop
8652 
8653  if(lookup_before==-1 || lookup_after==-1){ //issue a warning: wrong index...
8654  char index[ 20 ];
8655  sprintf( index, "%d", crop_index);
8656  g_msg->Warn( WARN_BUG, "OptimisingFarm::Make_rotations(): Error (possibly caused by a new tov type that is not incuded in the crops_lookup table) in reading the lookup table; tov type that should not appear: ", index );
8657  exit( 1 );
8658  }
8659 
8660  if(lookup_before==1 && lookup_after==1){
8661  rotation[j].Tov = all_crops[i]; //same as crop_index
8662  rotation[j].taken = true;
8663  test=true;
8664  }
8665  else count++; //did not succeed in placing the crop, so increase the count
8666  }
8667  else{
8668  count++; //did not succeed in placing the crop, so increase the count
8669  }
8670 
8671  } //inner for loop: searching for a place for a given crop
8672 
8673  if(test==false){ //there is no place that does not break the lookup table rules
8674 
8675  //so try to go through the whole rotation and find a place where the current crop fits
8676 
8677  for(int r=0; r<(int)rotation.size() && test==false; r++){
8678 
8679  TTypesOfVegetation crop_before, crop_after;
8680 
8681  crop_before = rotation[r].Tov;
8682  crop_after = (r==99) ? rotation[0].Tov : rotation[r+1].Tov;
8683  int lookup_before = m_OurManager->Get_lookup_table(crop_before * (tov_Undefined+1) + crop_index); //check with a preceeding crop; tov_undef+1 - because this tov_undef is included in the lookup table
8684  int lookup_after = m_OurManager->Get_lookup_table(crop_index * (tov_Undefined+1) + crop_after); //check with a following crop
8685 
8686  if(lookup_before==1 && lookup_after==1){
8687  MakeRotation crop = {true, all_crops[i]};
8688  rotation.insert(rotation.begin() + r+1, crop); //->insert before element r+1
8689  test=true;
8690 
8691  //need to remove 1 element of the rotation! as 1 additional was just inserted
8692  //but this might cause troubles: two already placed elements might become incompatible...
8693 
8694  for(int p=(int)rotation.size()-1; p>=0; p--){//start at the end - more efficient, as here should be empty elements
8695  if(rotation[p].Tov == tov_Undefined){
8696  rotation.erase(rotation.begin() + p);
8697  //check if the 'new neighbours' can be next to each other
8698  crop_before = (p==0) ? rotation[99].Tov : rotation[p-1].Tov;
8699  crop_after = (p==100) ? rotation[0].Tov : rotation[p].Tov; //100 because the index is p
8700  int crop_after_position = (p==100) ? 0 : p;
8701 
8702  lookup_before = m_OurManager->Get_lookup_table(crop_before * (tov_Undefined+1) + crop_after); //check with a preceeding crop; tov_undef+1 - because this tov_undef is included in the lookup table
8703 
8704  TTypesOfVegetation crop_before1, crop_after1, crop_before2;
8705  crop_before2=tov_Undefined; //for the begininng
8706  int crop_before2_position = 0; // **CJT** Added to remove warning 09-08-2018
8707  int count2=0;
8708 
8709  while(lookup_before!=1){ //need to move somewhere the crop_after
8710 
8711  //check if there is no correct rotation possible
8712  if(count2>100){ //problem: impossible to make a rotation
8713  //so switch some crop...to Spring Barley
8714  TTypesOfVegetation problem_crop = rotation[crop_before2_position].Tov;
8715  rotation[crop_before2_position].Tov = tov_SpringBarley;
8716  //issue a message
8717  char index[ 20 ];
8718  sprintf( index, "%d", problem_crop);
8719  g_msg->Warn( WARN_BUG, "OptimisingFarm::Make_rotations(): The following crop was changed to spring barley: ", index );
8720  break; //break the if
8721  }
8722 
8723  crop_index = crop_after; //now crop_after is searching for a place
8724  bool test2=false;
8725  for(int t=0; t<(int)rotation.size() && test2==false; t++){
8726  crop_before1 = rotation[t].Tov;
8727  crop_after1 = (t==99) ? rotation[0].Tov : rotation[t+1].Tov;
8728  int lookup_before1 = m_OurManager->Get_lookup_table(crop_before1 * (tov_Undefined+1) + crop_index); //check with a preceeding crop; tov_undef+1 - because this tov_undef is included in the lookup table
8729  int lookup_after1 = m_OurManager->Get_lookup_table(crop_index * (tov_Undefined+1) + crop_after1); //check with a following crop
8730 
8731  if(lookup_before1==1 && lookup_after1==1){
8732  //check for indefinite loop
8733 
8734  bool skip=true;
8735  for(int s=crop_after_position; s!=t+1; s++){ //check locations between;
8736  if(s==100) s=0;
8737  TTypesOfVegetation crop = rotation[s].Tov;
8738  int lookup = m_OurManager->Get_lookup_table(crop_before2 * (tov_Undefined+1) + crop);
8739  if( lookup == 1){
8740  skip = false;
8741  break; //there is a different crop that the one that we removed (crop_index) - so there shouldnt be an infinite loop
8742  }
8743  }
8744 
8745  if(!skip){
8746 
8747  MakeRotation crop = {true, crop_index};
8748  rotation.insert(rotation.begin() + t+1, crop);
8749  //now the crop to be removed can be at the same or changed position, depending on where we inserted the crop
8750 
8751  if(t+1 > crop_after_position){ //OK
8752  rotation.erase(rotation.begin() + crop_after_position); //remove the crop that was just placed in a new position-from the old one
8753  crop_before2 = (crop_after_position==0) ? rotation[99].Tov : rotation[crop_after_position-1].Tov;
8754  crop_before2_position = (crop_after_position==0) ? 99 : crop_after_position-1;
8755  crop_after = (crop_after_position==99) ? rotation[0].Tov : rotation[crop_after_position].Tov;
8756  crop_after_position = (crop_after_position==99) ? 0 : crop_after_position;
8757  lookup_before = m_OurManager->Get_lookup_table(crop_before2 * (tov_Undefined+1) + crop_after);
8758  }
8759  else{
8760  rotation.erase(rotation.begin() + crop_after_position + 1); //can be 99+1 -ok, now the size is 101
8761  crop_before2 = (crop_after_position==0) ? rotation[99].Tov : rotation[crop_after_position].Tov;
8762  crop_before2_position = (crop_after_position==0) ? 99 : crop_after_position;
8763  crop_after = (crop_after_position==99) ? rotation[0].Tov : rotation[crop_after_position+1].Tov;
8764  crop_after_position = (crop_after_position==99) ? 0 : crop_after_position+1;
8765  lookup_before = m_OurManager->Get_lookup_table(crop_before2 * (tov_Undefined+1) + crop_after);
8766  }
8767  test2=true;
8768  }
8769 
8770  }
8771 
8772  }
8773  count2++;
8774  } //while
8775 
8776  break; //break the for (index p) loop, need to remove just one element
8777  }//undefined removed
8778  }//for:searching for an undef element to remove
8779  }//if:found a place to put an element that doesnt fit in any empty space left
8780  }//for: searching for a place for a problematic crop
8781 
8782  if(test==false){ //we have a problem
8783  char index[ 20 ];
8784  sprintf( index, "%d", crop_index);
8785  //sprintf( index, "%d", m_almass_no);
8786  g_msg->Warn( WARN_BUG, "OptimisingFarm::Make_rotations(): The following tov type cannot be assigned a place in the rotation: ", index );
8787  exit( 1 );
8788  }
8789 
8790  }//there's no empty space that fits for the current crop
8791  }//outer for loop: searcin for an empty spae for a current crop
8792 
8793 
8794  //copy the tovs from rotation vector to the m_rotation vector
8795  for(int i=0; i<100; i++){
8796  m_rotation[i] = rotation[i].Tov;
8797  }
8798 
8799  }//if there are any rotational crops
8800 
8801 else{ //no rotational crops
8802  m_rotation.resize(0);
8803  }
8804 }
8805 
8814  vector<TTypesOfVegetation> veg_type;
8815  //vector<double>profits; //profit from each field
8816  //profits.resize(m_fields.size());
8817 
8818  double priceNt = cfg_Price_Nt.value();
8819 
8820  //for energy maize impacts on wildlife
8821  bool emaize=false;
8822 
8823  //exp. agg. yield - for now it is not necessary to do this every year since the fields size is constant, but later it might change!
8824  m_exp_aggregated_yield = (double)m_fields.size(); //cause each field is expected to give 100% = 1. Except the fields with a crop with exp yield = 0.
8825 
8826  //go through all farm's field:
8827  for(int i=0; i<(int)m_fields.size(); i++){
8828 
8829  CropActualValues crop_data;
8830  TTypesOfVegetation crop;
8831  double biomass=0; double area=0; double yield_loss_pest=0; double no_herb_app=0; double no_fi_app=0;
8832  double unit_loss_herb=0; double unit_loss_fi=0; //to determine or take from field's data
8833  double yield_ha=0; double income_ha=0; double income=0; double costs_ha=0; double costs=0; double profit_ha=0; double profit=0; //to determine
8834  double yield_exp=0; double yield_ratio=0; double income_exp=0; double costs_exp=0; double profit_exp=0; //to account for - it was already calculated per crop in the determine GM function
8835  double sellingPrice=0; double priceHerb=0; double priceFi=0; double priceLM=0; double priceH=0; double priceW=0; double priceG=0; double subsidy=0; //economic data - need to be given as input;
8836  double no_missed_herb_app, no_missed_fi_app = 0; //no_missed - how many applications of herb/fi were missed
8837  double fert_applied=0; double fert_opt=0; double fert_trade=0; double beta1=0; double beta2=0; double alfaH=0; double alfaFI=0;
8838  double yield_factor = 0; //this serves both as biomass-to-yield factor and day degrees-to-yield factor - they are saved in one input table (a single crop has just one of these factors!)
8839  VegElement * pf = dynamic_cast<VegElement*>(m_fields[i]);
8840 
8841  int cropDataStorage_index=-1; //initialize
8842 
8843  if(pf->Get_taken(1)){ //there is a crop at position one - so account for this crop; otherwise go to position 0
8844  crop_data = pf->Get_CropDataStorage(1);
8845  cropDataStorage_index = 1;
8846  }
8847  else{
8848  crop_data = pf->Get_CropDataStorage(0);
8849  cropDataStorage_index = 0;
8850  if(crop_data.taken==false){//error
8851  g_msg->Warn( WARN_BUG, "OptimisingFarm::ActualProfit(): There is no crop data in the fields m_CropDataStorage", "" );
8852  exit( 1 );
8853  }
8854  }
8855 
8856  crop = crop_data.tov_type;
8857 
8858  //for energy maize impacts on wildlife
8859  if (crop==tov_Maize) emaize = true;
8860  //
8861 
8862  bool do_accounting = true;
8863  if(cropDataStorage_index==0){ //could be this crop was not harvested yet
8864  bool harvested = crop_data.harvested;
8867  && !harvested){
8868  //this is a crop that shoud be harvested, but so far it wasn't - so do not account for this crop yet! - just skip this field in accounting
8869  do_accounting = false;
8870  }
8871  }
8872 
8873  if(do_accounting){
8874  area = crop_data.area * 0.0001; //change the units from sq. meters to ha!
8875 
8876  if(crop==tov_SeedGrass1 || crop==tov_SeedGrass2){ //alfaherb is more than 100! - so problem with negative yield
8877  double betaH = crop_parameter(crop, "BetaHerb");
8878  alfaFI = crop_parameter(crop, "AlfaFi");
8879  unit_loss_herb = betaH/100/2;
8880  unit_loss_fi = alfaFI/100;
8881  }
8882  else{
8883  alfaH = crop_parameter(crop, "AlfaHerb");
8884  alfaFI = crop_parameter(crop, "AlfaFi");
8885  unit_loss_herb = alfaH/100; //yield loss per unit of herb application, = max yield loss/optBI = betaH/optBI = alfa. (and /100).
8886  unit_loss_fi = alfaFI/100; //yield loss per unit of fung-insecticide application
8887  }
8888 
8889  //draw random numbers to modify the pest related yield loss
8890  //method from: http://stackoverflow.com/questions/9651024/using-stdtr1normal-distribution-in-qt
8891  std::random_device rd;
8892  std::normal_distribution<double> dist(1, 0.2);
8893  std::mt19937 engine(rd());
8894  double r_number_1 = dist(engine);
8895  double r_number_2 = dist(engine);
8896 
8897 
8898  //determine the pest related yield loss
8899  no_missed_herb_app = crop_data.missed_herb_app;
8900  no_missed_fi_app = crop_data.missed_fi_app;
8901  yield_loss_pest = no_missed_herb_app * unit_loss_herb * r_number_1 + no_missed_fi_app * unit_loss_fi * r_number_2; //total yield loss due to missed pesticide applications
8902 
8903  //determine the yield
8904  biomass = crop_data.biomass_at_harvest;
8905  yield_factor = m_OurManager->pm_data->Get_biomass_factor(tov_Undefined * m_soilType + crop); //crop is tov - integer
8906 
8907  fert_applied = findCropByName_almass (crop)->m_n;
8908  fert_opt = findCropByName_almass (crop)->m_optimalN;
8909  fert_trade = findCropByName_almass (crop)->m_nt;
8910 
8911  int index = tov_Undefined * m_soilType + crop;
8912  beta1=m_OurManager->pm_data->Get_beta1(index);
8913  beta2=m_OurManager->pm_data->Get_beta2(index);
8914 
8915  double dd=m_OurManager->GetDD();
8916 
8917  yield_ha = (biomass==-1)? dd : biomass; //if biomass=-1 this crop is not harvested - use daydegress to estimate the yield
8918  yield_ha *= yield_factor; //multiply by the factor to convert biomass to yield - works both for harvested and not harvested crops.
8919  if(fert_opt!=0){
8920  yield_ha -= (1 - fert_applied/fert_opt) * (beta1 * fert_opt + beta2 * fert_opt*fert_opt); //subtract the amount which depends on the applied ferilizer - if the applied=optimal, then amount subtracted=0. The expression in brackets - with betas - corresponds to the max yield loss-when fert=0.
8921  }
8922  yield_ha *= (1-yield_loss_pest); //finally account for the yield loss due to pests
8923 
8924  //get other numbers for economic calculations
8925  sellingPrice = m_OurManager->pm_data->Get_sellingPrice(tov_Undefined*tos_Foobar*m_farmType + tov_Undefined*m_soilType + crop); //always tov_Undefined because this funtion is called ONLY in almass crop mode!
8926  priceFi = crop_parameter(crop, "PriceFi");
8927  priceHerb = crop_parameter(crop, "PriceHerb");
8928  priceG = crop_parameter(crop, "PriceG");
8929  priceH = crop_parameter(crop, "PriceH");
8930  priceW = crop_parameter(crop, "PriceW");
8931  priceLM = crop_parameter(crop, "PriceLM");
8932  subsidy =crop_parameter(crop, "Subsidy");
8933 
8934  double grooming = findCropByName_almass (crop)->m_grooming;
8935  double hoeing = findCropByName_almass (crop)->m_hoeing;
8936  double weeding = findCropByName_almass (crop)->m_weeding;
8937 
8938  no_herb_app = crop_data.no_herb_app;
8939  no_fi_app = crop_data.no_fi_app;
8940 
8941  //special case for potatoes and fodder beet
8942  if(crop==tov_Potatoes || crop==tov_PotatoesIndustry){
8943  no_herb_app = 1.41; //need to be consistent with numbers in the fix BI function!
8944  no_fi_app = 9.28;
8945  }
8946  if(crop==tov_FodderBeet){
8947  no_herb_app = 2.28; //need to be consistent with numbers in the fix BI function!
8948  }
8949 
8950  //saving the amount of pesticides and fertilizer
8951  if(g_date->GetYearNumber()>9){ //do it for the first time in year 10 ->only then we account for new dec.- modes
8952  for(int c=0; c<m_OurManager->pm_data->Get_noCrops(); c++){
8953  if(m_OurManager->Get_crops_summary_BIs_tov(c) == crop){
8954  m_OurManager->Set_crops_summary_BIs_herb(c, no_herb_app * area);
8955  m_OurManager->Set_crops_summary_BIs_fi(c, no_fi_app * area);
8956  m_OurManager->Set_crops_summary_BIs(c, (no_fi_app+no_herb_app) * area);
8957  m_OurManager->Set_crops_fertilizer(c, fert_applied * area);
8958  m_OurManager->Set_crops_fertilizer_trade(c, fert_trade * area);
8959  break;
8960  }
8961  }
8962  }
8963 
8964 
8965  //GET THE ACTUAL FIGURES:
8966  //1. determine the actual income from this crop: use selling price also for fodder crops! they do not add to income, just diminish the costs of fodder...hm
8967  income_ha = yield_ha * sellingPrice + subsidy;
8968  income = income_ha * area; //total income from this crop
8969 
8970  //2. account for the costs incurred for this crop
8971  costs_ha = no_herb_app*priceHerb + no_fi_app*priceFi + grooming*priceG + hoeing*priceH + weeding*priceW + fert_trade*priceNt+ priceLM;
8972  costs = costs_ha * area;
8973 
8974  //3. determine the actual profit
8975  profit_ha = income_ha - costs_ha;
8976  profit = profit_ha * area;
8977 
8978  //4. determine what part of the expected yield you actually got from this crop - but do this by ha! here there are only crops that were grown this year - because we go through the list of fields
8979  yield_exp = findCropByName_almass (crop)->m_resp;
8980  if(yield_exp!=0){
8981  yield_ratio = yield_ha/yield_exp; // must be min. 0, can be > than 1.
8982  }
8983  else{
8984  m_exp_aggregated_yield -=1; //this crop wasn't expected to yield anything, so exclude it from the sum of expected yields
8985  }
8986 
8987  //add actual figures for this crop to the totals at a farm this year
8988  m_actual_income += income;
8989  m_actual_costs += costs;
8990  m_actual_profit += profit;
8991  m_actual_aggregated_yield += yield_ratio;
8992 
8993 
8994  //add expected figures for this crop to the totals at a farm this year
8995  //get the expected values! use the actual area - otherwise a comparison doesn't make sense!
8996 
8997  //to determine the expected income use last year's price
8998  double resp = findCropByName_almass (crop)->m_resp;
8999  double totalLoss = findCropByName_almass (crop)->m_totalLoss;
9000  double sellingPrice_lastyr = m_OurManager->pm_data->Get_sellingPrice_lastyr(tov_Undefined*tos_Foobar*m_farmType + tov_Undefined*m_soilType + crop); //always tov_Undefined because this funtion is called ONLY in almass crop mode!
9001 
9003  bool fodder = m_OurManager->pm_data->Get_fodder(index1);
9004  if (fodder) income_exp = subsidy;
9005  else income_exp = (sellingPrice_lastyr*resp*(1-totalLoss/100)+subsidy)*area;
9006 
9007  costs_exp = findCropByName_almass (crop)->m_costs_ha *area;
9008  profit_exp = income_exp - costs_exp;
9009 
9010  m_exp_income += income_exp; //add income expected from this crop to the total expected income
9011  m_exp_costs += costs_exp;
9012  m_exp_profit += profit_exp;
9013 
9014  //clean data in this field's struct: remove the data that you just accounted for
9015  pf->Clean_CropDataStorage(cropDataStorage_index);
9016  }
9017  else{//there was no accounting done, print the crop and year in which this happened
9018  #ifdef _DEBUG
9019  g_msg->Warn("OptimisingFarm::ActualProfit(): There was no accounting for tov: ", crop);
9020  //g_msg->Warn("Farm Number: ",GetFarmNumber());
9021  g_msg->Warn("Year Number: ",g_date->GetYearNumber());
9022  #endif
9023  }
9024 
9025  //send the info on this field's crop for the landscape total crop areas accounting
9026  //first find the right index in m_cropTotals:
9027  int index_for_croptotals=0;
9029  for(int k = 0; k<size; k++){
9031  if(crop_type == crop){
9032  index_for_croptotals = k;
9033  break;
9034  }
9035  }
9036  //then add the area of this field to the right element of m_cropTotals; change the units from sq meters to ha.
9037  m_OurManager->Add_to_cropTotals(index_for_croptotals, m_fields[i]->GetArea() * 0.0001); //yearly totals
9038  if(g_date->GetYearNumber()>20){ //do it for the first time in year 10 ->only then we account for new dec.- modes//for wildlife runs - only since year 20 when emaize appears, but here in year 20 we only account for year 19...that's why it has to be '>20'
9039  m_OurManager->Set_cropTotals_sum(index_for_croptotals, m_fields[i]->GetArea() * 0.0001);
9040  if(m_farmType == toof_Plant){
9041  m_OurManager->Set_cropTotals_plant_sum(index_for_croptotals, m_fields[i]->GetArea() * 0.0001);
9042  }
9043  else if(m_farmType == toof_Pig){
9044  m_OurManager->Set_cropTotals_pig_sum(index_for_croptotals, m_fields[i]->GetArea() * 0.0001);
9045  }
9046  else if(m_farmType == toof_Cattle){
9047  m_OurManager->Set_cropTotals_cattle_sum(index_for_croptotals, m_fields[i]->GetArea() * 0.0001);
9048  }
9049  else if(m_farmType == toof_Other){
9050  m_OurManager->Set_cropTotals_other_sum(index_for_croptotals, m_fields[i]->GetArea() * 0.0001);
9051  }
9052  }
9053 
9054  //then add also to farm type specific crop totals
9055 
9056 
9057 
9058  }//for: going through m_fields
9059 
9060 
9061  //print the expected and actual values
9062  ofstream ofile ("Economic_figures.txt", ios::app);
9063  ofile << "farm_no: " << m_almass_no << '\t' << "year_no " << g_date->GetYearNumber() << endl;
9064  ofile << "Expected: " << '\t' <<"Income " << m_exp_income << "\tCosts "<< m_exp_costs << "\tProfit " << m_exp_profit<< "\tAgg.yield " << m_exp_aggregated_yield;
9065  ofile << endl;
9066  ofile << "Actual: " << '\t' << "Income " << m_actual_income << "\tCosts "<< m_actual_costs << "\tProfit " << m_actual_profit<< "\tAgg.yield " << m_actual_aggregated_yield;
9067  ofile << endl <<endl;
9068  ofile.close();
9069 
9070 
9071  //save the economic figures for this year (or rather past - we account for things happen in the year before the current March 1st, xxxx)
9074  m_previous_costs.push_back(m_actual_costs);
9076 
9077 
9078  double min_need_satisfaction1 = cfg_Min_need_satisfaction1.value();
9079  double min_need_satisfaction2 = cfg_Min_need_satisfaction2.value();
9080  if(cfg_OnlyDeliberation.value()){ //then everybody deliberates (and: min cert is set to 0 when config var OnlyDeliberation is set to true)
9081  min_need_satisfaction1 = 100;
9082  min_need_satisfaction2 = 100;
9083  }
9084 
9086  if(m_exp_profit>0){
9087  if(m_actual_profit >= min_need_satisfaction1*m_exp_profit){
9089  }
9090  else{
9092  }
9093  }
9094  else if(m_exp_profit<0){
9095  if(m_actual_profit >= (2 - min_need_satisfaction1) * m_exp_profit){ //e.g. EP=-1000, AP=-1100 -> ok for MNS<=0.9.
9097  }
9098  else{
9100  }
9101  }
9102  else{ //exp profit = 0
9103  m_need_satisfaction_level = (m_actual_profit >0)? 1 : 0; //need to deal with this case - not very likely to happen
9104  }
9105  }
9106  else if (m_main_goal == tofg_yield){
9107  m_need_satisfaction_level = (m_actual_aggregated_yield >= m_exp_aggregated_yield * min_need_satisfaction2)? 1 : 0 ;
9108  }
9109 
9110  m_previous_satisfaction_levels.push_back(m_need_satisfaction_level); //add it to the list of satisfaction levels from last 5 years
9111  if(m_previous_satisfaction_levels.size()>5){ // it's been more than 5 years since the first accoutning, so...
9112  m_previous_satisfaction_levels.erase(m_previous_satisfaction_levels.begin()); //remove the first element: satisfaction level 6 years ago
9113  }
9114 
9115  //for energy maize impact on wildlife - January 2014
9116  if(cfg_MaizeEnergy.value()){
9117  double threshold = cfg_AnimalsThreshold.value();
9118  double sum = 0;
9119  for(int i=0; i<m_animals_numbers.size(); i++){
9120  sum += m_animals_numbers[i];
9121  }
9122  double avrg_animals_no = 0;
9123  if(m_animals_numbers.size()>0){
9124  avrg_animals_no = sum/m_animals_numbers.size();
9125  }
9126 
9127  if(emaize && animals_no < threshold * avrg_animals_no && m_animals_numbers.size()>2){ //three conditions: 1. you actually have grown energy maize
9128  // 2. the animal numbers have decreased below the acceptable level 3. you have data on animal numbers from min. 3 years
9129  //then set the rotation max. for energy maize to zero and force deliberation to stop growing energy maize
9130  CropOptimised *em = findCropByName_almass ("Maize");
9131  em->m_rotationMax = 0;
9132  force_deliberation = true;
9133  }
9134  m_animals_numbers.push_back(animals_no);
9135  if(m_animals_numbers.size() > 3){ //have data for more than 3 years now
9136  m_animals_numbers.erase(m_animals_numbers.begin()); //remove the oldest data - first element
9137  }
9138 
9139  //force optimisation when energy maize price changed by more than a given %
9142  if(abs(EMPrice_current - EMPrice_lastyr) > EMPrice_lastyr * cfg_PriceChangeThreshold.value()){
9143  force_deliberation = true;
9144  }
9145  }
9146  //
9147 
9148  //and restart the actual and expected values - for next year
9149  m_exp_income = 0;
9150  m_exp_costs = 0;
9151  m_exp_profit = 0;
9152  //exp agg yield is determined at the begininng of this function;
9153  m_actual_income = 0;
9154  m_actual_costs = 0;
9155  m_actual_profit = 0;
9157 
9158 }
9159 
9160 
9162 
9178  double field_size_pct = a_field->GetArea()/GetArea() * 100; //convert field size to pct of total arable farm area (a_rotational_crops will contain values of areas in %)
9179  TTypesOfVegetation current_crop =a_field->GetVegType();
9180  TTypesOfVegetation crop_to_grow = tov_Undefined;
9181 
9182  if(current_crop==tov_PermanentGrassGrazed || current_crop==tov_PermanentGrassTussocky || current_crop==tov_PermanentSetaside ||
9183  current_crop==tov_PermanentGrassLowYield || current_crop==tov_YoungForest || current_crop==tov_OrchardCrop) {
9184 
9185  crop_to_grow = current_crop; //and do not switch rot index - has to stay as it is to mark the field as perm
9186  }
9187  else{
9188 
9189  if((int)m_rotational_crops_copy.size()==0 ){ // in the 1st year it is empty since the choose dec. mode was not called yet!
9190  m_rotational_crops_copy = m_rotational_crops; //restart the copy - it is empty and we still need crops
9191  //debug
9192  if((int)m_rotational_crops_copy.size()==0){ //should not happen!
9193  char index[ 20 ];
9194  sprintf( index, "%d", m_almass_no);
9195  g_msg->Warn( WARN_BUG, "OptimisingFarm::Match_crop_to_field(): rot crops vector is empty! Farm no: ", index );
9196  exit( 1 );
9197  }
9198  }
9199 
9200  if (current_crop==tov_SeedGrass1){
9201  bool sg2=false;
9202  for(int i=0; i< (int)m_rotational_crops_copy.size(); i++){
9204  if(crop==tov_SeedGrass2) sg2 = true;
9205  }
9206  if (!sg2){ //there is no seedgrass2 in the list of crops. Otherwise just go to the normal procedure of choosing crop
9207  crop_to_grow = tov_SeedGrass2;
9208  }
9209  }
9210  if (current_crop==tov_CloverGrassGrazed1){
9211  bool cgg2=false;
9212  for(int i=0; i< (int)m_rotational_crops_copy.size(); i++){
9214  if(crop==tov_CloverGrassGrazed2) cgg2 = true;
9215  }
9216  if (!cgg2){ //there is no tov_CloverGrassGrazed2 in the list of crops. Otherwise just go to the normal procedure of choosing crop
9217  crop_to_grow = tov_CloverGrassGrazed2;
9218  }
9219  }
9220 
9221  if (current_crop!=tov_SpringBarley){
9222  bool other_crop_than_cgg = false;
9223  for(int i=0; i< (int)m_rotational_crops_copy.size(); i++){
9226  other_crop_than_cgg = true;
9227  break;
9228  }
9229  }
9230  if (!other_crop_than_cgg){ //there is no other tov than CGG1 or CGG2 in the list of crops. So need to grow smth which will fit - SB.
9231  crop_to_grow = tov_SpringBarley;
9232  }
9233  }
9234 
9235  bool Sb_inserted=false;
9236  if(crop_to_grow==tov_Undefined){ //if not, it is already CGG2 or SG
9237 
9238  //create the vector with numbers
9239  vector<int>probability_line;
9240  probability_line.push_back(0); //add the first element
9241  for(int i=0; i< (int)m_rotational_crops_copy.size(); i++){
9242  if(m_rotational_crops_copy[i].Number<0.5) m_rotational_crops_copy[i].Number += 0.5; //just in case - to avoid having crops that disappeear
9243  int area = (int)(m_rotational_crops_copy[i].Number + 0.5); //change to integer
9244  probability_line.push_back(area + (int)probability_line[probability_line.size() - 1]); //add a number equal to the sum of the current last element and this crop's area
9245  }
9246 
9247  //pick an index of a crop
9248  //see: http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution
9249  std::random_device rd;
9250  std::mt19937 gen(rd());
9251  int last_number = probability_line[(int)probability_line.size() - 1]; //the last number
9252  distribution_type2 dis(0, last_number - 1);
9253  double crop_index = 0;
9254 
9255  double diff = 0;
9256  int index_j = 0;
9257  bool crop_found = false;
9258  for(int c = 0; !crop_found; c++){
9259  crop_index = dis(gen); //int from a range 0 - sum of crop areas in percent - only crops that haven't been grown yet - on their 'full' i.e. planned area
9260  //which crop is it?
9261  for(int j=0; j < (int)probability_line.size(); j++){
9262  if(j==(int)probability_line.size()-1) { //unless j=0 smth's wrong: we didnt find this index
9263  if(j==0){ //there are no crops left - prob. line contains just one element - 0.why?
9264  char index[ 20 ];
9265  sprintf( index, "%d", (int) crop_index);
9266  g_msg->Warn( WARN_BUG, "OptimisingFarm::Match_crop_to_field(): no crops left, index drawn is ", index );
9267  exit( 1 );
9268  }
9269  else{
9270  char index[ 20 ];
9271  sprintf( index, "%d", (int) crop_index);
9272  g_msg->Warn( WARN_BUG, "OptimisingFarm::Match_crop_to_field(): index not found in the prob. line", index );
9273  exit( 1 );
9274  }
9275  }
9276  if(crop_index >= probability_line[j] && crop_index < probability_line[j+1]) {
9277  if(j >= (int)m_rotational_crops_copy.size()) { //problem
9278  char index[ 20 ];
9279  sprintf( index, "%d", j);
9280  g_msg->Warn( WARN_BUG, "OptimisingFarm::Match_crop_to_field(): index out of a range", index );
9281  exit( 1 );
9282  }
9283  crop_to_grow = m_rotational_crops_copy[j].Tov;
9284  index_j = j;
9285  break; //got the crop type
9286  }
9287 
9288  }
9289  //make a check
9290  int lookup_before = m_OurManager->Get_lookup_table(current_crop * (tov_Undefined+1) + crop_to_grow); //check with a preceeding crop; tov_undef+1 - because this tov_undef is included in the lookup table
9291  if(lookup_before==-1){ //issue a warning: wrong index...
9292  char index[ 20 ];
9293  sprintf( index, "%d", current_crop);
9294  g_msg->Warn( WARN_BUG, "OptimisingFarm::Match_crop_to_field(): Error (possibly caused by a new tov type that is not incuded in the crops_lookup table) in reading the lookup table; tov type that should not appear: ", index );
9295  exit( 1 );
9296  }
9297  if(lookup_before==1){ //if so, make another check - but not if we tried already 20 times - then release this constraint
9298 
9299  bool WRape_grown = false;
9300  if(cfg_Areas_Based_on_Distribution.value()){ //then another check: spring rape cannot be grown if the farm grows winter rape within 1000 m (www.landbrugsinfo.dk)
9301  if(crop_to_grow == tov_SpringRape){
9302  for(int w=0; w<(int)m_fields.size(); w++){
9303  if(m_fields[w]->GetVegType() == tov_WinterRape) WRape_grown = true;
9304  }
9305  }
9306  }
9307 
9308  if(c<20){
9309  diff = field_size_pct - m_rotational_crops_copy[index_j].Number;
9310  if(diff <= 20 && !WRape_grown){ //diff in size smaller than 20 percent points - ok. Plus there is no winter rape around in case the chosen crop is SRape
9311  crop_found=true;
9312  break; //break the for - this crop is OK
9313  }
9314  }
9315  else{
9316  diff = field_size_pct - m_rotational_crops_copy[index_j].Number;
9317  if(!WRape_grown){
9318  crop_found=true; //this crop must be accepted
9319  break;
9320  }
9321  }
9322  }
9323  if(c==1000 && !crop_found){ //seems there's no crop that can follow the current one, so restart the crops instead and continue the search!
9324  m_rotational_crops_copy = m_rotational_crops; //restart - that's not enough - need a new prob line
9325  probability_line.clear();
9326  probability_line.push_back(0); //add the first element
9327  for(int i=0; i< (int)m_rotational_crops_copy.size(); i++){
9328  if(m_rotational_crops_copy[i].Number<0.5) m_rotational_crops_copy[i].Number += 0.5; //necessary to avoid having crop disappeeared
9329  int area = (int)(m_rotational_crops_copy[i].Number + 0.5); //change to integer
9330  probability_line.push_back(area + (int)probability_line[probability_line.size() - 1]); //add a number equal to the sum of the current last element and this crop's area
9331  }
9332 
9333  last_number = probability_line[(int)probability_line.size() - 1]; //the last number
9334  distribution_type2 dis(0, last_number - 1);
9335  }
9336  if(c>1500){ //seems there's no crop that can follow the current one - issue a warning; but now do this only after restarting
9337  #ifdef _DEBUG
9338  char index[ 20 ];
9339  sprintf( index, "%d", current_crop);
9340  g_msg->Warn( WARN_BUG, "OptimisingFarm::Match_crop_to_field(): There is no crop that can follow the current crop. Sbarley will be grown. The current crop is: ", index );
9341  #endif
9342  crop_to_grow=tov_SpringBarley;
9343  Sb_inserted=true;
9344  break;
9345  //exit( 1 );
9346  }
9347  }
9348 
9349  //crop found, so update the vector of crops
9350  if(!Sb_inserted){
9351  if(diff < 0){ //crop area should be larger than this field's area
9352  m_rotational_crops_copy[index_j].Number -= field_size_pct;
9353  }
9354  else{
9355  if(m_rotational_crops_copy.size() <1){ //smth is wrong
9356  char index[ 20 ];
9357  sprintf( index, "%d", current_crop);
9358  g_msg->Warn( WARN_BUG, "OptimisingFarm::Match_crop_to_field(): m_rotational_crops_copy is empty, the crop chosen is: ", index );
9359  exit( 1 );
9360  }
9361  m_rotational_crops_copy.erase(m_rotational_crops_copy.begin() + index_j);
9362  }
9363  }
9364  }
9365 
9366  //switch the rotational index:
9367 
9368  //1. find the chosen crop in the m_rotation
9369  int position_in_mrotation=-1;
9370  int size=(int)m_rotation.size();
9371 
9372  for(int c=0; c< (int)m_rotation.size(); c++){
9373  if(m_rotation[c] == crop_to_grow){
9374  position_in_mrotation=c;
9375  break;
9376  }
9377  }
9378 
9379  if(position_in_mrotation==-1){
9380  char error_num[ 20 ];
9381  sprintf( error_num, "%d", crop_to_grow );
9382  g_msg->Warn( WARN_FILE, "OptimisingFarm::Match_crop_to_field(): ""Unknown vegetation type:", error_num );
9383  exit( 1 );
9384  }
9385  //2. switch the rot index to a crop just before the chosen one
9386  if(position_in_mrotation!=0){
9387  a_field->SetRotIndex(position_in_mrotation-1);
9388  }
9389  else{
9390  a_field->SetRotIndex(size-1);
9391  }
9392  }//current crop is a rotational crop
9393 }
9394 
9399 polylist* Farm::ListOpenFields( int a_openness )
9400 {
9401  polylist* p_list = new polylist;
9402  int nf = (int) m_fields.size();
9403  for ( int i = 0; i < nf; i++ )
9404  {
9405  if ( m_fields[ i ]->GetOpenness() >= a_openness )
9406  {
9407  p_list->push_back( m_fields[i]->GetPoly());
9408  }
9409  }
9410  return p_list;
9411 }
OptimisingFarm::assignFixed
void assignFixed()
Adds areas of fixed crops to the variable m_assigned. For each fixed crop it saves its area under var...
Definition: farm.cpp:6275
OptimisingFarm::findTotalArea
void findTotalArea()
Determines m_totalArea of a farm.
Definition: farm.cpp:5624
UserDefinedFarm
A farm that can have its rotation defined by the user at runtime.
Definition: farm.h:1267
tov_AgroChemIndustryCereal
Definition: tov_declaration.h:55
tocv_BIHerb
Definition: farm.h:404
UserDefinedFarm4::UserDefinedFarm4
UserDefinedFarm4(FarmManager *a_manager)
Definition: farm.cpp:2244
cfg_Yield_max_proportion
CfgFloat cfg_Yield_max_proportion("YIELD_MAX_PROPORTION", CFG_CUSTOM, 0)
A parameter setting the proportion of farmers of a type yield maximiser.
tof_UserDefinedFarm35
Definition: farm.h:272
UserDefinedFarm31::UserDefinedFarm31
UserDefinedFarm31(const char *fname, FarmManager *a_manager)
Definition: farm.cpp:2596
UserDefinedFarm3::UserDefinedFarm3
UserDefinedFarm3(FarmManager *a_manager)
Definition: farm.cpp:2236
VegElement::Set_CropDataStorage
void Set_CropDataStorage(int index, CropActualValues a_struct)
Definition: elements.h:662
FarmManager::InIllegalList
bool InIllegalList(int a_farm_ref, vector< int > *a_farmlist)
Checks a list to see if a farm matches the illegal list of references.
Definition: farm.cpp:3088
tov_OSpringBarleyClover
Definition: tov_declaration.h:46
NoPesticideBaseFarm::NoPesticideBaseFarm
NoPesticideBaseFarm(FarmManager *a_manager)
Definition: farm.cpp:2148
FarmManager::DistributeFarmerTypes
void DistributeFarmerTypes()
Randomly assigns farmer types to farms (OptimisingFarm) in proportions specified in an input file.
Definition: farm.cpp:4965
OptimisingFarm::determineAreas_ha
void determineAreas_ha(vector< CropOptimised * >crops)
Determines areas of crops in ha.
Definition: farm.cpp:7967
tov_SpringBarleyStrigling
Definition: tov_declaration.h:58
FarmManager::Set_crops_summary_BIs_herb
void Set_crops_summary_BIs_herb(int i, double BIherb)
Definition: farm.h:1854
tov_PLWinterWheatLate
Definition: tov_declaration.h:85
FarmManager::ReadLivestockData
void ReadLivestockData()
Reads the data on livestock parameters (do not vary with farm variables) and saves them in a vector D...
Definition: farm.cpp:4212
AgroChemIndustryCerealFarm3::AgroChemIndustryCerealFarm3
AgroChemIndustryCerealFarm3(FarmManager *a_manager)
Definition: farm.cpp:2130
OptimisingPigFarm::OptimisingPigFarm
OptimisingPigFarm(FarmManager *a_myfarmmanager, int a_No)
Definition: farm.cpp:5280
OptimisingFarm::Get_farmType
TTypesOfOptFarms Get_farmType(void)
Definition: farm.h:2034
tov_PLSpringWheat
Definition: tov_declaration.h:75
tov_NLSpringBarley
Definition: tov_declaration.h:93
AnimalFarm::correctFodderDemand
void correctFodderDemand(int a_foobar)
Determines how much fodder is produced from fixed crops and min. areas of variable crops.
Definition: farm.cpp:7488
toof_Pig
Definition: farm.h:282
FarmManager::ReadInitialCropAreas
void ReadInitialCropAreas()
Reads the data on farms' initial crop distributions and saves them in a vector DataForOptimisation::m...
Definition: farm.cpp:3571
Farm::AssignPermanentCrop
void AssignPermanentCrop(TTypesOfVegetation tov, int pct)
Used to assign a permanent crop to an otherwise rotational field polygon.
Definition: farm.cpp:2401
DataForOptimisation::Set_cropArea
void Set_cropArea(double a_area)
Definition: farm.h:604
tov_NLMaizeSpring
Definition: tov_declaration.h:102
tof_UserDefinedFarm19
Definition: farm.h:256
tov_Oats
Definition: tov_declaration.h:40
tov_OWinterBarley
Definition: tov_declaration.h:47
tof_UserDefinedFarm7
Definition: farm.h:244
CropActualValues
Struct for storing actual data on crop type, area of a field it is grown in, biomass at harvest,...
Definition: elements.h:555
OrganicPig
A farm that can have its rotation defined by the user at runtime.
Definition: farm.h:1148
tofg_yield
Definition: farm.h:437
toc_Oats
Definition: farm.h:325
LE::SetOwner
void SetOwner(Farm *a_owner, int a_owner_num, int a_owner_index)
Definition: elements.h:219
DataForOptimisation::Set_noCrops
void Set_noCrops(int no)
Definition: farm.h:668
FarmManager::Add_to_cropTotals
void Add_to_cropTotals(int i, double value)
Definition: farm.h:1838
OptimisingFarm::GetFarmCentroidX
int GetFarmCentroidX()
Definition: farm.h:2055
toc_PeasSil
Definition: farm.h:343
Farm::Centroids
void Centroids()
Finds farm's centroids - x and y.
Definition: farm.cpp:5334
tov_NLPotatoes
Definition: tov_declaration.h:92
OptimisingFarm::m_soilSubType
int m_soilSubType
Farm's soil subtype. Defined only for cattle farms on sandy soil (0-bad, 1-good, 2-undefined).
Definition: farm.h:2218
Livestock::m_number
int m_number
Number of animals of a given type at a farm.
Definition: farm.h:1624
CfgStr::value
const char * value(void)
Definition: configurator.h:152
AnimalFarm::checkWinterRotation1
virtual void checkWinterRotation1()
Animal farm version of the OptimisingFarm::checkWinterRotation1() function (accounts for fodder chang...
Definition: farm.cpp:6636
OptimisingFarm::m_totalFUdemandBefore
double m_totalFUdemandBefore
Farm's total demand for fodder. [fodder units]
Definition: farm.h:2234
UserDefinedFarm11
A farm that can have its rotation defined by the user at runtime.
Definition: farm.h:1368
FarmManager::ReadCropsData_perSoilType_almass
void ReadCropsData_perSoilType_almass()
Reads the data on crops' parameters that vary with a soil type (alfa, beta1, beta2,...
Definition: farm.cpp:3790
DataForOptimisation::FarmData::md_farmSize
TTypesOfFarmSize md_farmSize
Definition: farm.h:680
PesticideTrialControl::PesticideTrialControl
PesticideTrialControl(FarmManager *a_manager)
Definition: farm.cpp:2059
tof_UserDefinedFarm33
Definition: farm.h:270
top_AlfaG
Definition: farm.h:383
UserDefinedFarm30::UserDefinedFarm30
UserDefinedFarm30(const char *fname, FarmManager *a_manager)
Definition: farm.cpp:2591
tof_UserDefinedFarm23
Definition: farm.h:260
tof_UserDefinedFarm34
Definition: farm.h:271
OptimisingFarm::m_totalArea_original
double m_totalArea_original
Total area of a farm as in bedriftsmodel, i.e. original farm optimization model. [ha].
Definition: farm.h:2226
cfg_Neighbor_dist
CfgFloat cfg_Neighbor_dist("NEIGHBOR_DIST", CFG_CUSTOM, 1.5)
A parameter setting the maximum distance from a farm to another farm that can be considred a neighbou...
Farm::GetNoOpenFields
int GetNoOpenFields(int a_openness)
Returns the number of the fields above an openness of a_openness.
Definition: farm.cpp:1359
tof_UserDefinedFarm32
Definition: farm.h:269
FarmManager::FindNeighbours
void FindNeighbours()
Finds all OptimisingFarms' neighbours and saves them in the farm's OptimisingFarm::m_neighbours vecto...
Definition: farm.cpp:4657
CropOptimised::m_BI
double m_BI
Summary value of BI for herbicides and fung- and insecticides [BI/ha].
Definition: farm.h:1671
UserDefinedFarm13
A farm that can have its rotation defined by the user at runtime.
Definition: farm.h:1386
top_Foobar
Definition: farm.h:389
tolp_Nusable
Definition: farm.h:394
ConvMarginalJord::ConvMarginalJord
ConvMarginalJord(FarmManager *a_manager)
Definition: farm.cpp:2083
OptimisingFarm::m_totalHoeing
double m_totalHoeing
Total hoeing planned at a farm.
Definition: farm.h:2256
TTypesOfCropVariables
TTypesOfCropVariables
Definition: farm.h:399
cfg_Price_Triticale
CfgFloat cfg_Price_Triticale("PRICE_TRITICALE", CFG_CUSTOM, 80)
toc_Other
Definition: farm.h:366
FarmManager::CheckOpenness
bool CheckOpenness(int a_openness, int a_ref)
Check if a farm has at least one field with openness above a_openness.
Definition: farm.cpp:3399
OrganicPlant::OrganicPlant
OrganicPlant(FarmManager *a_manager)
Definition: farm.cpp:2052
tov_OPermanentGrassGrazed
Definition: tov_declaration.h:44
DataForOptimisation::m_Nnorm
vector< double > m_Nnorm
Maximum amount of fertilizer (N) that can be applied for a given crop [kg N/ha]. Soil specific.
Definition: farm.h:734
LE::GetArea
double GetArea(void)
Definition: elements.h:196
OptimisingFarm::m_totalArea
double m_totalArea
Total area of a farm. A sum of initial crop areas (if in bedriftsmodel, i.e. original farm optimizati...
Definition: farm.h:2224
tof_PTrialTreatment
Definition: farm.h:230
OptimisingFarm::m_actual_costs
double m_actual_costs
Actual costs at a farm in a given year.
Definition: farm.h:2126
tof_UserDefinedFarm18
Definition: farm.h:255
DataForOptimisation
Class for storing data for optimisation.
Definition: farm.h:589
top_BetaHerb
Definition: farm.h:380
Farm::LeSwitch
bool LeSwitch(FarmEvent *ev)
Call do function for any crop with an outstanding event. Signal if the crop has terminated.
Definition: farm.cpp:386
OptimisingFarm::m_grownVariableCrops
vector< CropOptimised * > m_grownVariableCrops
Vector of pointers to variable crops that are grown on area larger than areaMin (after determineAreas...
Definition: farm.h:2192
UserDefinedFarm25
A farm that can have its rotation defined by the user at runtime.
Definition: farm.h:1501
Farm::GetFirstCropIndex
virtual int GetFirstCropIndex(TTypesOfLandscapeElement a_type)
Gets the first crop for the farm.
Definition: farm.cpp:1385
ConventionalPig::ConventionalPig
ConventionalPig(FarmManager *a_manager)
Definition: farm.cpp:2000
tocv_Hoeing
Definition: farm.h:408
OptimisingFarm::Translate_crops_to_almass
void Translate_crops_to_almass()
Translates crops from Bedriftsmodel (original farm optimization model) to Almass crops....
Definition: farm.cpp:8075
DataForOptimisation::Get_sellingPrice_lastyr
double Get_sellingPrice_lastyr(int i)
Definition: farm.h:650
FarmManager::Set_crops_summary_BIs_fi
void Set_crops_summary_BIs_fi(int i, double BIfi)
Definition: farm.h:1855
CropActualValues::taken
bool taken
Definition: elements.h:556
FarmManager::totalOptFarmsArea_cattle
double totalOptFarmsArea_cattle
Definition: farm.h:1933
top_AlfaFi
Definition: farm.h:381
cfg_Env_fert_multiplier
CfgFloat cfg_Env_fert_multiplier("ENV_FERT_MULTIPLIER", CFG_CUSTOM, 0.8)
A parameter of the environmentalist farmer type: reduces environmentalist's use of fertiliser....
OptimisingFarm::Get_soilType
TTypesOfSoils Get_soilType(void)
Definition: farm.h:2035
CropOptimised::m_weeding
double m_weeding
Value of mechanical weed control for a crop - manual weeding [DKK/ha].
Definition: farm.h:1677
NonAnimalFarm::NonAnimalFarm
NonAnimalFarm(FarmManager *a_myfarmmanager, int a_No)
Definition: farm.cpp:5276
OptimisingFarm::findGrossMargin
void findGrossMargin(CropOptimised *a_crop, int a_foobar, double benefit)
Determines the gross margin (CropOptimised::m_GM) for a given crop at a farm.
Definition: farm.cpp:6225
DataForOptimisation::m_sellingPrice
vector< double > m_sellingPrice
Selling price of a crop [DKK/hkg]. Farm type specific and soil type specific.
Definition: farm.h:748
toc_OOilseed
Definition: farm.h:333
tov_PLSpringBarleySpr
Definition: tov_declaration.h:84
FarmEvent
A struct to hold the information required to trigger a farm event.
Definition: farm.h:463
UserDefinedFarm19::UserDefinedFarm19
UserDefinedFarm19(const char *fname, FarmManager *a_manager)
Definition: farm.cpp:2536
DataForOptimisation::Set_fixed
void Set_fixed(string a_value, int i)
Definition: farm.h:634
DataForOptimisation::Set_cropTypes_almass_str
void Set_cropTypes_almass_str(string crop_type)
Definition: farm.h:665
UserDefinedFarm3
A farm that can have its rotation defined by the user at runtime.
Definition: farm.h:1296
FarmManager::totalOptFarmsArea_other
double totalOptFarmsArea_other
Definition: farm.h:1934
tov_OOats
Definition: tov_declaration.h:44
Farm::DoIt
bool DoIt(double a_probability)
Return chance out of 0 to 100.
Definition: farm.cpp:800
cfg_Sensitivity_analysis
CfgBool cfg_Sensitivity_analysis("SENSITIVITY_ANALYSIS", CFG_CUSTOM, false)
DataForOptimisation::Get_sellingPrice
double Get_sellingPrice(int i)
Definition: farm.h:648
Calendar::GetYearNumber
int GetYearNumber(void)
Definition: calendar.h:68
FarmManager::ChooseDecisionMode_for_farms
void ChooseDecisionMode_for_farms()
Calls OptimisingFarm::ChooseDecisionMode for all optimising farms.
Definition: farm.cpp:3444
VegElement::Set_taken
void Set_taken(bool a_taken, int index)
Definition: elements.h:637
toa_Duck
Definition: farm.h:317
polylist
vector< unsigned > polylist
Definition: farm.h:207
OptimisingFarm::GetFarmCentroidY
int GetFarmCentroidY()
Definition: farm.h:2056
FarmManager::CreateFarms
void CreateFarms(const char *a_farmfile)
Definition: farm.cpp:2772
DataForOptimisation::m_sellingPrice_lastyr
vector< double > m_sellingPrice_lastyr
Selling price of a crop in a previous year [DKK/hkg]. Farm type specific and soil type specific.
Definition: farm.h:750
OptimisingPigFarm
Subclass of the AnimalFarm.
Definition: farm.h:2433
OptimisingCattleFarm::OptimisingCattleFarm
OptimisingCattleFarm(FarmManager *a_myfarmmanager, int a_No)
Definition: farm.cpp:5284
Farm::GetFirstDate
int GetFirstDate(TTypesOfVegetation a_tov)
Gets the start date for a crop type.
Definition: farm.cpp:1582
tof_OrganicPlant
Definition: farm.h:228
TTypesOfSoils
TTypesOfSoils
Definition: farm.h:286
cfg_Env_pest_multiplier
CfgFloat cfg_Env_pest_multiplier("ENV_PEST_MULTIPLIER", CFG_CUSTOM, 1.25)
A parameter of the environmentalist farmer type: increases the chance that environmentalist does not ...
CompPcts
bool CompPcts(tpct i, tpct j)
Used for sorting a farmers field size vector.
Definition: farm.cpp:294
OptimisingFarm::m_almass_no
int m_almass_no
Farm's almass number.
Definition: farm.h:2220
DataForOptimisation::m_alfa
vector< double > m_alfa
Crop parameter for response (growth) function (resp = alfa + beta1*N + beta2*N^2; defines relationshi...
Definition: farm.h:728
UserDefinedFarm29::UserDefinedFarm29
UserDefinedFarm29(const char *fname, FarmManager *a_manager)
Definition: farm.cpp:2586
Farm::m_fields
vector< LE * > m_fields
Definition: farm.h:937
tov_PLMaizeSilage
Definition: tov_declaration.h:78
tov_OTriticale
Definition: tov_declaration.h:47
UserDefinedFarm5::UserDefinedFarm5
UserDefinedFarm5(FarmManager *a_manager)
Definition: farm.cpp:2252
tos_Other
Definition: farm.h:288
FarmManager::ReadCropsData_perFarm_and_Soil_and_Size_almass
void ReadCropsData_perFarm_and_Soil_and_Size_almass()
Reads the data on crops' parameters that vary with a farm type, soil type and farm size (rotationMax,...
Definition: farm.cpp:4117
tocv_Income
Definition: farm.h:412
OptimisingFarm::m_totalBIFi
double m_totalBIFi
Total amount of fung- and insecticides which is planned to be applied at a farm. Expressed as a Treat...
Definition: farm.h:2250
cfg_Price_WBarley
CfgFloat cfg_Price_WBarley("PRICE_WBARLEY", CFG_CUSTOM, 93)
tov_MaizeStrigling
Definition: tov_declaration.h:58
DataForOptimisation::Get_livestockParameter
double Get_livestockParameter(int i)
Definition: farm.h:618
Farm::GetNextCropIndex
virtual int GetNextCropIndex(int a_rot_index)
Returns the next crop in the rotation.
Definition: farm.cpp:1427
DataForOptimisation::Get_fodder
bool Get_fodder(int i)
Definition: farm.h:643
g_letype
class LE_TypeClass * g_letype
Definition: elements.cpp:277
tof_OptimisingFarm
Definition: farm.h:273
AnimalFarm::increaseCrops
virtual void increaseCrops(vector< CropSort >cropsToIncrease, double &howMuchToIncrease)
Increases area of cropsToIncrease by howMuchToIncrease.
Definition: farm.cpp:7874
DataForOptimisation::Set_cropTypes_str
void Set_cropTypes_str(string crop_type)
Definition: farm.h:597
DataForOptimisation::Get_noCrops
int Get_noCrops()
Definition: farm.h:669
FarmManager::DumpFarmrefs
void DumpFarmrefs()
dumps the farmrefs file to a standard named file
Definition: farm.cpp:2997
DataForOptimisation::FarmData::md_almass_no
int md_almass_no
Definition: farm.h:677
toc_SugarBeet
Definition: farm.h:339
toc_Veg
Definition: farm.h:358
OptimisingFarm::m_totalProfit
double m_totalProfit
Planned total profit (= income - costs) at a farm. In case of animal farms costs of purchased fodder ...
Definition: farm.h:2264
FarmManager::m_cropTotals_pig_sum
vector< double > m_cropTotals_pig_sum
Stores the sums of crops areas on pig farms within one simulation at the landscape level.
Definition: farm.h:1945
tof_AgroChemIndustryCerealFarm2
Definition: farm.h:234
VegElement::Get_taken
bool Get_taken(int index)
Definition: elements.h:638
OptimisingFarm::CropSort
Struct used for sorting crops.
Definition: farm.h:2161
UserDefinedFarm30
A farm that can have its rotation defined by the user at runtime.
Definition: farm.h:1551
tov_OWinterWheatUndersown
Definition: tov_declaration.h:49
CropActualValues::missed_fi_app
int missed_fi_app
Definition: elements.h:564
FarmManager::GetFarmNoLookup
int GetFarmNoLookup(int a_ref)
Get a farm reference from the lookup table.
Definition: farm.h:1882
tov_Undefined
Definition: tov_declaration.h:114
tof_ConventionalPig
Definition: farm.h:224
tocv_Weeding
Definition: farm.h:409
toc_GrassEnv1
Definition: farm.h:349
CfgStr
String configurator entry class.
Definition: configurator.h:144
Farm::DoIt_prob
bool DoIt_prob(double a_probability)
Return chance out of 0 to 1.
Definition: farm.cpp:808
OptimisingFarm::m_totalCosts
double m_totalCosts
Planned total costs of growing crops at a farm. [DKK].
Definition: farm.h:2260
FarmManager::ReadCropsData_perFarmType
void ReadCropsData_perFarmType()
Reads the data on crops' parameters that vary with a farm type (fixed, fodder, FUKey) and saves them ...
Definition: farm.cpp:3881
OptimisingFarm::determineAreas
virtual void determineAreas(int a_foobar)
Determines areas of variable crops.
Definition: farm.cpp:6304
tpct
Used for storing farmers field size vectors.
Definition: farm.h:454
tof_UserDefinedFarm9
Definition: farm.h:246
UserDefinedFarm6::UserDefinedFarm6
UserDefinedFarm6(FarmManager *a_manager)
Definition: farm.cpp:2260
FarmManager::FindClosestFarmOpennessProbSmallIsBest
int FindClosestFarmOpennessProbSmallIsBest(HunterInfo a_hinfo, vector< int > *a_farmlist, int a_openness, vector< int > *a_farmsizelist)
Finds the closest farm to this co-ordinate with openness more than a value but uses a probability dis...
Definition: farm.cpp:3233
FarmManager::GetSpilledMaize
double GetSpilledMaize()
Returns the average amount of spilled maize in KJ/m2 this year.
Definition: farm.cpp:3064
FarmManager::RemoveField
void RemoveField(int a_OwnerIndex, LE *a_field)
Definition: farm.cpp:2747
toc_PotatoFood
Definition: farm.h:338
CropOptimised::m_cropType_almass
TTypesOfVegetation m_cropType_almass
Type/name of a crop (ALMaSS crops).
Definition: farm.h:1646
tof_UserDefinedFarm17
Definition: farm.h:254
tof_UserDefinedFarm27
Definition: farm.h:264
tov_FieldPeasStrigling
Definition: tov_declaration.h:56
tocv_Response
Definition: farm.h:411
toc_PerGrassLow
Definition: farm.h:347
DataForOptimisation::Get_cropTypes
TTypesOfCrops Get_cropTypes(int i)
Definition: farm.h:600
tov_WinterBarleyStrigling
Definition: tov_declaration.h:59
FarmManager::InitFarms
void InitFarms()
Calls OptimisingFarm::Init for all optimising farms.
Definition: farm.cpp:3014
tov_NLBeetSpring
Definition: tov_declaration.h:100
cfg_ClosestFarmProbParam1
CfgFloat cfg_ClosestFarmProbParam1("CLOSESTFARMPROBPARAMONE", CFG_CUSTOM, 0.005)
A fitting parameter for the probability of hunter acceptance of a farm wiht distance from home - slop...
AnimalFarm::determineFodderAreas
void determineFodderAreas(int a_foobar)
Determines areas of fodder crops and corrects areas of non-fodder crops.
Definition: farm.cpp:7619
tof_AgroChemIndustryCerealFarm3
Definition: farm.h:235
FarmManager::CropDistribution
void CropDistribution()
Calculates total crop areas (at the landscape level). Includes results of the initial farm otpimisati...
Definition: farm.cpp:4588
OptimisingFarm::checkRestrictions
virtual void checkRestrictions()
Checks if the restrictions are fulfilled and corrects crops' areas if necessary.
Definition: farm.cpp:6410
toc_GrassSeed
Definition: farm.h:336
tos_Clay
Definition: farm.h:289
CropOptimised::m_costs_ha
double m_costs_ha
Costs of growing 1 ha of a crop. Include costs of labour and machine (constant), pesticides (herbicid...
Definition: farm.h:1685
FarmManager::ReadCropsData_perFarmType_almass
void ReadCropsData_perFarmType_almass()
Reads the data on crops' parameters that vary with a farm type (fixed, fodder, FUKey) and saves them ...
Definition: farm.cpp:3937
UserDefinedFarm17
A farm that can have its rotation defined by the user at runtime.
Definition: farm.h:1422
AgroChemIndustryCerealFarm1::AgroChemIndustryCerealFarm1
AgroChemIndustryCerealFarm1(FarmManager *a_manager)
Definition: farm.cpp:2097
tov_PLFodderLucerne1
Definition: tov_declaration.h:81
OptimisingFarm::checkWinterRotation1
virtual void checkWinterRotation1()
Checks if the restriction on a winter rotation is fulfilled.
Definition: farm.h:2330
FarmManager::FindClosestFarmOpenness
int FindClosestFarmOpenness(HunterInfo a_hinfo, vector< int > *a_farmlist, int a_openness)
Finds the closest farm to this co-ordinate but uses a probability distribtution for acceptance.
Definition: farm.cpp:3155
FarmManager::AddToIllegalList
void AddToIllegalList(int a_farm_ref, vector< int > *a_farmlist)
Add to a list if a farm is not already among the illegal list of references.
Definition: farm.cpp:3099
OptimisingFarm::Spraying_fungins
virtual bool Spraying_fungins(TTypesOfVegetation a_tov_type)
Returns true if a farmer decided to treat a given crop with fung- and insecticides.
Definition: farm.cpp:5360
tov_WinterWheat
Definition: tov_declaration.h:55
DataForOptimisation::Set_cropParameter
void Set_cropParameter(double a_value, int i)
Definition: farm.h:621
toc_CloverGrz
Definition: farm.h:357
Crop::Crop
Crop()
Definition: farm.cpp:297
DataForOptimisation::Get_farmType
TTypesOfOptFarms Get_farmType(int a_almass_no)
Used by FarmManager::CreateFarms. Finds a matching almass number and returns farm's type.
Definition: farm.cpp:5086
FarmManager::ReadFarmsData
void ReadFarmsData()
Reads farm level parameters and saves them in a vector DataForOptimisation::m_farm_data.
Definition: farm.cpp:3484
toa_MHen
Definition: farm.h:314
DataForOptimisation::Get_winterMax
int Get_winterMax(int i)
Definition: farm.h:614
FarmManager::Set_crops_fertilizer_trade
void Set_crops_fertilizer_trade(int i, double fert_trade)
Definition: farm.h:1864
UserDefinedFarm12::UserDefinedFarm12
UserDefinedFarm12(FarmManager *a_manager)
Definition: farm.cpp:2306
DataForOptimisation::Set_livestockTypes
void Set_livestockTypes(TTypesOfAnimals livestock_type)
Definition: farm.h:595
OptimisingFarm::Match_crop_to_field
void Match_crop_to_field(LE *a_field)
Finds a crop to be grown on a given field next year.
Definition: farm.cpp:9161
tof_AgroChemIndustryCerealFarm1
Definition: farm.h:233
tov_OCloverGrassSilage1
Definition: tov_declaration.h:43
tolp_AUKey
Definition: farm.h:393
tov_PermanentGrassTussocky
Definition: tov_declaration.h:49
Farm::GetNextCropStartDate
int GetNextCropStartDate(LE *a_field, TTypesOfVegetation &a_curr_veg)
Returns the start date of the next crop in the rotation.
Definition: farm.cpp:864
UserDefinedFarm29
A farm that can have its rotation defined by the user at runtime.
Definition: farm.h:1541
FarmManager::ReadCropsData_perSoilType
void ReadCropsData_perSoilType()
Reads the data on crops' parameters that vary with a soil type (alfa, beta1, beta2,...
Definition: farm.cpp:3724
toc_Potato
Definition: farm.h:337
l_map_farmref_file
static CfgStr l_map_farmref_file("MAP_FARMREF_FILE", CFG_CUSTOM, "farmrefs.txt")
tov_PLWinterTriticale
Definition: tov_declaration.h:73
tocv_AreaHa
Definition: farm.h:401
top_BetaW
Definition: farm.h:388
toc_EnergyFor
Definition: farm.h:363
VegElement::Set_area_in_crop_data
void Set_area_in_crop_data(double a_area)
Definition: elements.h:641
OptimisingFarm::Get_crop
CropOptimised * Get_crop(int i)
Definition: farm.h:2040
tof_ConvMarginalJord
Definition: farm.h:232
OptimisingFarm::Get_Neighbour
OptimisingFarm * Get_Neighbour(int i)
Definition: farm.h:2050
ConventionalPlant
Inbuilt farm type.
Definition: farm.h:1122
tov_OCloverGrassGrazed2
Definition: tov_declaration.h:43
DataForOptimisation::Get_FUKey
double Get_FUKey(int i)
Definition: farm.h:645
tov_PLPotatoes
Definition: tov_declaration.h:79
tov_NLCabbage
Definition: tov_declaration.h:95
tofs_Foobar
Definition: farm.h:296
tof_UserDefinedFarm24
Definition: farm.h:261
OptimisingFarm::findYieldLoss
void findYieldLoss(CropOptimised *a_crop)
Determines the yield losses (CropOptimised::m_lossHerb, CropOptimised::m_lossFi, CropOptimised::m_tot...
Definition: farm.cpp:6200
tof_UserDefinedFarm21
Definition: farm.h:258
CropOptimised::m_BIHerb
double m_BIHerb
Value of BI for herbicides [BI/ha].
Definition: farm.h:1667
UserDefinedFarm7
A farm that can have its rotation defined by the user at runtime.
Definition: farm.h:1332
tov_PLBeet
Definition: tov_declaration.h:80
TTypesOfOptFarms
TTypesOfOptFarms
Definition: farm.h:278
WARN_BUG
Definition: maperrormsg.h:34
tocv_BI
Definition: farm.h:406
DataForOptimisation::Set_sellingPrice
void Set_sellingPrice(double a_value, int i)
Definition: farm.h:647
tofg_environment
Definition: farm.h:438
UserDefinedFarm10
A farm that can have its rotation defined by the user at runtime.
Definition: farm.h:1359
OptimisingFarm::Initialize
void Initialize(FarmManager *a_pfm)
Assigns to each farm its farm type, farm size, farm's real ID number, and soil type....
Definition: farm.cpp:5187
tov_PermanentSetaside
Definition: tov_declaration.h:49
OptimisingFarm::m_actual_income
double m_actual_income
An actual income at a farm in a given year.
Definition: farm.h:2122
OptimisingFarm::Get_main_goal
TTypeOfFarmerGoal Get_main_goal()
Definition: farm.h:2058
toa_DCalf
Definition: farm.h:303
toc_WRape
Definition: farm.h:332
toa_MCalf
Definition: farm.h:304
g_farm_fixed_rotation_farms_async
CfgBool g_farm_fixed_rotation_farms_async("FARM_FIXED_ROTATION_FARMS_ASYNC", CFG_CUSTOM, false)
tof_NoPesticideBase
Definition: farm.h:236
Farm::m_farmtype
TTypesOfFarm m_farmtype
Definition: farm.h:940
tov_Lawn
Definition: tov_declaration.h:63
UserDefinedFarm22
A farm that can have its rotation defined by the user at runtime.
Definition: farm.h:1471
cfg_Price_Nt
CfgFloat cfg_Price_Nt("PRICE_NT", CFG_CUSTOM, 1.93)
Price of fertilizer. [DKK/kg].
FarmManager::ReadInitialCropAreas_almass
void ReadInitialCropAreas_almass()
Reads the data on farms' initial crop distributions and saves them in a vector of a DataForOptimisati...
Definition: farm.cpp:3612
tov_NLSpringBarleySpring
Definition: tov_declaration.h:104
OptimisingFarm::m_previous_costs
vector< double > m_previous_costs
Vector of costs from previous years.
Definition: farm.h:2141
Livestock
A class for storing livestock parameters and variables for optimising farms.
Definition: farm.h:1617
AgroChemIndustryCerealFarm2::AgroChemIndustryCerealFarm2
AgroChemIndustryCerealFarm2(FarmManager *a_manager)
Definition: farm.cpp:2114
UserDefinedFarm24::UserDefinedFarm24
UserDefinedFarm24(const char *fname, FarmManager *a_manager)
Definition: farm.cpp:2561
UserDefinedFarm25::UserDefinedFarm25
UserDefinedFarm25(const char *fname, FarmManager *a_manager)
Definition: farm.cpp:2566
tov_PLWinterRye
Definition: tov_declaration.h:74
tov_OSpringBarley
Definition: tov_declaration.h:46
cfg_grain_distribution
CfgInt cfg_grain_distribution("GOOSE_GRAIN_DISTRIBUTION", CFG_CUSTOM, 0, 0, 2)
A switch to fix the grain distribution to a specific year or make a random pick between years....
tov_Setaside
Definition: tov_declaration.h:50
toa_Turkey
Definition: farm.h:315
OptimisingFarm::Get_NeighboursSize
int Get_NeighboursSize(void)
Definition: farm.h:2049
CropOptimised::m_n
double m_n
Total amount of fertilizer applied per ha of a crop [kg N/ha].
Definition: farm.h:1656
UserDefinedFarm24
A farm that can have its rotation defined by the user at runtime.
Definition: farm.h:1491
tov_OrchardCrop
Definition: tov_declaration.h:65
DataForOptimisation::Get_alfa
double Get_alfa(int i)
Definition: farm.h:625
OptimisingFarm::m_area_scaling_factor
double m_area_scaling_factor
Factor used to scale areas of fixed crops and livestock numbers. Used to adjust these values to the f...
Definition: farm.h:2228
cfg_Min_need_satisfaction2
CfgFloat cfg_Min_need_satisfaction2("MIN_NEED_SATISFACTION_TWO", CFG_CUSTOM, 100)
A parameter setting the minimum satisfaction level for yield.
top_PriceHerb
Definition: farm.h:374
OptimisingFarm::InitiateManagement
virtual void InitiateManagement(void)
Kicks off the farm's management.
Definition: farm.cpp:5124
Farm::ReadRotation
void ReadRotation(std::string fname)
Reads a rotation file into the rotation.
Definition: farm.cpp:816
FarmManager::Get_crops_summary_BIs_tov
TTypesOfVegetation Get_crops_summary_BIs_tov(int i)
Definition: farm.h:1853
OptimisingFarm::MakeRotation::Tov
TTypesOfVegetation Tov
Definition: farm.h:2175
tov_SpringBarleySeed
Definition: tov_declaration.h:52
cfg_Price_FU
CfgFloat cfg_Price_FU("PRICE_FU", CFG_CUSTOM, 1.157)
Price of a fodder unit. [DKK/FU].
tov_SpringBarleySKManagement
Definition: tov_declaration.h:65
OptimisingCattleFarm::checkCattleRotation_almass
void checkCattleRotation_almass()
Checks if the cattle restriction is fulfilled - in the ALMaSS crops mode.
Definition: farm.cpp:7304
AnimalFarm::m_fakeCrop
CropOptimised * m_fakeCrop
Crop used to fill up area of a farm up to 100% in case its non-fodder crops do not sum to 100% in det...
Definition: farm.h:2378
OptimisingCattleFarm
Subclass of the AnimalFarm.
Definition: farm.h:2448
toc_SCerealG
Definition: farm.h:346
OptimisingFarm::reverseSort
Struct redefining operator < - used for sorting crops.
Definition: farm.h:2167
DataForOptimisation::Get_Nnorm
double Get_Nnorm(int i)
Definition: farm.h:631
FarmManager::FindFarmWithRandom
int FindFarmWithRandom(vector< int > *a_farmlist)
Finds a farm openness more than a value not on the list.
Definition: farm.cpp:3353
OptimisingFarm::Get_almass_no
int Get_almass_no(void)
Definition: farm.h:2039
tof_UserDefinedFarm29
Definition: farm.h:266
OptimisingFarm::Check_SG_and_CGG
void Check_SG_and_CGG()
Modifies areas of SeedGrass1 and SeedGrass2, CloverGrassGrazed1 and CloverGrassGrazed2 to be even....
Definition: farm.cpp:5877
CropOptimised::m_GM
double m_GM
Value of gross margin for a crop (m_income_ha - m_costs_ha) [DKK/ha].
Definition: farm.h:1689
tov_WWheatPToxicControl
Definition: tov_declaration.h:55
tov_NLMaize
Definition: tov_declaration.h:91
OptimisingFarm::m_totalNt
double m_totalNt
Total amount of fertilizer purchased at a farm. [kg].
Definition: farm.h:2246
tov_OWinterWheat
Definition: tov_declaration.h:66
DataForOptimisation::Get_rotationMax
double Get_rotationMax(int i)
Definition: farm.h:653
OptimisingFarm::m_soilType
TTypesOfSoils m_soilType
Farm's soil type (sandy, clay, other).
Definition: farm.h:2212
OptimisingFarm::OptimisingFarm
OptimisingFarm(FarmManager *a_myfarmmanager, int a_No)
The constructor.
Definition: farm.cpp:5153
UserDefinedFarm4
A farm that can have its rotation defined by the user at runtime.
Definition: farm.h:1305
UserDefinedFarm17::UserDefinedFarm17
UserDefinedFarm17(FarmManager *a_manager)
Definition: farm.cpp:2342
Farm::GetTotalArea
int GetTotalArea(void)
Returns the area of all fields owned by that farm.
Definition: farm.cpp:1340
OptimisingFarm::findTotalNanim
void findTotalNanim()
Determines total animal fertilizer (m_totalNanim) available at a farm.
Definition: farm.cpp:5643
AnimalFarm::m_fodderToProduceBefore
double m_fodderToProduceBefore
Fodder that has to be produced to fulfill the min. fodder production restriction at the beginning of ...
Definition: farm.h:2395
tov_SpringBarleyStriglingCulm
Definition: tov_declaration.h:62
Crop::SimpleEvent
void SimpleEvent(long a_date, int a_todo, bool a_lock)
Adds an event to this crop management.
Definition: farm.cpp:307
l_map_read_farmfile
static CfgBool l_map_read_farmfile("MAP_READ_FARMFILE", CFG_PRIVATE, true)
toc_WBarley
Definition: farm.h:327
tov_FieldPeasSilage
Definition: tov_declaration.h:65
toc_GrassRot
Definition: farm.h:351
tov_OCarrots
Definition: tov_declaration.h:43
tole_YoungForest
Definition: tole_declaration.h:55
UserDefinedFarm33::UserDefinedFarm33
UserDefinedFarm33(const char *fname, FarmManager *a_manager)
Definition: farm.cpp:2606
tov_OWinterWheatUndersownExt
Definition: tov_declaration.h:63
FarmManager::m_farms
vector< Farm * > m_farms
Definition: farm.h:1906
LowPriPair
Used in event handling.
Definition: lowqueue.h:83
CropOptimised::m_totalLoss
double m_totalLoss
Summary value of the yield loss due to the limited use of herbicides and fung- and insecticides [%].
Definition: farm.h:1683
DataForOptimisation::Get_cropTypes_almass_str
string Get_cropTypes_almass_str(int i)
Definition: farm.h:666
tov_NLGrassGrazedLast
Definition: tov_declaration.h:108
DataForOptimisation::Set_FUKey
void Set_FUKey(double a_value, int i)
Definition: farm.h:644
tof_UserDefinedFarm22
Definition: farm.h:259
top_PriceG
Definition: farm.h:376
cfg_Areas_Based_on_Distribution
CfgBool cfg_Areas_Based_on_Distribution("AREAS_BASED_ON_DISTRIBUTION", CFG_CUSTOM, false)
If set to true, crops are assigned area based on their gross margin proportion in the total GM for al...
UserDefinedFarm34::UserDefinedFarm34
UserDefinedFarm34(const char *fname, FarmManager *a_manager)
Definition: farm.cpp:2611
tof_UserDefinedFarm31
Definition: farm.h:268
OptimisingFarm::force_deliberation
bool force_deliberation
If set to true, a farm must use deliberation as a decision strategy.
Definition: farm.h:2152
ConventionalCattle
Inbuilt farm type.
Definition: farm.h:1098
FarmManager::FindFarmWithOpenness
int FindFarmWithOpenness(vector< int > *a_farmlist, int a_openness)
Finds a farm openness more than a value not on the list.
Definition: farm.cpp:3370
OptimisingFarm::increaseCrops
virtual void increaseCrops(vector< CropSort >cropsToIncrease, double &howMuchToIncrease)
Increases area of crops by a specified number.
Definition: farm.cpp:7854
top_BetaFi
Definition: farm.h:382
Farm::InvIntPartition
int InvIntPartition(vector< tpct > *items, int target)
Finds all possible sums of the integers in the items array.
Definition: farm.cpp:2493
tov_OBarleyPeaCloverGrass
Definition: tov_declaration.h:41
AnimalFarm::checkWinterCrops
virtual void checkWinterCrops()
Animal farm version of the checkWinterCrops() function (accounts for fodder changes).
Definition: farm.cpp:6932
toof_Plant
Definition: farm.h:281
FarmManager::GetSpilledGrain
double GetSpilledGrain()
Returns the average amount of spilled grain in KJ/m2 this year.
Definition: farm.cpp:3033
tos_Foobar
Definition: farm.h:290
tov_WinterWheatShort
Definition: tov_declaration.h:56
DataForOptimisation::Set_rotationMin
void Set_rotationMin(double a_value, int i)
Definition: farm.h:654
tov_SpringBarleyGrass
Definition: tov_declaration.h:52
g_farm_enable_crop_rotation
CfgBool g_farm_enable_crop_rotation("FARM_ENABLE_CROP_ROTATION", CFG_CUSTOM, true)
OptimisingFarm::Spraying_herbicides
virtual bool Spraying_herbicides(TTypesOfVegetation a_tov_type)
Returns true if a farmer decided to treat a given crop with herbicides.
Definition: farm.cpp:5348
cfg_UseBedriftsmodelFarmAreas
CfgBool cfg_UseBedriftsmodelFarmAreas("USE_BEDRIFTSMODEL_FARM_AREAS", CFG_CUSTOM, false)
If set to true, the farm areas from the original farm optimisation model are used in the optimisation...
OptimisingFarm::findBIs
void findBIs(CropOptimised *a_crop, double benefit)
Determines the optimal Treatment frequency indices (behandling index, BI in Danish) (CropOptimised::m...
Definition: farm.cpp:6047
OptimisingFarm::Print_FarmVariables
void Print_FarmVariables(ofstream *ap_output_file)
Prints farm-level variables to a text file (one file for all farms).
Definition: farm.cpp:8045
OptimisingFarm::m_animals_numbers
vector< double > m_animals_numbers
Vector for storing numbers of animals at a farm in previous years (3).
Definition: farm.h:2150
tof_UserDefinedFarm20
Definition: farm.h:257
FarmManager::ReadLookupTable
void ReadLookupTable()
Reads the lookup table with allowed/forbidden crop order from a text file and saves it into a vector ...
Definition: farm.cpp:4625
AnimalFarm::determineMinFodder
void determineMinFodder(int a_foobar)
Covers the min. required fodder production for animal farms.
Definition: farm.cpp:7541
tocv_BIFi
Definition: farm.h:405
OptimisingFarm::m_decision_mode_counters
vector< int > m_decision_mode_counters
Vector with counters for each decision mode. 0 - imitation, 1 - social comparison,...
Definition: farm.h:2114
cfg_Profit_max_proportion
CfgFloat cfg_Profit_max_proportion("PROFIT_MAX_PROPORTION", CFG_CUSTOM, 100)
A parameter setting the proportion of farmers of a type profit maximiser.
tov_NorwegianOats
Definition: tov_declaration.h:68
DataForOptimisation::Get_cropArea
double Get_cropArea(int index)
Definition: farm.h:607
Farm::m_stockfarmer
bool m_stockfarmer
Definition: farm.h:943
DataForOptimisation::m_winterMax
vector< int > m_winterMax
Maximal area taken by winter crops at a farm. [%].
Definition: farm.h:716
cfg_Price_WRape
CfgFloat cfg_Price_WRape("PRICE_WRAPE", CFG_CUSTOM, 163)
toc_Uncult
Definition: farm.h:353
UserDefinedFarm::UserDefinedFarm
UserDefinedFarm(const char *fname, FarmManager *a_manager)
Definition: farm.cpp:2349
cfg_Min_fodder_prod_cattle
CfgFloat cfg_Min_fodder_prod_cattle("MIN_FODDER_PROD_CATTLE", CFG_CUSTOM, 35)
A parameter setting the minimum proportion of fodder demand that has to be supplied from own fodder p...
DataForOptimisation::Set_winterMax
void Set_winterMax(int a_value, int i)
Definition: farm.h:613
OptimisingFarm::m_previously_imitated_neighbour
OptimisingFarm * m_previously_imitated_neighbour
The neighbouring farmer whose crops might be copied in imitation and social comparison decision modes...
Definition: farm.h:2147
tofs_Business
Definition: farm.h:294
PermCropData
Used for storing permanent crop data for the farm rotation.
Definition: farm.h:448
OptimisingFarm::Get_rotational_crops_visible
vector< AlmassCrop > Get_rotational_crops_visible()
Definition: farm.h:2052
Landscape
The landscape class containing all environmental and topographical data.
Definition: landscape.h:112
toc_SCerealSil
Definition: farm.h:342
toc_Triticale
Definition: farm.h:330
ConventionalPlant::ConventionalPlant
ConventionalPlant(FarmManager *a_manager)
Definition: farm.cpp:2019
tof_UserDefinedFarm3
Definition: farm.h:240
tov_YoungForest
Definition: tov_declaration.h:60
CropOptimised::m_lossFi
double m_lossFi
Value of the yield loss due to the limited use of fung- and insecticides [%].
Definition: farm.h:1681
CropOptimised
A class for storing all parameters and results of crop optimisation.
Definition: farm.h:1634
cfg_Environmentalist_proportion
CfgFloat cfg_Environmentalist_proportion("ENVIRONMENTALIST_PROPORTION", CFG_CUSTOM, 0)
A parameter setting the proportion of farmers of a type environmentalist.
OptimisingFarm::HandleEvents
virtual void HandleEvents(void)
If there are events to carry out do this, and perhaps start a new crop.
Definition: farm.cpp:952
OptimisingFarm::findNanim
void findNanim()
Determines amount of animal fertilizer per ha (m_Nanim) at a farm.
Definition: farm.cpp:5665
DataForOptimisation::m_beta2
vector< double > m_beta2
Crop parameter for response (growth) function (resp = alfa + beta1*N + beta2*N^2; defines relationshi...
Definition: farm.h:732
DataForOptimisation::Get_cropAreasSize
int Get_cropAreasSize()
Definition: farm.h:608
tov_OWinterBarleyExt
Definition: tov_declaration.h:65
UserDefinedFarm1
Definition: farm.h:1278
tov_NorwegianSpringBarley
Definition: tov_declaration.h:68
AlmassCrop
Struct for storing ALMaSS crop type (TTypesOfVegetation) with a corresponding value (mainly crop area...
Definition: farm.h:580
toa_Mink
Definition: farm.h:312
toc_SBarley
Definition: farm.h:324
FarmManager::TranslateSoilCodes
TTypesOfSoils TranslateSoilCodes(string &str)
Definition: farm.cpp:4286
tov_SpringBarleySilage
Definition: tov_declaration.h:52
top_BetaH
Definition: farm.h:386
OptimisingFarm::m_totalGrooming
double m_totalGrooming
Total grooming planned at a farm.
Definition: farm.h:2254
UserDefinedFarm14::UserDefinedFarm14
UserDefinedFarm14(FarmManager *a_manager)
Definition: farm.cpp:2320
UserDefinedFarm16
A farm that can have its rotation defined by the user at runtime.
Definition: farm.h:1413
CropOptimised::m_optimalN
double m_optimalN
Optimal amount of fertilizer per ha of a crop supposing ferilizer price equals zero [kg N/ha]....
Definition: farm.h:1660
OptimisingFarm::findMWeedControl
void findMWeedControl(CropOptimised *a_crop)
Determines the optimal mechanical weed control means (CropOptimised::m_grooming, CropOptimised::m_hoe...
Definition: farm.cpp:6153
tov_NLGrassGrazed1Spring
Definition: tov_declaration.h:107
VegElement
Definition: elements.h:568
DataForOptimisation::Get_cropTypes_almass
TTypesOfVegetation Get_cropTypes_almass(int i)
Definition: farm.h:663
tof_UserDefinedFarm5
Definition: farm.h:242
FarmManager::TranslateCropsCodes
TTypesOfCrops TranslateCropsCodes(string &str)
Definition: farm.cpp:4338
OptimisingFarm::preventCashCrops
virtual void preventCashCrops()
Prevents small cattle farms from growing cash crops and maize silage.
Definition: farm.h:2293
OptimisingFarm::crop_parameter
double crop_parameter(int index, string par_name)
Reads in crop parameters that do NOT vary with any farm level parameters.
Definition: farm.cpp:7756
CropOptimised::m_hoeing
double m_hoeing
Value of mechanical weed control for a crop - hoeing [DKK/ha].
Definition: farm.h:1675
Farm::GetFarmNumber
int GetFarmNumber(void)
Definition: farm.h:782
LE::SetRotIndex
void SetRotIndex(int a_index)
Definition: elements.h:307
OptimisingFarm::Set_Crop
void Set_Crop(CropOptimised *p_crop)
Definition: farm.h:2043
DataForOptimisation::m_fixed
vector< bool > m_fixed
Crop Boolean parameter - fixed/variable crop. Farm type specific.
Definition: farm.h:741
tov_DummyCropPestTesting
Definition: tov_declaration.h:112
FarmManager::m_cropTotals
vector< double > m_cropTotals
Stores crops areas at the landscape level per year.
Definition: farm.h:1937
TTypesOfVegetation
TTypesOfVegetation
Definition: tov_declaration.h:30
UserDefinedFarm28
A farm that can have its rotation defined by the user at runtime.
Definition: farm.h:1531
OptimisingFarm::decreaseCrops
virtual void decreaseCrops(vector< CropSort >cropsToDecrease, double &howMuchToDecrease)
Decreases area of a crops by a specified number.
Definition: farm.cpp:7912
toc_OLSeed
Definition: farm.h:335
OptimisingFarm::m_exp_profit
double m_exp_profit
An expected farm's profit for a given year.
Definition: farm.h:2120
tov_SpringRape
Definition: tov_declaration.h:53
OptimisingFarm::findFertilizer
void findFertilizer(CropOptimised *a_crop, int a_foobar, double benefit)
Determines the optimal amounts of: total fertilizer (CropOptimised::m_n) and purchased fertilizer (Cr...
Definition: farm.cpp:5906
FarmManager::PrintOutput
void PrintOutput(TTypesOfCropVariables a_var, string a_fileName)
Makes an output file for one crop variable and prints its values for each crop and each OptimisingFar...
Definition: farm.cpp:4504
tof_UserDefinedFarm1
Definition: farm.h:238
OptimisingFarm::m_actual_profit
double m_actual_profit
An actual profit realised at a farm in a given year.
Definition: farm.h:2118
PesticideTrialControl
Inbuilt special purpose farm type.
Definition: farm.h:1172
cfg_Yield_max_pest_prob_multiplier
CfgFloat cfg_Yield_max_pest_prob_multiplier("YIELD_MAX_PEST_PROB_MULITPLIER", CFG_CUSTOM, 1.5)
A parameter of the yield maximizer farmer type: it increases the chance of necessity of carrying out ...
tof_UserDefinedFarm4
Definition: farm.h:241
FarmManager::ReadCropsData_perFarm_and_Soil
void ReadCropsData_perFarm_and_Soil()
Reads the data on crops' parameters that vary with a farm and soil type (sellingPrice) and saves them...
Definition: farm.cpp:4003
FarmManager::ActualProfit
void ActualProfit()
Calls OptimisingFarm::ActualProfit for all optimising farms.
Definition: farm.cpp:3433
UserDefinedFarm::InitiateManagement
virtual void InitiateManagement(void)
Kicks off the farm's management.
Definition: farm.cpp:1499
OptimisingCattleFarm::checkRestrictions
virtual void checkRestrictions()
Checks if the restrictions are fulfilled and corrects crops' areas if necessary.
Definition: farm.cpp:6442
Calendar::Date
long Date(void)
Definition: calendar.h:57
tov_PotatoesIndustry
Definition: tov_declaration.h:50
CropActualValues::no_herb_app
int no_herb_app
Definition: elements.h:561
OrganicCattle
A farm that can have its rotation defined by the user at runtime.
Definition: farm.h:1160
OptimisingFarm::m_totalFUgrown
double m_totalFUgrown
Fodder grown, i.e. obtained from growing fodder crops. [fodder units].
Definition: farm.h:2240
OptimisingFarm::Print_rotations
void Print_rotations(ofstream *ap_output_file)
Prints the content of a farm's m_rotation. Not used in ALMaSS crop mode.
Definition: farm.cpp:8389
tofs_Private
Definition: farm.h:295
DataForOptimisation::FarmData::md_farmType
TTypesOfOptFarms md_farmType
Definition: farm.h:678
toa_EHen
Definition: farm.h:313
OptimisingFarm::m_previous_incomes
vector< double > m_previous_incomes
Vector of incomes from previous years.
Definition: farm.h:2139
tov_SpringBarleyPTreatment
Definition: tov_declaration.h:63
OptimisingCattleFarm::preventCashCrops
virtual void preventCashCrops()
Prevents small cattle farms from growing cash crops and maize silage.
Definition: farm.cpp:5704
UserDefinedFarm16::UserDefinedFarm16
UserDefinedFarm16(FarmManager *a_manager)
Definition: farm.cpp:2334
OptimisingOtherFarm
Subclass of the NonAnimalFarm.
Definition: farm.h:2504
Livestock::m_animalType
TTypesOfAnimals m_animalType
Type of livestock.
Definition: farm.h:1622
FarmManager::ReadCropsData_almass
void ReadCropsData_almass()
Reads the data on crops' parameters that do not vary with farm variables and saves them in a vector D...
Definition: farm.cpp:3688
tov_FodderGrass
Definition: tov_declaration.h:62
OptimisingFarm::m_previous_aggregated_yields
vector< double > m_previous_aggregated_yields
Vector of aggregated yields from previous years.
Definition: farm.h:2143
NoPesticideNoPFarm::NoPesticideNoPFarm
NoPesticideNoPFarm(FarmManager *a_manager)
Definition: farm.cpp:2193
toa_Finisher
Definition: farm.h:309
FarmManager::ReadCropsData
void ReadCropsData()
Reads the data on crops' parameters that do not vary with farm variables and saves them in a vector D...
Definition: farm.cpp:3656
tov_PLBeetSpr
Definition: tov_declaration.h:86
tov_PlantNursery
Definition: tov_declaration.h:66
tov_NLCatchPeaCrop
Definition: tov_declaration.h:106
tov_Carrots
Definition: tov_declaration.h:31
AnimalFarm::determineAreas
virtual void determineAreas(int a_foobar)
Determines areas of variable crops.
Definition: farm.cpp:6373
UserDefinedFarm8
A farm that can have its rotation defined by the user at runtime.
Definition: farm.h:1341
toc_OFodderBeet
Definition: farm.h:356
tof_PTrialControl
Definition: farm.h:229
CropOptimised::m_area_ha
double m_area_ha
Area of a crop in ha at a farm [ha].
Definition: farm.h:1699
UserDefinedFarm27::UserDefinedFarm27
UserDefinedFarm27(const char *fname, FarmManager *a_manager)
Definition: farm.cpp:2576
UserDefinedFarm23::UserDefinedFarm23
UserDefinedFarm23(const char *fname, FarmManager *a_manager)
Definition: farm.cpp:2556
OptimisingFarm::FarmLevelCalculation
void FarmLevelCalculation()
Calls functions determining farm level values before the initial optimisation.
Definition: farm.cpp:5613
DataForOptimisation::Set_Nnorm
void Set_Nnorm(double a_value, int i)
Definition: farm.h:630
OptimisingFarm::animals_no
int animals_no
Holds the number of animals in a farm at a particular day in a year (depends on a species).
Definition: farm.h:2154
VegElement::Clean_CropDataStorage
void Clean_CropDataStorage(int index)
Definition: elements.cpp:2129
OptimisingFarm::createVariableCrops
void createVariableCrops(int a_foobar)
Creates a list of pointers to all variable crops included in the optimisation and a list of pointers ...
Definition: farm.cpp:5579
tov_NLCarrotsSpring
Definition: tov_declaration.h:101
CfgBool
Bool configurator entry class.
Definition: configurator.h:127
FarmManager::PrintFinalResults
void PrintFinalResults()
At the end of a simulation it prints results on crop distribution, pesticide and fertilizer usage.
Definition: farm.cpp:4741
tole_PermPasture
Definition: tole_declaration.h:47
Farm::AddNewEvent
void AddNewEvent(TTypesOfVegetation a_event, long a_date, LE *a_field, int a_todo, long a_num, bool a_lock, int a_start, bool a_first_year, TTypesOfVegetation a_crop)
Adds an event to the event queue for a farm.
Definition: farm.cpp:789
tocv_GM
Definition: farm.h:414
OptimisingFarm::checkWinterCrops
virtual void checkWinterCrops()
Checks if the restriction on a max. share of winter crops is fulfilled.
Definition: farm.h:2332
AnimalFarm::m_fodderToProduce
double m_fodderToProduce
Fodder that has to be produced to fulfill the min. fodder production restriction at the end of a year...
Definition: farm.h:2393
tov_NLPotatoesSpring
Definition: tov_declaration.h:103
AnimalFarm::cash_crops_allowed
bool cash_crops_allowed
Sets to true if cash crops are allowed. True by default.
Definition: farm.h:2397
FarmManager::FarmManagement
void FarmManagement()
Runs the daily farm management for each farm, but also calculates annual spilled grain and maize.
Definition: farm.cpp:2707
DataForOptimisation::Get_biomass_factor
double Get_biomass_factor(int i)
Definition: farm.h:660
tofg_profit
Definition: farm.h:436
OptimisingFarm::findCropByName
CropOptimised * findCropByName(string crop_name)
Returns a pointer to a crop whose name is specified as the argument (bedriftsmodel,...
Definition: farm.cpp:7762
OptimisingFarm::findFodderDemand
virtual void findFodderDemand()
Determines farm's total demand for fodder (m_totalFUdemand).
Definition: farm.cpp:5670
cfg_FarmSizeProbParam1
CfgFloat cfg_FarmSizeProbParam1("FARMSIZEPROBPARAMONE", CFG_CUSTOM, 1.5)
A fitting parameter for the probability of hunter acceptance of a farm that is smaller.
Farm::m_rotation
vector< TTypesOfVegetation > m_rotation
Definition: farm.h:938
UserDefinedFarm21
A farm that can have its rotation defined by the user at runtime.
Definition: farm.h:1461
Farm::m_farm_centroidx
int m_farm_centroidx
Farm's centroid, value x. Equal to the average of the x centroid values of all farm's fields.
Definition: farm.h:959
CropOptimised::m_benefit
double m_benefit
A value of selling price for non-fodder crops or a value of fodder units obtained from a hkg of a fod...
Definition: farm.h:1663
FarmManager::Save_last_years_crops_for_farms
void Save_last_years_crops_for_farms()
Calls OptimisingFarm::Save_last_years_crops for all optimising farms.
Definition: farm.cpp:3456
FarmManager::m_crops_fertilizer_trade
vector< double > m_crops_fertilizer_trade
Stores information on aggregate (all farms) fertilizer trade (Nt) usage for each crop.
Definition: farm.h:1955
UserDefinedFarm9::UserDefinedFarm9
UserDefinedFarm9(FarmManager *a_manager)
Definition: farm.cpp:2284
OptimisingFarm::m_crops
vector< CropOptimised * > m_crops
Vector of pointers to all crops.
Definition: farm.h:2183
tov_SpringBarleyCloverGrass
Definition: tov_declaration.h:52
CropOptimised::m_nt
double m_nt
Amount of purchased (and applied) fertilizer per ha of a crop [kg N/ha].
Definition: farm.h:1658
TTypesOfLivestockParameters
TTypesOfLivestockParameters
Definition: farm.h:392
TTypesOfFarmSize
TTypesOfFarmSize
Definition: farm.h:293
tov_WinterRape
Definition: tov_declaration.h:53
FarmManager::PrintDecModes_counts
void PrintDecModes_counts()
For each OptimizingFarm it prints the number of times each of the decision modes was used within a si...
Definition: farm.cpp:4720
tov_OGrazingPigs
Definition: tov_declaration.h:44
tov_SugarBeet
Definition: tov_declaration.h:66
cfg_ClosestFarmProbParam2
CfgFloat cfg_ClosestFarmProbParam2("CLOSESTFARMPROBPARAMTWO", CFG_CUSTOM, 1.0)
A fitting parameter for the probability of hunter acceptance of a farm with distance from home - scal...
OptimisingFarm::m_Nanim
double m_Nanim
Amount of animal fertilizer available at a farm per hectar. [kg/ha].
Definition: farm.h:2232
FarmManager::AddField
void AddField(int a_OwnerIndex, LE *a_newland, int a_Owner)
Definition: farm.cpp:2741
tov_NLBeet
Definition: tov_declaration.h:89
UserDefinedFarm23
A farm that can have its rotation defined by the user at runtime.
Definition: farm.h:1481
tov_NorwegianPotatoes
Definition: tov_declaration.h:68
CropOptimised::m_BIFi
double m_BIFi
Value of BI for fung- and insecticides [BI/ha].
Definition: farm.h:1669
tole_PermanentSetaside
Definition: tole_declaration.h:46
tov_OSBarleySilage
Definition: tov_declaration.h:56
top_AlfaW
Definition: farm.h:387
OptimisingFarm::m_main_goal
TTypeOfFarmerGoal m_main_goal
Farmer's main goal (determined by a farmer's type) .
Definition: farm.h:2103
cfg_OnlyDeliberation
CfgBool cfg_OnlyDeliberation("ONLY_DELIBERATION", CFG_CUSTOM, true)
If set to yes, the only decision mode/startegy the farmers can use is deliberation (i....
FarmManager::PrintNeighbours
void PrintNeighbours()
Creates an output file with a list of neighbours of each OptimisingFarm.
Definition: farm.cpp:4701
tov_SpringBarleyPeaCloverGrassStrigling
Definition: tov_declaration.h:60
tov_PermanentGrassGrazed
Definition: tov_declaration.h:49
CropOptimised::m_cropType
TTypesOfCrops m_cropType
Type/name of a crop (original farm optimization model crop types).
Definition: farm.h:1644
cfg_MaizeEnergy
CfgBool cfg_MaizeEnergy("MAIZE_ENERGY", CFG_CUSTOM, false)
If set to true, the energy maize crop is included in the simulation.
OptimisingFarm::m_totalNanim
double m_totalNanim
Total animal fertilizer at a farm. A sum of Livestock::m_NanimUsable (from all types of livestock)....
Definition: farm.h:2230
CropOptimised::m_income_ha
double m_income_ha
Value of income per ha of a crop. Includes value of sales and subsidy [DKK/ha].
Definition: farm.h:1687
LowPriPair::m_pri
long m_pri
Definition: lowqueue.h:89
HunterInfo
A data structure to hold hunter information for distribution.
Definition: farm.h:510
FarmManager::TranslateCropVariablesCodes
TTypesOfCropVariables TranslateCropVariablesCodes(string &str)
Definition: farm.cpp:4426
FarmManager::pm_output_file
ofstream * pm_output_file
Definition: farm.h:1877
tov_CloverGrassGrazed2
Definition: tov_declaration.h:33
UserDefinedFarm35
A farm that can have its rotation defined by the user at runtime.
Definition: farm.h:1601
AnimalFarm::createFodderCrops
void createFodderCrops(int a_foobar)
Creates a list of pointers to all fodder crops.
Definition: farm.cpp:5596
cfg_Min_certainty
CfgFloat cfg_Min_certainty("MIN_CERTAINTY", CFG_CUSTOM, 0)
A parameter setting the minimum certainty level.
tov_WWheatPControl
Definition: tov_declaration.h:55
toa_DCow
Definition: farm.h:301
UserDefinedFarm5
A farm that can have its rotation defined by the user at runtime.
Definition: farm.h:1314
top_Subsidy
Definition: farm.h:372
tov_PLWinterRape
Definition: tov_declaration.h:71
MapErrorMsg::Warn
void Warn(MapErrorState a_level, std::string a_msg1, std::string a_msg2)
Definition: maperrormsg.cpp:59
toc_OUncult
Definition: farm.h:354
tov_PLBeans
Definition: tov_declaration.h:87
tov_SpringBarleyCloverGrassStrigling
Definition: tov_declaration.h:58
FarmManager::Get_lookup_table
int Get_lookup_table(int index)
Definition: farm.h:1879
DataForOptimisation::m_beta1
vector< double > m_beta1
Crop parameter for response (growth) function (resp = alfa + beta1*N + beta2*N^2; defines relationshi...
Definition: farm.h:730
tov_Potatoes
Definition: tov_declaration.h:50
LE::GetRotIndex
int GetRotIndex(void)
Definition: elements.h:309
top_PriceW
Definition: farm.h:378
tov_WinterRyeStrigling
Definition: tov_declaration.h:59
Farm::m_PermCrops
vector< PermCropData > m_PermCrops
Definition: farm.h:939
AnimalFarm::m_fakeCropTest
bool m_fakeCropTest
Set to true if the fake crop is present after determineAreas function.
Definition: farm.h:2384
FarmManager::FindClosestFarm
int FindClosestFarm(HunterInfo a_hinfo, vector< int > *a_farmlist)
Finds the closest farm to this co-ordinate.
Definition: farm.cpp:3126
tov_PLWinterBarley
Definition: tov_declaration.h:72
Landscape::SupplyDayInYear
int SupplyDayInYear(void)
Definition: landscape.h:1596
toc_SRape
Definition: farm.h:331
CropOptimised::m_resp
double m_resp
Response - yield of a crop per ha [hkg/ha].
Definition: farm.h:1665
AgroChemIndustryCerealFarm1
Inbuilt special purpose farm type.
Definition: farm.h:1214
FarmManager::Switch_rotation
void Switch_rotation()
Switches OptimisingFarms Farm::m_rotation to the list of all possible rotational crops.
Definition: farm.cpp:4942
FarmEvent::m_event
TTypesOfVegetation m_event
Definition: farm.h:470
tov_WinterWheatStriglingCulm
Definition: tov_declaration.h:62
Crop::Do
virtual bool Do(Farm *a_farm, LE *a_field, FarmEvent *a_ev)
Definition: farm.cpp:303
top_BetaG
Definition: farm.h:384
FarmManager::FindClosestFarmOpennessProbNearRoostIsBest
int FindClosestFarmOpennessProbNearRoostIsBest(HunterInfo a_hinfo, vector< int > *a_farmlist, int a_openness, vector< APoint > *a_farmsizelist)
Finds the closest farm to this co-ordinate with openness more than a value but uses a probability dis...
Definition: farm.cpp:3289
VegElement::Set_tov_type
void Set_tov_type(TTypesOfVegetation a_tov_type, int index)
Definition: elements.h:639
OptimisingFarm::Set_animals_no
void Set_animals_no(int a_number)
Definition: farm.h:2059
Farm::m_farm_centroidy
int m_farm_centroidy
Farm's centroid, value y. Equal to the average of the y centroid values of all farm's fields.
Definition: farm.h:961
OptimisingFarm::m_need_satisfaction_level
double m_need_satisfaction_level
Farmer's actual satisfaction level.
Definition: farm.h:2110
Farm::GetArea
int GetArea(void)
Returns the area of arable fields owned by that farm.
Definition: farm.cpp:1331
tocc_Winter
Definition: farm.h:214
tos_Sand
Definition: farm.h:287
tov_NLTulips
Definition: tov_declaration.h:96
Livestock::m_NanimUsable
double m_NanimUsable
Amount of usable animal fertilizer from a given type of livestock. [kg].
Definition: farm.h:1626
DataForOptimisation::m_rotationMax
vector< double > m_rotationMax
Maximum acreage of a crop at a farm [%]. Farm type, soil type and farm size specific.
Definition: farm.h:753
UserDefinedFarm1::UserDefinedFarm1
UserDefinedFarm1(FarmManager *a_manager)
Definition: farm.cpp:2220
tov_WinterRapeStrigling
Definition: tov_declaration.h:59
toc_OSpecCrops
Definition: farm.h:361
toof_Cattle
Definition: farm.h:280
CropActualValues::tov_type
TTypesOfVegetation tov_type
Definition: elements.h:557
UserDefinedFarm35::UserDefinedFarm35
UserDefinedFarm35(const char *fname, FarmManager *a_manager)
Definition: farm.cpp:2616
OptimisingFarm::Get_cropsSize
int Get_cropsSize(void)
Definition: farm.h:2041
UserDefinedFarm20::UserDefinedFarm20
UserDefinedFarm20(const char *fname, FarmManager *a_manager)
Definition: farm.cpp:2541
FarmManager::TranslateFarmSizeCodes
TTypesOfFarmSize TranslateFarmSizeCodes(string &str)
Definition: farm.cpp:4298
tpct::pct
int pct
Definition: farm.h:456
OptimisingPlantFarm
Subclass of the NonAnimalFarm.
Definition: farm.h:2495
DataForOptimisation::Get_cropParameter
double Get_cropParameter(int i)
Definition: farm.h:622
Landscape::SupplyYearNumber
int SupplyYearNumber(void)
Definition: landscape.h:1616
toa_Horse
Definition: farm.h:300
FarmEvent::m_field
LE * m_field
Definition: farm.h:472
FarmManager::Set_cropTotals_other_sum
void Set_cropTotals_other_sum(int i, double crop_area)
Definition: farm.h:1861
toc_FruitTree
Definition: farm.h:360
OptimisingFarm::m_rotational_crops_visible
vector< AlmassCrop > m_rotational_crops_visible
Stores a copy of m_rotational_crops from a previous year and is accessible to farmers who want to cop...
Definition: farm.h:2206
DataForOptimisation::Set_fodder
void Set_fodder(string a_value, int i)
Definition: farm.h:639
PesticideTrialTreatment
Inbuilt special purpose farm type.
Definition: farm.h:1192
PesticideTrialToxicControl::PesticideTrialToxicControl
PesticideTrialToxicControl(FarmManager *a_manager)
Definition: farm.cpp:2067
Livestock::Livestock
Livestock(TTypesOfAnimals a_animalType, int a_number)
Constructor.
Definition: farm.cpp:5094
tof_UserDefinedFarm10
Definition: farm.h:247
TTypesOfParameters
TTypesOfParameters
Definition: farm.h:371
UserDefinedFarm18::UserDefinedFarm18
UserDefinedFarm18(const char *fname, FarmManager *a_manager)
Definition: farm.cpp:2531
AnimalFarm::AnimalFarm
AnimalFarm(FarmManager *a_myfarmmanager, int a_No)
Definition: farm.cpp:5270
toc_WCerealSil
Definition: farm.h:345
tov_OMaizeSilage
Definition: tov_declaration.h:65
OptimisingFarm::m_totalBI
double m_totalBI
Total amount of pesticides (sum of m_totalBIHerb and m_totalBIFi) which is planned to be applied at a...
Definition: farm.h:2252
OptimisingFarm::createCropsLists
virtual void createCropsLists(int a_foobar)
Creates lists of crops.
Definition: farm.cpp:5570
toa_Suckler
Definition: farm.h:302
tole_Orchard
Definition: tole_declaration.h:71
OptimisingFarm::sortCrops
void sortCrops(vector< CropSort > &cropsToSort, string sortingKey)
Sorts structs of type CropSort.
Definition: farm.cpp:7788
DataForOptimisation::m_biomass_factors
vector< double > m_biomass_factors
Factor used to determine actual response (yield per ha) based on crop biomass at a harvest....
Definition: farm.h:737
tov_Maize
Definition: tov_declaration.h:36
UserDefinedFarm2
A farm that can have its rotation defined by the user at runtime.
Definition: farm.h:1287
CropActualValues::biomass_at_harvest
double biomass_at_harvest
Definition: elements.h:558
tof_UserDefinedFarm30
Definition: farm.h:267
cfg_Price_SBarley
CfgFloat cfg_Price_SBarley("PRICE_SBARLEY", CFG_CUSTOM, 83)
CropOptimised::m_lossHerb
double m_lossHerb
Value of the yield loss due to the limited use of herbicides [%].
Definition: farm.h:1679
OptimisingFarm::m_exp_aggregated_yield
double m_exp_aggregated_yield
Expected aggregated yield at a farm in a given year.
Definition: farm.h:2134
DataForOptimisation::m_FUKey
vector< double > m_FUKey
Crop parameter: Fodder unit key, i.e. a number of fodder units obtained from a given crop [FU/hkg]....
Definition: farm.h:745
tocv_AreaPercent
Definition: farm.h:400
OptimisingFarm::m_actual_aggregated_yield
double m_actual_aggregated_yield
Actual aggregated yield at a farm in a given year.
Definition: farm.h:2131
UserDefinedFarm15
A farm that can have its rotation defined by the user at runtime.
Definition: farm.h:1404
CropActualValues::area
double area
Definition: elements.h:560
cfg_Price_Oats
CfgFloat cfg_Price_Oats("PRICE_OATS", CFG_CUSTOM, 75)
DataForOptimisation::Set_cropTypes
void Set_cropTypes(TTypesOfCrops crop_type)
Definition: farm.h:596
tov_OWinterRape
Definition: tov_declaration.h:47
g_farm_fixed_rotation_enable
CfgBool g_farm_fixed_rotation_enable("FARM_FIXED_ROTATION_ENABLE", CFG_CUSTOM, false)
tov_WWheatPTreatment
Definition: tov_declaration.h:55
OptimisingFarm::Get_actual_profit
double Get_actual_profit()
Definition: farm.h:2053
OptimisingFarm::m_totalFUdemand
double m_totalFUdemand
Farm's total demand for fodder (it is covered by growing fodder crops and/or purchasing fodder and th...
Definition: farm.h:2236
VegElement::Get_CropDataStorage
CropActualValues Get_CropDataStorage(int index)
Definition: elements.h:663
tof_UserDefinedFarm25
Definition: farm.h:262
toa_MCattle
Definition: farm.h:305
PermCropData::Tov
TTypesOfVegetation Tov
Definition: farm.h:449
FarmManager::Create_Output_file_for_farms
void Create_Output_file_for_farms()
Creates an output file. Prints the crop variables in the first row of the file. The file is used then...
Definition: farm.cpp:4609
CfgFloat::value
double value(void)
Definition: configurator.h:118
FarmManager::ReadCropsData_perFarm_and_Soil_and_Size
void ReadCropsData_perFarm_and_Soil_and_Size()
Reads the data on crops' parameters that vary with a farm type, soil type and farm size (rotationMax,...
Definition: farm.cpp:4074
PesticideTrialToxicControl
Inbuilt special purpose farm type.
Definition: farm.h:1182
DataForOptimisation::Set_alfa
void Set_alfa(double a_value, int i)
Definition: farm.h:624
ConvMarginalJord
Inbuilt special purpose farm type.
Definition: farm.h:1204
OptimisingFarm::m_totalWeeding
double m_totalWeeding
Total manual weeding planned at a farm.
Definition: farm.h:2258
OptimisingFarm::m_rotational_crops_copy
vector< AlmassCrop > m_rotational_crops_copy
A copy of m_rotational_crops used when matching crops to fields.
Definition: farm.h:2204
FarmEvent::m_todo
int m_todo
Definition: farm.h:469
toa_So
Definition: farm.h:308
tof_PTrialToxicControl
Definition: farm.h:231
cfg_OptimisingFarms
CfgBool cfg_OptimisingFarms("OPTIMISING_FARMS", CFG_CUSTOM, false)
If set to true, the farmer decision making model is active.
DataForOptimisation::Set_rotationMax
void Set_rotationMax(double a_value, int i)
Definition: farm.h:652
tov_FieldPeas
Definition: tov_declaration.h:34
OptimisingFarm::Get_farmSize
TTypesOfFarmSize Get_farmSize(void)
Definition: farm.h:2036
tocv_Grooming
Definition: farm.h:407
UserDefinedFarm27
A farm that can have its rotation defined by the user at runtime.
Definition: farm.h:1521
tov_SpringBarleyStriglingSingle
Definition: tov_declaration.h:60
tov_BroadBeans
Definition: tov_declaration.h:66
toc_GrassEnv2
Definition: farm.h:350
Farm::RemoveField
void RemoveField(LE *a_field)
Removes a field from a farm.
Definition: farm.cpp:1473
FarmManager::TranslateCropCodes
TTypesOfVegetation TranslateCropCodes(std::string &str)
Definition: farm.cpp:1818
DataForOptimisation::Get_beta1
double Get_beta1(int i)
Definition: farm.h:627
cfg_Min_fodder_prod_pig
CfgFloat cfg_Min_fodder_prod_pig("MIN_FODDER_PROD_PIG", CFG_CUSTOM, 20)
A parameter setting the minimum proportion of fodder demand that has to be supplied from own fodder p...
PesticideTrialTreatment::PesticideTrialTreatment
PesticideTrialTreatment(FarmManager *a_manager)
Definition: farm.cpp:2075
UserDefinedFarm2::UserDefinedFarm2
UserDefinedFarm2(FarmManager *a_manager)
Definition: farm.cpp:2228
LE_TypeClass::TranslateVegTypes
TTypesOfVegetation TranslateVegTypes(int VegReference)
Definition: elements.cpp:3088
DataForOptimisation::Get_livestockNumbersSize
int Get_livestockNumbersSize()
Definition: farm.h:606
CropOptimised::m_areaPercent
double m_areaPercent
Area of a crop in percent of a farm's total area [%].
Definition: farm.h:1695
tov_NLGrassGrazed1
Definition: tov_declaration.h:97
FarmManager::Set_crops_fertilizer
void Set_crops_fertilizer(int i, double fert)
Definition: farm.h:1863
cfg_organic_extensive
CfgBool cfg_organic_extensive("FARM_ORGANIC_EXTENSIVE", CFG_CUSTOM, false)
tocv_Nt
Definition: farm.h:403
OptimisingFarm::Set_Livestock
void Set_Livestock(Livestock *p_lvs)
Definition: farm.h:2042
DataForOptimisation::m_fodder
vector< bool > m_fodder
Crop Boolean parameter - fodder/non-fodder crop. Farm type specific.
Definition: farm.h:743
tov_OSeedGrass1
Definition: tov_declaration.h:46
UserDefinedFarm26::UserDefinedFarm26
UserDefinedFarm26(const char *fname, FarmManager *a_manager)
Definition: farm.cpp:2571
DataForOptimisation::Set_biomass_factor
void Set_biomass_factor(double a_value, int i)
Definition: farm.h:659
FarmManager::ConnectFarm
int ConnectFarm(int a_owner)
Definition: farm.cpp:2752
OptimisingCattleFarm::m_cattleCrops
vector< CropSort > m_cattleCrops
Vector of crops used in checkCattleRotation.
Definition: farm.h:2451
OptimisingFarm::m_winterCrops
vector< CropSort > m_winterCrops
Vector of structs containing pointers to winter crops.
Definition: farm.h:2198
DataForOptimisation::FarmData
Class storing farm information: farm's number used in ALMaSS system, farm's soil type,...
Definition: farm.h:675
FarmManager::TranslateLivestockParametersCodes
TTypesOfLivestockParameters TranslateLivestockParametersCodes(string &str)
Definition: farm.cpp:4414
FarmManager::OptimisationOutput
void OptimisationOutput()
Creates output files for all crop level variables and for landscape level crop distribution....
Definition: farm.cpp:4451
OptimisingFarm::Set_Neighbour
void Set_Neighbour(OptimisingFarm *farm)
Definition: farm.h:2048
toa_Foobar
Definition: farm.h:320
tocv_Costs
Definition: farm.h:413
tov_OFodderBeet
Definition: tov_declaration.h:65
tof_UserDefinedFarm11
Definition: farm.h:248
tov_NLWinterWheat
Definition: tov_declaration.h:94
OptimisingFarm::sumMinAreas
void sumMinAreas()
Adds minimum required areas of variable crops to the variable m_assigned.
Definition: farm.cpp:6294
OptimisingFarm::Prob_multiplier
virtual double Prob_multiplier()
Used when determining whether there should be a spraying event (i.e. pesticides application) or not....
Definition: farm.cpp:5372
UserDefinedFarm9
A farm that can have its rotation defined by the user at runtime.
Definition: farm.h:1350
tov_PLMaize
Definition: tov_declaration.h:77
CFG_CUSTOM
Definition: configurator.h:60
tov_OCloverGrassGrazed1
Definition: tov_declaration.h:43
FarmManager::m_cropTotals_plant_sum
vector< double > m_cropTotals_plant_sum
Stores the sums of crops areas on plant farms within one simulation at the landscape level.
Definition: farm.h:1943
tole_PermPastureTussocky
Definition: tole_declaration.h:45
OptimisingFarm::m_variableCrops2
vector< CropSort > m_variableCrops2
Vector of structs containing pointers to crops which are not fixed and: in case of the winter rotatio...
Definition: farm.h:2190
tov_OSpringBarleyPigs
Definition: tov_declaration.h:47
PermCropData::Pct
int Pct
Definition: farm.h:450
tov_SpringBarleySpr
Definition: tov_declaration.h:66
UserDefinedFarm8::UserDefinedFarm8
UserDefinedFarm8(FarmManager *a_manager)
Definition: farm.cpp:2276
toc_Peas
Definition: farm.h:334
DataForOptimisation::Get_livestockNumber
int Get_livestockNumber(int index)
Definition: farm.h:605
DataForOptimisation::Get_cropTypes_almass_size
int Get_cropTypes_almass_size()
Definition: farm.h:664
FarmManager::FindOpennessFarm
int FindOpennessFarm(int a_openness)
Finds a random farm with at least one field with openness above a_openness.
Definition: farm.cpp:3387
tof_UserDefinedFarm14
Definition: farm.h:251
FarmManager::Set_cropTotals_cattle_sum
void Set_cropTotals_cattle_sum(int i, double crop_area)
Definition: farm.h:1860
g_farm_fixed_crop_type
CfgInt g_farm_fixed_crop_type("FARM_FIXED_CROP_TYPE", CFG_CUSTOM, 22)
LE
Definition: elements.h:81
FarmManager::TranslateFarmCodes
TTypesOfOptFarms TranslateFarmCodes(string &str)
Definition: farm.cpp:4273
tov_PLSpringBarley
Definition: tov_declaration.h:76
DataForOptimisation::m_farm_data
vector< FarmData * > m_farm_data
Definition: farm.h:685
toc_GrassClover
Definition: farm.h:340
tov_PermanentGrassLowYield
Definition: tov_declaration.h:63
FarmManager::IsDuplicateRef
bool IsDuplicateRef(int a_ref, HunterInfo *a_hinfo)
Checks if we already have this ref.
Definition: farm.cpp:3116
UserDefinedFarm20
A farm that can have its rotation defined by the user at runtime.
Definition: farm.h:1451
tov_WinterWheatStrigling
Definition: tov_declaration.h:59
tole_Field
Definition: tole_declaration.h:43
FarmManager::GetDD
double GetDD(void)
Returnes day degrees for the period March 1st - November 1st. Used for determining yields of crops th...
Definition: farm.h:1835
ConventionalPig
Inbuilt farm type.
Definition: farm.h:1110
UserDefinedFarm22::UserDefinedFarm22
UserDefinedFarm22(const char *fname, FarmManager *a_manager)
Definition: farm.cpp:2551
tof_OrganicPig
Definition: farm.h:227
tof_NoPesticideNoP
Definition: farm.h:237
CropOptimised::CropOptimised
CropOptimised()
Definition: farm.cpp:5118
AnimalFarm
Subclass of the OptimisingFarm. Either pig or cattle farm.
Definition: farm.h:2375
CropOptimised::m_rotationMin
double m_rotationMin
Minimum area in percent of farm's arable area for a given crop (depends on a farm size,...
Definition: farm.h:1652
DataForOptimisation::FarmData::md_soilSubType
int md_soilSubType
Definition: farm.h:682
FarmManager::FarmManager
FarmManager()
Farm manager constructor.
Definition: farm.cpp:2626
tov_WinterWheatStriglingSingle
Definition: tov_declaration.h:62
HunterInfo::homeX
int homeX
Hunter home x-coord.
Definition: farm.h:516
OptimisingFarm::m_fixedCrops
vector< CropOptimised * > m_fixedCrops
Vector of pointers to fixed crops.
Definition: farm.h:2194
FarmManager::FindClosestFarmOpennessProb
int FindClosestFarmOpennessProb(HunterInfo a_hinfo, vector< int > *a_farmlist, int a_openness)
Finds the closest farm to this co-ordinate with openness more than a value but uses a probability dis...
Definition: farm.cpp:3182
OptimisingFarm::Init
void Init(ofstream *ap_output_file)
Function carrying out the initial calculations at a farm level (including the initial optimisation).
Definition: farm.cpp:5294
FarmManager::Set_cropTotals_sum
void Set_cropTotals_sum(int i, double crop_area)
Definition: farm.h:1857
Farm::Farm
Farm(FarmManager *a_manager)
Farm constructor - creates an instance of each possible crop type.
Definition: farm.cpp:1058
OptimisingFarm::ChooseDecisionMode
void ChooseDecisionMode()
Function determines which decision mode to use. The choice depends on the values of need satisfaction...
Definition: farm.cpp:5478
OptimisingFarm::MakeRotation
Struct used only in Bedriftsmodel crop type mode for creating m_rotation vector. Bool member used for...
Definition: farm.h:2173
tole_PermPastureLowYield
Definition: tole_declaration.h:44
NoPesticideNoPFarm
Inbuilt special purpose farm type.
Definition: farm.h:1250
UserDefinedFarm32
A farm that can have its rotation defined by the user at runtime.
Definition: farm.h:1571
LowPriPair::m_element
ELEMTYPE m_element
Definition: lowqueue.h:88
HunterInfo::homeY
int homeY
Hunter home y-coord.
Definition: farm.h:518
OptimisingFarm::m_totalN
double m_totalN
Total amount of fertilizer used at a farm. [kg].
Definition: farm.h:2244
NonAnimalFarm
Subclass of the OptimisingFarm. Either plant or other farm.
Definition: farm.h:2475
FarmManager::m_SpilledGrain
bool m_SpilledGrain
Is it 2013 (true) or 2014 (false) as far as grain goes.
Definition: farm.h:1912
toc_PerGrassNorm
Definition: farm.h:348
tolp_Foobar
Definition: farm.h:396
WARN_FILE
Definition: maperrormsg.h:37
PROG_START
#define PROG_START
Definition: farm.h:76
OptimisingFarm::m_farmRealID
int m_farmRealID
Farm's real ID number.
Definition: farm.h:2216
Farm::Management
virtual void Management(void)
Starts the main management loop for the farm and performs some error checking.
Definition: farm.cpp:361
CfgInt
Integer configurator entry class.
Definition: configurator.h:87
DataForOptimisation::DataForOptimisation
DataForOptimisation()
The constructor.
Definition: farm.cpp:5050
cfg_PriceChangeThreshold
CfgFloat cfg_PriceChangeThreshold("PRICE_CHANGE_THRESHOLD", CFG_CUSTOM, 0.2)
This parameter specifies the relative difference in energy maize price which causes a farmer to delib...
UserDefinedFarm34
A farm that can have its rotation defined by the user at runtime.
Definition: farm.h:1591
tov_PLCarrots
Definition: tov_declaration.h:83
Farm::Assign_rotation
void Assign_rotation(vector< TTypesOfVegetation >a_new_rotation)
Definition: farm.cpp:1488
Farm::m_OurManager
FarmManager * m_OurManager
Pointer to the FarmManager.
Definition: farm.h:935
tov_WinterBarley
Definition: tov_declaration.h:53
CropOptimised::m_GM_Savings
double m_GM_Savings
Holds the value of m_GM in case of non-fodder crops and a value of m_savings in case of fodder crops ...
Definition: farm.h:1693
FarmManager::InitiateManagement
void InitiateManagement(void)
Definition: farm.cpp:2733
FarmManager::m_crops_fertilizer
vector< double > m_crops_fertilizer
Stores information on aggregate (all farms) fertilizer usage for each crop.
Definition: farm.h:1953
UserDefinedFarm6
A farm that can have its rotation defined by the user at runtime.
Definition: farm.h:1323
Farm
The base class for all farm types.
Definition: farm.h:767
OptimisingFarm::m_livestock
vector< Livestock * > m_livestock
Vector of pointers to animals belonging to a farm.
Definition: farm.h:2181
FarmManager::totalOptFarmsArea
double totalOptFarmsArea
Definition: farm.h:1930
OptimisingFarm::m_totalBIHerb
double m_totalBIHerb
Total amount of herbicides which is planned to be applied at a farm. Expressed as a Treatment frequen...
Definition: farm.h:2248
AnimalFarm::createCropsLists
virtual void createCropsLists(int a_foobar)
Creates lists of crops.
Definition: farm.cpp:5574
OrganicPig::OrganicPig
OrganicPig(FarmManager *a_manager)
Definition: farm.cpp:2045
FarmManager::Set_cropTotals_pig_sum
void Set_cropTotals_pig_sum(int i, double crop_area)
Definition: farm.h:1859
top_PriceLM
Definition: farm.h:373
OptimisingFarm::m_previous_satisfaction_levels
vector< double > m_previous_satisfaction_levels
Vector of satisfaction levels in five previous years.
Definition: farm.h:2145
Farm::HandleEvents
virtual void HandleEvents(void)
If there are events to carry out do this, and perhaps start a new crop.
Definition: farm.cpp:882
g_msg
MapErrorMsg * g_msg
This pointer provides access the to the internal ALMaSS error message system.
Definition: maperrormsg.cpp:41
toof_Other
Definition: farm.h:279
OrganicPlant
A farm that can have its rotation defined by the user at runtime.
Definition: farm.h:1135
TTypesOfLandscapeElement
TTypesOfLandscapeElement
Definition: tole_declaration.h:36
UserDefinedFarm19
A farm that can have its rotation defined by the user at runtime.
Definition: farm.h:1441
NonAnimalFarm::findFodderDemand
virtual void findFodderDemand()
Determines farm's total demand for fodder (m_totalFUdemand).
Definition: farm.cpp:5693
tof_UserDefinedFarm8
Definition: farm.h:245
FarmManager::TranslateAnimalsCodes
TTypesOfAnimals TranslateAnimalsCodes(string &str)
Definition: farm.cpp:4309
Landscape::SupplyFarmAnimalCensus
int SupplyFarmAnimalCensus(int a_farm_ref, int a_LifeStage)
Definition: Landscape.cpp:745
FarmManager::DumpFarmAreas
void DumpFarmAreas()
Definition: farm.cpp:1964
tov_SeedGrass2
Definition: tov_declaration.h:50
Livestock::m_FUdemand
double m_FUdemand
Amount of fodder needed for a given type of livestock. [fodder units].
Definition: farm.h:1628
DataForOptimisation::Set_beta2
void Set_beta2(double a_value, int i)
Definition: farm.h:628
OptimisingFarm::m_crops_almass
vector< AlmassCrop > m_crops_almass
Vector of structs with almass type crops with positive areas in % (result of optimisation).
Definition: farm.h:2200
AgroChemIndustryCerealFarm2
Inbuilt special purpose farm type.
Definition: farm.h:1223
CfgFloat
Double configurator entry class.
Definition: configurator.h:106
tof_UserDefinedFarm13
Definition: farm.h:250
UserDefinedFarm11::UserDefinedFarm11
UserDefinedFarm11(FarmManager *a_manager)
Definition: farm.cpp:2299
tov_MaizeSilage
Definition: tov_declaration.h:62
DataForOptimisation::m_livestockParameters
vector< double > m_livestockParameters
Vector storing parameters of all livestock types.
Definition: farm.h:720
toa_Piglet
Definition: farm.h:310
FarmManager::m_crop_lookup_table
vector< int > m_crop_lookup_table
Specifies which crop order is allowed in a rotation (i.e. if a given crop can follow another crop).
Definition: farm.h:1939
LE::m_tried_to_do
int m_tried_to_do
Definition: elements.h:85
OptimisingFarm::m_variableCrops
vector< CropSort > m_variableCrops
Vector of structs containing pointers to crops which are not fixed.
Definition: farm.h:2185
FarmManager::m_crop_areas_stages
vector< double > m_crop_areas_stages
Stores information on crop areas calculated in different stages of model development: for comparison ...
Definition: farm.h:1957
FarmManager::m_renumbered
bool m_renumbered
A flag to show whether renumbering was already done.
Definition: farm.h:1917
tov_OPotatoes
Definition: tov_declaration.h:44
OptimisingPigFarm::checkRestrictions
virtual void checkRestrictions()
Checks if the restrictions are fulfilled and corrects crops' areas if necessary.
Definition: farm.cpp:6457
OptimisingFarm::randomizeCropList
void randomizeCropList(vector< CropSort > &listToRandomize, string key)
Swaps randomly elements of the list holding same values of the key (according to which the list was p...
Definition: farm.cpp:7811
CropActualValues::harvested
bool harvested
Definition: elements.h:559
toc_Foobar
Definition: farm.h:367
CFG_PRIVATE
Definition: configurator.h:62
CfgInt::value
int value(void)
Definition: configurator.h:98
cfg_LifeStage
CfgInt cfg_LifeStage("LIFE_STAGE", CFG_CUSTOM, 0)
This parameter specifies the life stage of a species whose numbers farmers use during their decision ...
OptimisingOtherFarm::OptimisingOtherFarm
OptimisingOtherFarm(FarmManager *a_myfarmmanager, int a_No)
Definition: farm.cpp:5291
DataForOptimisation::Set_livestockNumber
void Set_livestockNumber(int a_number)
Definition: farm.h:603
AnimalFarm::m_totalFodderToProduce
double m_totalFodderToProduce
Fodder that has to be produced by a farm to fulfill the min. fodder production restriction....
Definition: farm.h:2391
tole_PlantNursery
Definition: tole_declaration.h:95
Farm::AddField
void AddField(LE *a_newfield)
Adds a field to a farm.
Definition: farm.cpp:1447
OptimisingFarm::Make_rotational_crops
void Make_rotational_crops()
Creates a vector m_rotational_crops using the results of optimisation.
Definition: farm.cpp:8285
OptimisingFarm::m_area_rot
double m_area_rot
Area assigned to rotational crops. [ha].
Definition: farm.h:2266
NonAnimalFarm::checkWinterRotation1
virtual void checkWinterRotation1()
Checks if the restriction on a winter rotation is fulfilled.
Definition: farm.cpp:6469
FarmManager::TranslateParametersCodes
TTypesOfParameters TranslateParametersCodes(string &str)
Definition: farm.cpp:4387
OptimisingPigFarm::check_WRape_WBarley
void check_WRape_WBarley()
Checks if the restriction on winter rape and winter barley attachment is fulfilled and corrects crops...
Definition: farm.cpp:7380
DataForOptimisation::Set_livestockParameter
void Set_livestockParameter(double a_value, int i)
Definition: farm.h:617
CropOptimised::m_savings
double m_savings
Value of savings resulting from growing a fodder crop and not purchasing amount of fodder correspondi...
Definition: farm.h:1691
FarmManager::Save_diff_farm_types_areas
void Save_diff_farm_types_areas()
Calculates and saves total areas of all optimising farms and specific farm types.
Definition: farm.cpp:3404
DataForOptimisation::m_cropParameters
vector< double > m_cropParameters
Vector storing parameters of all crop types.
Definition: farm.h:725
OrganicCattle::OrganicCattle
OrganicCattle(FarmManager *a_manager)
Definition: farm.cpp:2038
CropActualValues::no_fi_app
int no_fi_app
Definition: elements.h:563
DataForOptimisation::Get_beta2
double Get_beta2(int i)
Definition: farm.h:629
tov_OSeedGrass2
Definition: tov_declaration.h:46
DataForOptimisation::m_rotationMin
vector< double > m_rotationMin
Minimum acreage of a crop at a farm [%]. Farm type, soil type and farm size specific.
Definition: farm.h:755
OptimisingFarm::m_rotationCrops
vector< CropSort > m_rotationCrops
Vector of structs containing pointers to (winter) rotation crops.
Definition: farm.h:2196
FarmManager::m_crops_summary_BIs
vector< PesticideData > m_crops_summary_BIs
Stores information on aggregate (all farms)pesticide usage for each crop.
Definition: farm.h:1951
UserDefinedFarm12
A farm that can have its rotation defined by the user at runtime.
Definition: farm.h:1377
OptimisingFarm::m_rotational_crops
vector< AlmassCrop > m_rotational_crops
Vector of structs with almass type crops with positive areas in % (result of optimisation): includes ...
Definition: farm.h:2202
g_farmmanager
FarmManager * g_farmmanager
Definition: farm.cpp:284
janfirst
Definition: plants.h:52
FarmManager::pm_data
DataForOptimisation * pm_data
Pointer to the DataForOptimisation.
Definition: farm.h:1876
FarmEvent::m_run
long m_run
Definition: farm.h:468
OptimisingFarm::m_farmType
TTypesOfOptFarms m_farmType
Farm's type (cattle, pig, plant, other).
Definition: farm.h:2210
tof_UserDefinedFarm16
Definition: farm.h:253
OptimisingFarm
A farm that carries out crop, pesticide and fertilizer planning using simplified optimisation or othe...
Definition: farm.h:2028
AnimalFarm::m_fodderCrops
vector< CropSort > m_fodderCrops
List of pointers to variable (non-fixed) fodder crops.
Definition: farm.h:2386
toc_ChrisTree
Definition: farm.h:362
tov_NLGrassGrazed2
Definition: tov_declaration.h:98
OptimisingFarm::m_assigned
double m_assigned
Variable holding a value of area already reserved for certain crops at a farm. [0-100%].
Definition: farm.h:2242
OptimisingFarm::fixBI
void fixBI()
Sets values of Treatment frequency indices (BI) for crops with fixed amount of pesticides (CropOptimi...
Definition: farm.cpp:6123
DataForOptimisation::FarmData::md_farmRealID
int md_farmRealID
Definition: farm.h:681
FarmManager::m_farmmapping_lookup
int * m_farmmapping_lookup
Used for a dynamic array of lookups converting farm references to internal renumbering.
Definition: farm.h:1915
tov_OFieldPeasSilage
Definition: tov_declaration.h:56
UserDefinedFarm32::UserDefinedFarm32
UserDefinedFarm32(const char *fname, FarmManager *a_manager)
Definition: farm.cpp:2601
Calendar::DayInYear
int DayInYear(void)
Definition: calendar.h:58
top_PriceFi
Definition: farm.h:375
Farm::GetAreaDouble
double GetAreaDouble(void)
Returns the area of arable fields owned by that farm.
Definition: farm.cpp:1350
UserDefinedFarm14
A farm that can have its rotation defined by the user at runtime.
Definition: farm.h:1395
DataForOptimisation::Get_fixed
bool Get_fixed(int i)
Definition: farm.h:638
toa_MDuck
Definition: farm.h:318
OptimisingFarm::findResponse
void findResponse(CropOptimised *a_crop, int a_foobar)
Determines the response (CropOptimised::m_resp) of a crop at a farm.
Definition: farm.cpp:6031
tov_SpringWheat
Definition: tov_declaration.h:53
DataForOptimisation::Set_emaize_price
void Set_emaize_price(double a_value)
Definition: farm.h:671
CropOptimised::m_grooming
double m_grooming
Value of mechanical weed control for a crop - grooming [DKK/ha].
Definition: farm.h:1673
cfg_Animals_number_test_day
CfgInt cfg_Animals_number_test_day("ANIMALS_NUMBER_TEST_DAY", CFG_CUSTOM, 152)
This parameter specifies the day at which farmers observe the number of animals residing at their far...
OptimisingFarm::Find_neighbour_to_imitate
OptimisingFarm * Find_neighbour_to_imitate()
Picks randomly a farmer to imitate/compare with. It chooses among neighbouring farmers with similar f...
Definition: farm.cpp:5380
CropOptimised::m_initialArea
double m_initialArea
Initial area of a crop on a farm [ha].
Definition: farm.h:1642
tov_SpringBarley
Definition: tov_declaration.h:52
FarmManager::~FarmManager
~FarmManager()
Farm manager destructor.
Definition: farm.cpp:2699
FarmManager::totalOptFarmsArea_plant
double totalOptFarmsArea_plant
Definition: farm.h:1931
tov_OWinterRye
Definition: tov_declaration.h:49
tov_NLCarrots
Definition: tov_declaration.h:90
toc_OLSeedCut
Definition: farm.h:341
OptimisingFarm::m_certainty_level
double m_certainty_level
Farmer's certainty level.
Definition: farm.h:2112
OptimisingCattleFarm::checkCattleRotation
void checkCattleRotation()
Checks if the cattle restriction is fulfilled - in the Bedriftsmodel (original farm optimization mode...
Definition: farm.cpp:7053
g_date
class Calendar * g_date
Definition: calendar.cpp:38
OptimisingFarm::m_previous_profits
vector< double > m_previous_profits
Vector of profits from previous years.
Definition: farm.h:2137
top_PriceH
Definition: farm.h:377
tov_OFirstYearDanger
Definition: tov_declaration.h:44
AgroChemIndustryCerealFarm3
Inbuilt special purpose farm type.
Definition: farm.h:1232
cfg_DumpFarmAreas
CfgBool cfg_DumpFarmAreas("DUMP_FARM_AREAS", CFG_CUSTOM, false)
If set to true, an output file with farm areas is produced.
Farm::ListOpenFields
polylist * ListOpenFields(int a_openness)
Returns a list of fields with openness above a_openness.
Definition: farm.cpp:9399
toc_WRye
Definition: farm.h:329
tov_CloverGrassGrazed1
Definition: tov_declaration.h:32
UserDefinedFarm26
A farm that can have its rotation defined by the user at runtime.
Definition: farm.h:1511
tof_UserDefinedFarm15
Definition: farm.h:252
tov_OFieldPeas
Definition: tov_declaration.h:43
Farm::GetAreaOpenFields
int GetAreaOpenFields(int a_openness)
Returns the area of the fields above an openness of a_openness.
Definition: farm.cpp:1369
tov_FodderBeet
Definition: tov_declaration.h:35
TTypesOfCrops
TTypesOfCrops
Definition: farm.h:323
toc_OSCrops
Definition: farm.h:326
tov_WinterRye
Definition: tov_declaration.h:55
tov_PLFodderLucerne2
Definition: tov_declaration.h:82
toc_Fruit
Definition: farm.h:359
FarmManager::ReadLivestockNumbers
void ReadLivestockNumbers()
Reads the data on livestock numbers and saves them in a vector DataForOptimisation::m_livestockNumber...
Definition: farm.cpp:3530
toa_Deer
Definition: farm.h:311
FarmManager::ReadFarmsData_perFarmType
void ReadFarmsData_perFarmType()
Reads the data on farms' parameters that vary with a farm type and saves them in a vector of a DataFo...
Definition: farm.cpp:4184
tov_Triticale
Definition: tov_declaration.h:53
OptimisingFarm::m_exp_costs
double m_exp_costs
Expected costs at a farm in a given year.
Definition: farm.h:2128
Farm::~Farm
virtual ~Farm(void)
Farm destructor - deletes all crop instances and empties event queues.
Definition: farm.cpp:1199
OptimisingFarm::Save_last_years_crops
void Save_last_years_crops()
It saves the OptimisingFarm::m_rotational_crops in a vector m_rotational_crops_visible which is acces...
Definition: farm.cpp:5472
OptimisingFarm::findCropByName_almass
CropOptimised * findCropByName_almass(string crop_name)
Returns a pointer to almass crop whose name is specified as the argument (ALMaSS crops mode).
Definition: farm.cpp:7770
tolp_FUuKey
Definition: farm.h:395
UserDefinedFarm28::UserDefinedFarm28
UserDefinedFarm28(const char *fname, FarmManager *a_manager)
Definition: farm.cpp:2581
tov_PLWinterWheat
Definition: tov_declaration.h:70
g_farm_fixed_crop_enable
CfgBool g_farm_fixed_crop_enable("FARM_FIXED_CROP_ENABLE", CFG_CUSTOM, false)
DataForOptimisation::Set_beta1
void Set_beta1(double a_value, int i)
Definition: farm.h:626
cfg_Price_WWheat
CfgFloat cfg_Price_WWheat("PRICE_WWHEAT", CFG_CUSTOM, 94)
tof_ConventionalPlant
Definition: farm.h:225
CropActualValues::missed_herb_app
int missed_herb_app
Definition: elements.h:562
top_AlfaH
Definition: farm.h:385
tocv_Savings
Definition: farm.h:415
toof_Foobar
Definition: farm.h:283
tof_ConventionalCattle
Definition: farm.h:223
toa_Goose
Definition: farm.h:316
tof_UserDefinedFarm6
Definition: farm.h:243
FarmManager::ReadEnergyMaizePrice
void ReadEnergyMaizePrice()
Definition: farm.cpp:4244
OptimisingFarm::Check_if_area_100
void Check_if_area_100()
Checks if the sum of crops' areaPercent is 100%.
Definition: farm.cpp:8060
tpct::index
int index
Definition: farm.h:455
OptimisingFarm::m_exp_income
double m_exp_income
An expected farm's income at a farm in a given year.
Definition: farm.h:2124
UserDefinedFarm7::UserDefinedFarm7
UserDefinedFarm7(FarmManager *a_manager)
Definition: farm.cpp:2268
TTypesOfAnimals
TTypesOfAnimals
Definition: farm.h:299
DataForOptimisation::InitializeVector
void InitializeVector(vector< double > &vector)
Initializes vector with -1 values.
Definition: farm.cpp:5039
CropOptimised::m_areaVariable
double m_areaVariable
Area of a crop that can be changed when checking for restrictions (=m_areaPercent - m_rotationMin) [%...
Definition: farm.h:1697
g_rand_uni
boost::variate_generator< base_generator_type &, boost::uniform_real<> > g_rand_uni
cfg_OptimiseBedriftsmodelCrops
CfgBool cfg_OptimiseBedriftsmodelCrops("OPTIMISE_BEDRIFTSMODEL_CROPS", CFG_CUSTOM, false)
If set to true, the original farm optimisation model's crop set is used in the farmer decision making...
g_farm_fixed_rotation_farmtype
CfgInt g_farm_fixed_rotation_farmtype("FARM_FIXED_ROTATION_FARMTYPE", CFG_CUSTOM, 0)
FarmManager::m_cropTotals_cattle_sum
vector< double > m_cropTotals_cattle_sum
Stores the sums of crops areas on cattle farms within one simulation at the landscape level.
Definition: farm.h:1947
NoPesticideBaseFarm
Inbuilt special purpose farm type.
Definition: farm.h:1241
DataForOptimisation::Get_rotationMin
double Get_rotationMin(int i)
Definition: farm.h:655
FarmManager
The Farm Manager class.
Definition: farm.h:1706
FarmManager::m_cropTotals_other_sum
vector< double > m_cropTotals_other_sum
Stores the sums of crops areas on other farms within one simulation at the landscape level.
Definition: farm.h:1949
NonAnimalFarm::checkWinterCrops
virtual void checkWinterCrops()
Checks if the restriction on a max. share of winter crops is fulfilled.
Definition: farm.cpp:6836
CfgBool::value
bool value(void)
Definition: configurator.h:135
toc_MaizeSil
Definition: farm.h:344
UserDefinedFarm10::UserDefinedFarm10
UserDefinedFarm10(FarmManager *a_manager)
Definition: farm.cpp:2292
tov_NLPermanentGrassGrazed
Definition: tov_declaration.h:99
FarmManager::ReadCropsData_perFarm_and_Soil_almass
void ReadCropsData_perFarm_and_Soil_almass()
Reads the data on crops' parameters that vary with a farm and soil type (sellingPrice) and saves them...
Definition: farm.cpp:4036
OptimisingFarm::m_farmSize
TTypesOfFarmSize m_farmSize
Scale of the farm - business (size above 10 ha) or private (size below 10 ha).
Definition: farm.h:2214
toa_Ostrich
Definition: farm.h:319
cfg_AnimalsThreshold
CfgFloat cfg_AnimalsThreshold("ANIMALS_THRESHOLD", CFG_CUSTOM, 0)
This parameter specifies the proportion of average number of animals on a farm for previous 3 years,...
Farm::CheckRotationManagementLoop
void CheckRotationManagementLoop(FarmEvent *ev)
Definition: farm.cpp:839
toa_Sheep
Definition: farm.h:306
Crop::ChooseNextCrop
void ChooseNextCrop(int a_no_dates)
Chooses the next crop to grow in a field.
Definition: farm.cpp:318
OptimisingFarm::m_neighbours
vector< OptimisingFarm * > m_neighbours
Vector of pointers to the farms considered neighbours (fulfilling the neighbourship condition) of a g...
Definition: farm.h:2108
OptimisingPlantFarm::OptimisingPlantFarm
OptimisingPlantFarm(FarmManager *a_myfarmmanager, int a_No)
Definition: farm.cpp:5287
OptimisingFarm::Get_actual_aggregated_yield
double Get_actual_aggregated_yield()
Definition: farm.h:2054
OptimisingFarm::Make_rotations
void Make_rotations()
Creates m_rotation. Not used in ALMaSS crop mode.
Definition: farm.cpp:8403
top_AlfaHerb
Definition: farm.h:379
UserDefinedFarm21::UserDefinedFarm21
UserDefinedFarm21(const char *fname, FarmManager *a_manager)
Definition: farm.cpp:2546
tov_SeedGrass1
Definition: tov_declaration.h:50
OptimisingFarm::optimizeCrops
void optimizeCrops(int a_foobar)
Carries out crop optimisation at a farm.
Definition: farm.cpp:5796
FarmManager::Set_cropTotals_plant_sum
void Set_cropTotals_plant_sum(int i, double crop_area)
Definition: farm.h:1858
CropOptimised::m_rotationMax
double m_rotationMax
Maximum area in percent of farm's arable area for a given crop (depends on a farm size,...
Definition: farm.h:1650
DataForOptimisation::FarmData::md_soilType
TTypesOfSoils md_soilType
Definition: farm.h:679
DataForOptimisation::Set_cropTypes_almass
void Set_cropTypes_almass(TTypesOfVegetation crop_type)
Definition: farm.h:662
UserDefinedFarm31
A farm that can have its rotation defined by the user at runtime.
Definition: farm.h:1561
cfg_Min_need_satisfaction1
CfgFloat cfg_Min_need_satisfaction1("MIN_NEED_SATISFACTION_ONE", CFG_CUSTOM, 100)
A parameter setting the minimum satisfaction level for profit.
tov_OSpringBarleyGrass
Definition: tov_declaration.h:46
tof_UserDefinedFarm2
Definition: farm.h:239
OptimisingFarm::m_totalFUt
double m_totalFUt
Fodder from trade (has to be purchased). [fodder units].
Definition: farm.h:2238
LE::SetVegType
virtual void SetVegType(TTypesOfVegetation, TTypesOfVegetation)
Definition: elements.h:164
UserDefinedFarm15::UserDefinedFarm15
UserDefinedFarm15(FarmManager *a_manager)
Definition: farm.cpp:2327
OptimisingCattleFarm::setCattleCropsAtMin
void setCattleCropsAtMin()
Decreases area of cattle crops to their min. required area.
Definition: farm.cpp:7027
OptimisingFarm::ActualProfit
void ActualProfit()
Function that determines actual crop yields and profit in a given year.
Definition: farm.cpp:8806
toa_Goat
Definition: farm.h:307
cfg_Price_SRape
CfgFloat cfg_Price_SRape("PRICE_SRAPE", CFG_CUSTOM, 163)
FarmManager::totalOptFarmsArea_pig
double totalOptFarmsArea_pig
Definition: farm.h:1932
UserDefinedFarm13::UserDefinedFarm13
UserDefinedFarm13(FarmManager *a_manager)
Definition: farm.cpp:2313
OptimisingFarm::Make_almass_crops_vector
void Make_almass_crops_vector()
Creates a vector storing crops with positive area. Used in ALMaSS crop mode.
Definition: farm.cpp:8269
UserDefinedFarm33
A farm that can have its rotation defined by the user at runtime.
Definition: farm.h:1581
tof_OrganicCattle
Definition: farm.h:226
OptimisingFarm::m_totalIncome
double m_totalIncome
Planned total income from growing crops at a farm. [DKK].
Definition: farm.h:2262
tocv_TotalLoss
Definition: farm.h:410
OptimisingFarm::Get_decision_mode_counters
int Get_decision_mode_counters(int index)
Definition: farm.h:2060
OptimisingFarm::total
double total(TTypesOfCropVariables variable_name)
Function for determining total values per farm after initial optimisation.
Definition: farm.cpp:7977
tocv_N
Definition: farm.h:402
toc_Setaside
Definition: farm.h:352
g_landscape_p
Landscape * g_landscape_p
Definition: Landscape.cpp:258
cfg_RoostDistProbParam1
CfgFloat cfg_RoostDistProbParam1("ROOSTDISTPROBPARAMONE", CFG_CUSTOM, 1.5)
A fitting parameter for the probability of hunter acceptance of a farm with distance from roost.
toc_WWheat
Definition: farm.h:328
DataForOptimisation::Get_cropTypes_str
string Get_cropTypes_str(int i)
Definition: farm.h:599
tov_OSpringBarleyExt
Definition: tov_declaration.h:63
Farm::InitiateManagement
virtual void InitiateManagement(void)
Kicks off the farm's management.
Definition: farm.cpp:1514
AnimalFarm::decreaseCrops
virtual void decreaseCrops(vector< CropSort >cropsToDecrease, double &howMuchToDecrease)
Decreases area of cropsToDecrease by howMuchToDecrease.
Definition: farm.cpp:7931
l_emaize_price_file
static CfgStr l_emaize_price_file("EMAIZE_PRICE_FILE", CFG_CUSTOM, "EM_price.txt")
tof_UserDefinedFarm12
Definition: farm.h:249
OptimisingFarm::OptimiseFarm
void OptimiseFarm(int a_foobar)
Carries out the whole farm optimisation.
Definition: farm.cpp:5765
UserDefinedFarm18
A farm that can have its rotation defined by the user at runtime.
Definition: farm.h:1431
HunterInfo::FarmHuntRef
vector< int > FarmHuntRef
The hunter's is the farm reference number to where he hunts.
Definition: farm.h:520
ConventionalCattle::ConventionalCattle
ConventionalCattle(FarmManager *a_manager)
Definition: farm.cpp:1982
Crop::SimpleEvent_
void SimpleEvent_(long a_date, int a_todo, bool a_lock, Farm *a_farm, LE *a_field)
Adds an event to this crop management without relying on member variables.
Definition: farm.cpp:312
tof_UserDefinedFarm28
Definition: farm.h:265
tov_NLCabbageSpring
Definition: tov_declaration.h:105
DataForOptimisation::Get_livestockTypes
TTypesOfAnimals Get_livestockTypes(int i)
Definition: farm.h:598
FarmManager::m_cropTotals_sum
vector< double > m_cropTotals_sum
Stores the sums of crops areas within one simulation at the landscape level.
Definition: farm.h:1941
FarmManager::Set_crops_summary_BIs
void Set_crops_summary_BIs(int i, double BI)
Definition: farm.h:1856